text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
This will be useful for IncludeCleaner.
thanks, LG in general, just a couple polishing touches
this returns true even after inserting mainfile id, is that intended? I suppose it won't hurt too much, but means we'll go one step further for macros.
can you lift the isSelfContainedHeader into SourceCode.h and make use of it in both places (while updating the signature to accept a PP, through which you can access the SM).
we already have access to SM from the members, can you do the same for PP (stash as a member during construction) rather than plumbing at each call?
is this part of the check even relevant? let's drop this completely?
maybe make this an UnorderedElementsAre, do we have any ordering guarantees in this API's contract?
The ReferencedFiles is designed to make add() as cheap as possible, and do any per-file logic after folding the fileIDs together.
This keeps that loop tighter and also isolates the complexity of the symbol vs file logic.
Any reason we can't do that here?
Address review comments.
In D114370#3148143, @sammccall wrote:
The ReferencedFiles is designed to make add() as cheap as possible, and do any per-file logic after folding the fileIDs together.
This keeps that loop tighter and also isolates the complexity of the symbol vs file logic.
Any reason we can't do that here?
Good point, thanks!
This comment seems a bit unclear:
Maybe something like:
// If a header is not self-contained, we consider its symbols a logical part of the including file.
// Therefore, mark the parents of all used non-self-contained FileIDs as used.
// Perform this on FileIDs rather than HeaderIDs, as each inclusion of a non-self-contained file is distinct.
it seems like we'd be better off storing the "is-self-contained" in the IncludeStructure and looking up the HeaderID here rather than asking the preprocessor. That way we rely on info that's better obtained at preamble build time.
This helper checks e.g. for "don't include me", which is going to read source code of preamble files - we shouldn't do that, it's too slow and racy to do for every file in the preamble.
(It would be nice to handle those cases at some point, if we want to do that we need to do it at preamble build time and record the results in the IncludeStructure)
Resolve most comments.
I am slightly confused: we don't really have the IncludeStructure here and it is logically detached from the IncludeStructure processing. We'd still have to unroll the chain of FIDs in here, so the only difference would be querying IncludeStructure data for the cached isSelfContainedHeader value, is that right? Why is obtaining that info at preamble build time better?
the call-site has access to ParsedAST, hence the IncludeStructure. I believe the main reasoning behind Sam's suggestion is performing these lookups once while building the preamble and sharing it afterwards (we can even do the IO there).
no need for static here (and other places below)
i'd suggest AllowIO rather than ExpensiveCheck
can you also delete this and the other helpers?
looks like a debug artifact
Resolve review comments. This turned into a rather large refactoring change.
Untangle BeforeExecute call ordering change.
Thanks, this mostly LG now.
I'd consider splitting out the new infra change (IncludeStructure) from the feature change (include-cleaner treatment).
In case the latter causes some problems...
nit: at the file exit time -> at file exit time
Why redundantly track this on Inclusion? It's already available via IncludeStructure.SelfContained.contains(*HeaderID)
Maybe it's neater just to pass the CompilerInstance& - there's no other practical way to use this.
I think i'd prefer to see this private with an isSelfContained accessor, because the representation isn't the only sensible one.
Case in point: almost all headers in practice are self-contained, so in fact storing the set of non-self-contained headers seems preferable.
these helpers are 1000 lines away from the only place they're used, please move them closer
This still doesn't really describe the situation:
I'd rather say:
"This scans source code, and should not be called when using a preamble.
Prefer to access the cache in IncludeStructure::isSelfContained if you can."
Address review comments. Next step: split this patch into two, as suggested.
Leave the feature changes (IncludeCleaner bits) out of this patch
[clangd] IncludeCleaner: Attribute symbols from non self-contained headers to their parents
When a symbol comes from the non self-contained header, we recursively uplift
the file we consider used to the first includer that has a header guard. We
need to do this while we still have FileIDs because every time a non
self-contained header is included, it gets a new FileID but is later
deduplicated by HeaderID and it's not possible to understand where it was
included from.
Change base to D114370.
Get the changes back to this patch.
Thanks!
could consider friend class RecordHeaders, either is ugly, up to you
That was the original problem I had the public field in the previous iteration: RecordHeaders is defined in anonymous namespace, so IIUC I can not friend it from here unless I make it a subclass or somehow visible from here, otherwise it wouldn't work, would it? Is there any clean way to do the friend here?
No, you need to move it out of the anonymous namespace. Which is part of the ugliness, though not harmful in practice.
(If you're worried about namespace pollution you can make it a nested class of IncludeStructure. You have to forward declare it in the header. In that case you don't have to friend it)
Get rid of the setter in IncludeStructure.
I see, thanks! | https://reviews.llvm.org/D114370 | CC-MAIN-2021-49 | refinedweb | 976 | 63.8 |
Basic CS Interview Guide
Introduction
Topics
Technical interview questions come in a few categories. These include
- Fizz-buzz like questions to check if you're a minimally competent programmer
- Behavioral questions, both about previous experiences, and what actions you'd take in certain situations
- Hard-core technical design and coding questions involving algorithms and data structures
This guide will be primarily concerned with the latter two points, with heavy emphasis given to the last point. This guide assumes minimal competency with programming.
Choice of Language
You should first and foremost choose a language used at the company. If the company uses multiple languages, the highest level language should be used. If there are multiple high level languages (such as Python, Ruby, and CoffeeScript), you should choose the one you are most comfortable in.
Applicants interviewing with higher-level languages tend to have greater success on average than those with lower-level languages. This is because with higher-level languages one needs to write less, there are fewer opportunities to introduce bugs, and it's often less mental effort. There are certainly exceptions; if you're interviewing to write device drivers, you had better exhibit proficiency with lower-level languages!
This guide will have code written in Python, as this is the language I am encouraging my friend to use (and happens to be my favorite interview language.)
Behavioral and social aspects
I won't speak a lot to this extremely important aspect of interviews simply because I don't think I'm very qualified to. With that said,
- Don't argue with and upset the interviewer. I've seen this happen. Not pretty.
- Act natural, confident, and look your interviewer in the eyes.
- Smile when appropriate, and treat your interviewer as you would a coworker.
- Don't panic or act nervous. This is not good.
- When solving a problem, talk out loud. Whether you know exactly what to do, or have no idea what to do, the interviewer doesn't want to see your solution so much as they want to see your problem solving process.
- If you have seen an interview question before, tell the interviewer. This shows honesty.
- If you have no idea how to do a question, don't panic, and just start talking through it. Again, don't panic or get nervous, your job is not to solve the questions, it's to think through them.
The last point is extremely important. Often, interviewers will give you extremely hard questions which you have often no chance of solving. They know this, and do it to gauge how you work under pressure. Remember,
- Don't panic.
- Don't be nervous.
- Talk through the problem.
- Don't be afraid to ask for help if you're stuck.
Behavioral questions
Of the questions companies ask, these are often the hardest. Some examples are
- "What was the hardest bug you've encountered, and how did you fix it?"
- "Did you ever have disputes with your coworkers or boss? If so, about what, why, and how did you resolve them?" * The only way to prepare for these is to try and think of some potential classes of questions and have anecdotes relating to them. If you lack experience, don't say nothing or make something up. It's much better to tell the interviewer the truth; that you don't have a development experience which would give them a meaningful answer to their question.
Purpose and Citation
The purpose of this guide is to help one of my friends prepare for an interview at Google. Much of the material I have read to produce this guide is from the University of Michigan EECS 281 slides produced by professors David Paoletti and Don Windsor. I will never copy the material verbatim, but the organization of the guide may reflect the organization of the class. With that said, if anyone takes issue with the content of this guide, please contact me at [email protected], and I will be happy to review your request and make edits if necessary.
Technical Interview Questions
Many of the interview questions you'll experience fit into a few broad categories:
- Complexity analysis
- Choosing and implementing various algorithms
- Choosing and implementing various data structures
- Higher-level design questions
- General problem solving
I will touch on all of these, but focus on algorithms and data structures.
Complexity Analysis
Why does this matter?
Runtime of a program is affected by a number of things, including how good the programmer is, how fast the computer running the program is, and how the program was compiled. At companies like Google, we can assume that the program implementation is close to optimal, that computer power is no issue, and that the compiler is excellent. So then what does affect the runtime of a program? Algorithms.
In a lot of projects, the choice of certain algorithms, like sorting, might not make a significant difference in the user's experience. Who cares if a sorting algorithm takes 1ms or 20ms? But this is not the case with Google.
If you want to analyze tens of billions of emails, trillions of webpages, have cars drive themselves, or machines identify cat videos, algorithms do matter. In fact, they matter a lot more than compilers, programmers, and CPU speed put together. Choice of algorithms might not make a difference a lot of situations, but with the interesting problems, they certainly do. Which is why Google certainly will ask you about them. And they'll most likely ask you to do complexity analysis.
How do you measure input size?
Number of items is the most common way to measure input size, but sometimes it's better to be more specific or less specific. For instance, if you have a graph, it's common to measure algorithmic complexity in terms of vertices and edges, and sometimes it's more common to measure algorithmic complexity in bits. Just use common sense with regard to the problem at hand.
Why don't we just measure steps done?
There are a few problems with conducting runtime measurements like this. The first is that due to differences in compilers and instruction set architectures, this is not a reliable count of the actual instructions run by the processor. Secondly, it's not trivial to count the number of cycles executed for a single, known input, much less every possible input. It's much more worthwhile to measure runtime growth in terms of input size; this is the essence of Big O notation.
Big O Notation
It's best if you already know the mathematical foundations of this. Just remember, saying an algorithm is O(n) is saying that, at the very most, the runtime grows proportionally to n. Note that an O(1) algorithm is also O(n). Likewise, big omega is a lower bound, and big theta is an asymptotically tight bound.
Some common complexity classes include
- O(1), or constant
- O(log n), or logarithmic
- O(n), or linear
- O(n log n), or loglinear
- O(n^2), or quadratic
- O(c^n), or exponential
- O(n!) or factorial
- O(2^2^n), or doubly exponential
Big O notation can measure best case, worst case, and average case of performance (based on input case.)
Amortized complexity is a type of worst case complexity that can be considered an average complexity. For instance, with a phone card, you pay $20 up front, but you may be paying an average of 15 cents per minute. Likewise with the C++ STL vector, you may have O(1) complexity for the push back operation 99% of the time, but when it needs to expand, it takes log linear time. Even though this operation's worst case is log linear, we can say it's amortized O(1).
Pseudocode
Algorithms are often described in pseudocode, a language resembling Python code written when the author has a high blood alcohol level.
Recursion
Recursion is a handy tool for discovering new algorithms, as well as quick implementations of other algorithms. In reality, the performance of a recursive algorithm is often lower than its equivalent iterative version. Remember, every recursive function can be converted to an iterative function with the use of a stack.
Dafuq is a stack?
Stacks
A stack is a last in, first out(LIFO) data structure. It supports three operations: looking what value is on the top of a stack, popping the top value of a stack, and pushing a new value onto the top of the stack. This is commonly implemented as an STL vector(using the
myVec.push_back(),
myVec.back(), and
myVec.pop_back() methods), or in Python, an array, with
myArray.append(),
myArray.pop(), and
myArray[-1].
myStack = [] myStack.append(5) myStack.append(10) print(myStack.pop()) #prints 10 print(myStack[-1]) #prints 5
There are awesome animations of data structures online. I don't have the link offhand, but I wish I had that resource when doing 281. Google "Visualizations of Algorithms and Data Structures", and the correct site has a color scheme containing green and animation so many algorithms and data structures. I sent you the link before.
So what does this have to do with recursion?
Well, for one, they are how the computer runs recursive functions. In memory, there is a region designated as the program stack, filled with stack frames. A stack frame is a section of memory which holds the state of the program when a function call is made. All local variables, argument variables, and return values all get pushed on and popped off of the stack.
Here we have our dilemma; every recursive call to a function results in the allocation of a new stack frame. This takes time and memory. Every call results in the allocation of new local variables and arguments, which takes a lot of memory. In addition, there is only one program stack per thread, and they tend to be fairly limited in size. If you push too much onto the stack, it will overflow.
So what can you do to keep the behavior of a recursive function without the performance and memory penalties? Allocate a stack on the program heap of course(when you do calls to
new() and
malloc() you allocate memory on the heap.) If you save the appropriate data on your heap-based stack, the algorithms will perform identically, and your new version will be much faster.
Solving recurrence relations
I won't speak about recurrence relations, including solving them with telescoping or the Master theorem here, as odds are you won't be asked to solve a recurrence relation. It's good to have this math background though in case they do though.
As a side note, I'd recommend learning how to solve the Fibonacci sequence in O(log n) time though with the closed form solution, which I have heard come up in interviews multiple times.
Linked lists
These aren't so common in Python, but in C++ they're used a lot. All you have to know is that these are used to implement variable length arrays. A linked list is composed of a series of nodes, where each node contains a value, as well as a pointer to the next element(and sometimes to the previous element). To add a new element, you allocate a new node on the heap, set the list's last node's next pointer to point to the new element, and the new node's previous pointer to point to the former last element. The nice thing about Python is you don't have to worry about this :)
(As a side note, C++ has this functionality in std::list. Vectors are always stored contiguously in memory, and if space runs out, it is reallocated, expanded, and copied to the new location.)
Standard Libraries
Learn the standard library of the language of your choice. This will help you by allowing you to avoid the process of implementing data structures and common algorithms by yourself, instead providing you with high quality implementations.
Queues
A queue is very similar to a stack, in that it also supports the operations
put()(I called it
push() before, but it's called
put() in Python) and
get()(a.k.a.
pop()), but instead of the most recent items getting popped, it's the first items which were pushed on that get popped out(first in, first out, or FIFO.) Python has these in its standard library in the Queue module. To declare one, do
import Queue myQueue = Queue.Queue() myQueue.put(5) myQueue.put(10) front = myQueue.get() print(front) #is 5
You can also implement a stack-like LIFO data structure using Queues too, using
Queue.LifoQueue() in Python.
Priority Queues
A priority queue is a queue with a special property: each element is assigned a priority. In max-priority queues, the element with the highest priority is returned first. In min-priority queues, the element with the lowest priority is returned first. By default, the
Queue.PriorityQueue() in Python is a minimum priority queue. In Python, you can push anything that can be sorted on a priority queue. A common pattern is to push a tuple like
(priority, value) (remember, tuples are immutable, so if you need to change the priority, you need to completely replace it with a new object). Python sorts refer to the first object in a tuple, then if there is a tie, the second, etc (this is the way strings are compared as well.)
For more information on the Queue class, see the Python documentation.
So what about the complexity? If we sorted upon every insert and removal, we'd have a worst case time complexity of both of those operations of O(n log n). However, it turns out with the Heap container, we can get that down to O(log n). I'll talk about this later.
Deques
This is a funny one. It's a data structure that supports both pushing and popping from both ends.
Container Types
There are ordered and unordered containers. The main difference is that you can use binary search for O(log n) finds on sorted containers (as opposed to O(n) on ordered containers.) Consequently, addition and removal are slower on sorted containers compared to ordered containers( you can't simply append on sorted containers.)
Sets
Sets in Python are collections of unique, hashable objects(if you don't know what a hash is, I'll explain it right now.
Hash tables
Hash tables are arguably the most important data structure known to man. Unlike sorted containers which allow O(log n) lookup, these allow O(1) lookup. How do these data structures which are the programming equivalents of unicorns work?
The underlying data structure of a hash table is an array in memory. You have two other components: the hashing function, and the collision resolution scheme.
Hash functions
All a hash function does is turn a value into an array index. The hash function in turn is composed of two parts.
The first part, the hash code, takes a value and returns an integer. A function that always returned zero would be a hash coding function, but it would be a terrible one. More terrible ones include adding the ASCII values of a string together, multiplying the digits of a number, etc. A good hashing function minimizes the chance of a hash collision; a hash collision is when two distinct values have the same hash code. Good hashing functions, like SHA-256, have extremely small probabilities of hash collisions. I've heard that it's much more likely that a giant asteroid will impact the earth than a collision of SHA-256 ever happening in the wild. The second part of hash functions is the compression mapping. All this does is maps the integer to an array index using the modulus operator and the length of the underlying array.
A good hash function should be extremely fast to compute. Cryptographic-strength has functions often are relatively slow to compute, so faster ones are used that have higher collision rates. So how do we manage collisions?
Hash Collision Resolution
There are four methods of hash collision resolution I will talk about. These are
- Linear probing
- Quadratic probing
- Separate chaining
- Double hashing
Linear Probing
If a hash collision occurs(that is, if the value at the index returned from the hash function is different than the hashed value), the probe goes to the next element in the array. If an empty position in the array is found, the element is inserted there. Searching operates much the same way.
To remove an element, the most efficient way is to mark it as "deleted", and maintain the positions of all of the other elements in the array. Otherwise, you'd have to rehash all of the elements in the array to avoid erroneous misses.
Quadratic Probing
Quadratic probing is like linear probing, but instead of the probe moving linearly, it moves quadratically increasing distances away from the collision. This provides a more even spread of elements across the hash table (linear probing tends to have a lot of clustered elements, which decreases the efficiency of the hash table.
Double hashing
If a hash collision occurs, the hash function is reapplied to the hashed value. This is not a recommended method, as during lookup, each element must be hashed up to twice. In addition, if your hashing function returns 0 every time, you might get an infinite loop. Sucks.
Separate Chaining
This is a very common method of collision resolution. Instead of values being placed directly in the underlying array, each array index holds another array. Each insertion to the table just expands the subarray. During lookup, the subarray is linearly searched, resulting in a worst case time complexity of O(n) lookup. In practice, it's much better.
A great hash table will have a low load factor. What is load factor? Load factor, represented by a lowercase alpha, is equal to N/M, where N is the number of keys placed in an M sized table. For separate chaining, this is equal to the average number of elements in each subarray. For probing, it's the percentage of table positions occupied. That's pretty much all you need to know about hash tables!
Sets, continued
Back to sets! So in Python, sets are hash tables. To iterate over them, the computer just takes your underlying array, and iterates over the elements which are set. To see if an element is present, it just looks up the hash of the element and see if the corresponding array position contains an element. Note, in C++ STL, these are implemented with sorted containers, and have O(log n) lookup time.
As a side note, Python's dict class is also implemented with hash tables.
Sorting
I'm too lazy to write this section, as I learned sorting by looking up GIFs on Wikipedia. To learn it I suggest that you use the 281 lecture #10 and that really awesome data structure and algorithm visualization website. It won't take you long, I promise. But first, read the rest of this section, as well as the heap section, as it will help with heap sort.
There are some other things worth briefly saying about sorting. They all have distinct advantages; know when it's best to use sorts (for instance, insertion sort is really good to use when you need to put a new element into a list, bubble sort is greater for lists that are almost totally sorted, etc). Also, the theoretical limit for comparison based sorts is O(n log n), but bucket sort and radix sort can do better than O(n log n), which is pretty cool.
Learn these really well, as many many interview questions depend on them. Know how to implement AT LEAST binary, insertion, quick, merge, heap, and binary, and bucket sort and radix sort will impress people. For details about heaps and heap sort, look below as well.
Heaps
What if you wanted a data structure that allows you to easily and quickly pop the most extreme element? Heaps allow you to do just this.
They often use binary trees as their underlying data structure.
Trees
Trees are really important data structures. Go look at 281 lecture 11. Binary search trees are also important to learn, look at 281 lecture 16.
AVL trees are basically balanced binary trees. These aren't important to learn for interviews, but they're fairly easy to understand so you might as well. Let me teach these to you in person.
Heaps in Python
Priority Queues. Nuff' said.
Graphs
These are really hard to explain well without pictures. To learn them, look at the 281 slides from 20 and up in conjunction with the data structures and algorithms visualization site. I think you already have a pretty good background due to 203.
The rest of 281 material(only like 4 lectures or so)
This is the advanced stuff that puts all of the other stuff together. Read over this, don't spend time on anything if you don't understand it, and ask me about it when I get back.
If you've made it through this guide and aren't totally confused, pat yourself on the back! You've compressed most of the material taught over 3.5 months into a small document! You probably don't understand all of the material, but that's alright, that's what Google is for.
How do you effectively use the knowledge above to do interview questions?
When you get an interview question, first make sure you've fully understood the problem. Getting the correct idea of what the interviewer is asking is most of the battle once you know algorithms and data structures, so ask for clarification throughout the process about the question itself, limitations, edge cases, etc.
Once you have a basic idea of what the question is, then choose the right algorithms and data structures for the task. Make sure to tell the interviewer why you chose them(read: tell them the big O complexities, this will impress them.) Then, it's just a matter of putting it together with code.
Style
Write very small functions which are easy to understand (unless time is REALLY an issue, in which case, do whatever is fastest). Premature optimization is the root of all evil. Those basically are the only two things you have to worry about in these questions.
Where do you go from here?
Practice. Practice more. Practice more than that. The more you get used to the process, the easier that it becomes.
Learn fancy data structures and algorithms. Learn Bloom filters (these allow constant time set intersections, which is pretty badass, among other things). The wider your knowledge about crazy data structures and algorithms, the more you'll potentially impress the interviewer. The best is mentioning a great data structure the interviewer has never heard of. This basically guarantees you'll do well.
Expand your knowledge of Python and other languages. The more fluent you become, the easier the interview becomes, until it becomes basically effortless.
Learn optimization techniques. This requires a knowledge of the EECS 370 stuff, as when you know how the processor works, you can often tune your programs to take advantage of the architecture. Mostly, this is just exploiting spatial locality, memory organization(the order of variables in a struct matters), and knowing what operations take a lot of cycles. Don't worry about this too much for now.
Most importantly, do side projects. With good side projects, you can nail the behavioral questions, and often bypass the technical interview (and everything else about the interview process for that matter.)
Finally, relax. If you know the material, do the stuff recommended in the guide, and put in a bit of interview practice, you'll ace most of them. If you totally bomb a part of the interview, don't let it affect you, most other people probably did too, and you'll still probably get the job(you won't if you make a big deal out of your mistakes.)
Michael 12/22/2013 | https://devhub.io/repos/schmatz-cs-interview-guide | CC-MAIN-2019-39 | refinedweb | 4,047 | 63.49 |
I’m trying to play with Parallax and getting some weird bugs, wondering if anyone can add some input to it. The only app I’ve seen implement parallax effectively is soundcloud. It’s quite subtle, but each item has an image background and it has he parallax effect as you scroll. I’ve created a custom RecyclerView to […]
I hacked together my first app from a bunch of tutorials. With the help of one of them I implemented a RecyclerView inside a fragment which is used by the main activity. Now I found another tutorial which I want to use to implement multi-selection with the contextual action mode. The big problem is, that […]
I have some problems understanding RecyclerViews SortedList. Lets say I have a very simple class only having a very simple class holding data: public class Pojo { public final int id; public final char aChar; public Pojo(int id, char aChar) { this.id = id; this.aChar = aChar; } @Override public String toString() { return “Pojo[” […]
I am new to recycler view. My requirement is as follows: – I have to call a web service that will give two arrays. One with data I need to show in the list. For this purpose, I am using RecyclerView. The other array is of statuses, which I am showing in spinner. This web […]
The app has data in a SQLite database. The UI is primarily a RecyclerView. The question is how to best to transfer data from the database into the UI, whilst keeping off the main thread? I originally planned to use a CursorLoader, ContentProvider, and RecyclerView. But reading around it looks like RecyclerView has no out-of-the-box […]
I have a RecyclerView with Expandable Child Views, when the child ViewGroup is clicked it inflates an amount of views animating the ViewGroup height from 0 to the measured viewgroup height, like the following gif: The problem is: I’m calling smoothScrollToPosition on recyclerView, it smooth scroll to the view position, but it considers the current […]
Is there any way to redraw all items of RecyclerView? I have some Themes (in style.xml) and after changing the theme, I need the RecyclerView to be redrawn. So I want a method that will force to re-call onCreateViewHolder for each items of the adapter. I tried to: call adapter.notifyDataSetChanged but onCreateViewHolder is not called […]
I have a recylcler view, but it seems that does not implement the setGravity method. My list is horizontally aligned, but I need it to be centered. How do I do that? fragment_my_zone_item_controlled.xml <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”” android:layout_width=”match_parent” android:layout_height=”match_parent” android:background=”@color/dark_grey”> <FrameLayout android:id=”@+id/fragment_my_zone_item_controlled_content” android:layout_width=”match_parent” android:layout_height=”match_parent” android:layout_below=”@+id/fragment_my_zone_item_controlled_tabs” android:layout_marginBottom=”12dp” android:layout_marginTop=”12dp” /> <android.support.v7.widget.RecyclerView android:id=”@+id/fragment_my_zone_item_controlled_tabs” android:layout_width=”match_parent” android:layout_height=”44dp” android:background=”@color/action_bar_color” android:scrollbars=”none” […]
I want to build a message layout as in whatsapp. I have an edittext and a recylerView. the problem is when the keyboard appear it hide the messages ! So lets say this the RecylerView: —item 1— —item 2— —item 3— —item 4— —EditText— when the the keyboard appear , I get this : —item […]
I have implemented Admob native ads in my application. It has been placed to display once for every 4 items in my recyler view. The problem is before ads are being displayed, a blank space will be shown up for around 3 to 5 seconds til the ad is loaded. I need help to remove […] | http://babe.ilandroid.com/android/recyclerview/page/10 | CC-MAIN-2018-26 | refinedweb | 597 | 55.34 |
Pass function through the QML ListModel
import QtQuick 2.4 import QtQuick.Controls 1.1 Item { Column { TextArea { id: txt height: 20 } Repeater { model: ListModel { Component.onCompleted: { append({index: 0, f: function() { txt.forceActiveFocus() }}) } } Component { id: d Button { text: "btn" } } delegate: Loader { sourceComponent: d onLoaded: { item.onClicked.connect(f) } } } } }
The button, generated from a ListModel, should be able to trigger an invokable that is specified in the model. How to do that?
This example should get TextArea focused when the button is clicked. Instead, it gives: 'Error: Function.prototype.connect: target is not a function'.
(In the real example, there is a C++ object with Q_INVOKABLE instead of TextArea. And the ListModel has a couple of additional fields and functions to pass.)
- p3c0 Moderators
Hi @devel,
AFAIK
ListElementroles cannot have scripts as its values.
Values must be simple constants; either strings (quoted and optionally within a call to QT_TR_NOOP), boolean values (true, false), numbers, or enumeration values (such as AlignText.AlignHCenter).
ListModel.append()was a workaround to overcome this limitation: at least the
ids can be passed with it.
I'm going to pass the
Actionobjects there instead of plain functions for now. | https://forum.qt.io/topic/67498/pass-function-through-the-qml-listmodel | CC-MAIN-2018-39 | refinedweb | 193 | 51.75 |
Your answer is one click away!
I am using Grails excel import plugin to import an excel file.
static Map propertyConfigurationMap = [ name:([expectedType: ExcelImportService.PROPERTY_TYPE_STRING, defaultValue:null]), age:([expectedType: ExcelImportService.PROPERTY_TYPE_INT, defaultValue:0])] static Map CONFIG_BOOK_COLUMN_MAP = [ sheet:'Sheet1', startRow: 1, columnMap: [ //Col, Map-Key 'A':'name', 'B':'age', ] ]
I am able to retrieve the array list by using the code snippet:
def usersList = excelImportService.columns(workbook, CONFIG_USER_COLUMN_MAP)
which results in
[[name: Mark, age: 25], [name: Jhon, age: 46], [name: Anil, age: 62], [name: Steve, age: 32]]
And also I'm able to read each record say [name: Mark, age: 25] by using usersList.get(0)
How do I read the each column value? I know I can read something like this
String[] row = usersList.get(0) for (String s : row) println s
I wonder is there any thing that plugin supports so that I can read column value directly rather manipulating it to get the desired result.
Your
usersList is basically a
List<Map<String, Object>> (list of maps). You can read a column using the name you gave it in the config. In your example, you named column A name and column B age. So using your iteration example as a basis, you can read each column like this:
Map row = usersList.get(0) for(Map.Entry entry : row) { println entry.value }
Groovy makes this easier to do with
Object.each(Closure):
row.each { key, value -> println value }
If you want to read a specific column value, here are a few ways to do it:
println row.name // One println row['name'] // Two println row.getAt('name') // Three
Hint: These all end up calling
row.getAt('name') | http://www.devsplanet.com/question/35274094 | CC-MAIN-2017-22 | refinedweb | 278 | 57.67 |
The canonical way to build & bundle a Vue.js application is with webpack, and indeed, pretty much everything Vue-related assumes that you’ll be using webpack. However, you don’t have to. You could use Vue.js without build tooling, or you could use an alternative module bundler. It’s almost a joke at this point that configuring webpack can be quite a mystical journey, but it’s not the only option in town. The new kid on the block at the moment is ParcelJS. It basically fills the same role as webpack, but operates as a zero-configuration tool. You simply install the dependencies and run
parcel build, and out comes a perfectly bundled app.
So, let’s take a look at how to set up parcel for a Vue.js app.
📚 Recommended courses ⤵Push your Vue.js skills to the next level with Vue School’s video courses
Writing the App
In contrast to our usual steps, let’s go ahead and set up the skeleton app files before we do anything else.
In your project directory, create a new directory called
src. (The final file structure will look something like this:)
./my-project ├── package.json // Generate this with `npm init` ├── index.html ├── .babelrc // Babel is needed. └── src ├── App.vue └── main.js
Start off with your typical basic
index.html.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>My Vue.js App</title> </head> <body> <div id="app"></div> <!-- Note the reference to src here. Parcel will rewrite it on build. --> <script src="./src/main.js"></script> </body> </html>
Then add the Vue bootstrap code.
src/main.js
import Vue from 'vue'; import App from './App.vue'; new Vue({ el: '#app', render: h => h(App) });
And now the
App component.
src/App.vue
<template> <div id="app"> <h1>{{ msg }}</h1> </div> </template> <script> export default { name: 'app', data () { return { msg: 'Welcome to Your Vue.js App!' } } } </script> <style lang="css"> #app { color: #56b983; } </style>
Throw in
.babelrc as well too, just for good measure.
.babelrc
{ "presets": [ "env" ] }
Adding Parcel
Setting up Parcel is as simple as installing a few dependencies.
First, let’s install everything we need for the Vue app itself.
# Yarn $ yarn add vue # NPM $ npm install vue --save
Then parcel, a plugin for Vue, and
babel-preset-env…
# Yarn $ yarn add parcel-bundler parcel-plugin-vue @vue/component-compiler-utils babel-preset-env -D # NPM $ npm install parcel-bundler parcel-plugin-vue @vue/component-compiler-utils babel-preset-env --save-dev
Now… well, that’s it actually.
Running Parcel
You should now be able to run your app in development mode with hot reloading by running
npx parcel in your project directory. To build for production with minification and dead code elimination, just use
npx parcel build.
(If you’re wondering what
npx is, take a look here. It should just work as long as you have
NPM 5.2.0 or newer installed.)
But what if I want
eslint?
I’m glad you asked. In that case, go ahead and install
eslint,
eslint-plugin-vue, and
parcel-plugin-eslint.
# Yarn $ yarn add eslint eslint-plugin-vue parcel-plugin-eslint -D # NPM $ npm install eslint eslint-plugin-vue parcel-plugin-eslint --save-dev
(Don’t forget to create your
.eslintrc.js)
.eslintrc.js
// module.exports = { extends: [ 'eslint:recommended', 'plugin:vue/essential' ] }
What about LESS / SASS / PostCSS?
They’re supported by Parcel out-of-the box! Even in Vue components! For more information about built-in asset types, take a look at the official Parcel documentation.
Want More Information?
Take a look at our more in-depth Parcel guide. Oh, and, as always, read the official documentation! Parcel’s is nice and short. | https://alligator.io/vuejs/vue-parceljs/ | CC-MAIN-2019-09 | refinedweb | 623 | 60.01 |
Handling NotifyStore Errors
Hello, I am new to backtrader I'm currently working on handle errors from TWS
I have created two variances of code which handles errors
Variance #1
def notify_store(self, msg, *args, **kwargs): if msg.errorCode == 502: print(msg.errorCode)
This variance only works when the error exists for example if TWS is not running. If it is running it will produce an error
AttributeError: 'ManagedAccounts' object has no attribute 'errorCode'
Variance #2
def notify_store(self, msg, *args, **kwargs): try: if msg.errorCode == 502: print(msg.errorCode) # Do Something to handle error except AttributeError: # Error is not found print("No Error")
Is there a better way to handle if the error doesn't exist? using Attribute Error feels too broad
you could check if msg has the attr set:
if hasattr(msg, 'errorCode'): # check for error code
Awesome function, I didn't know this existed.
is there any difference between these two designs?
def notify_store(self, msg, *args, **kwargs): if hasattr(msg, 'errorCode'): if getattr(msg,'errorCode') == 502: # Do Something pass
def notify_store(self, msg, *args, **kwargs): if hasattr(msg, 'errorCode'): if msg.errorCode == 502: # Do Something pass
getattr gives you more options. so you could do something like:
error = getattr(msg, 'errorCode', False)
which would prevent the AttributeError exception, if no errorCode is set. In that case, you will get False as the result.
By accessing attributes directly, you would need to ensure, that the attribute you access is available or catch the AttributeError exception, so you know, the attribute is not set.
With hasattr() you can check for the existance of a attribute.
In your example, both solutions do the same.
you could do also this:
def notify_store(self, msg, *args, **kwargs): error = getattr(msg,'errorCode', False) if error: # Do Something | https://community.backtrader.com/topic/2897/handling-notifystore-errors/1 | CC-MAIN-2021-43 | refinedweb | 296 | 54.22 |
Investors eyeing a purchase of Salesforce.com Inc (Symbol: CRM) stock, but tentative about paying the going market price of $73.39/share, might benefit from considering selling puts among the alternative strategies at their disposal. One interesting put contract in particular, is the January 2019 put at the $40 strike, which has a bid at the time of this writing of $1.94. Collecting that bid as the premium represents a 4.8% return against the $40 commitment, or a 2.4% annualized rate of return (at Stock Options Channel we call this the YieldBoost ).
Selling a put does not give an investor access to CR Salesforce.com Inc sees its shares decline 45.5% and the contract is exercised (resulting in a cost basis of $38.06 per share before broker commissions, subtracting the $1.94 from $40), the only upside to the put seller is from collecting that premium for the 2.4% annualized rate of return.
Below is a chart showing the trailing twelve month trading history for Salesforce.com Inc, and highlighting in green where the $40 strike is located relative to that history:
The chart above, and the stock's historical volatility, can be a helpful guide in combination with fundamental analysis to judge whether selling the January 2019 put at the $40 strike for the 2.4% annualized rate of return represents good reward for the risks. We calculate the trailing twelve month volatility for Salesforce.com Inc (considering the last 252 trading day closing values as well as today's price of $73.39) to be 34%. For other put options contract ideas at the various different available expirations, visit the CRM Stock Options page of StockOptionsChannel.com.
Top YieldBoost Puts of. | https://www.nasdaq.com/articles/agree-purchase-salesforcecom-40-earn-48-using-options-2017-01-05 | CC-MAIN-2021-31 | refinedweb | 290 | 58.28 |
Hi Holger, On Mon, May 17, 2010 at 11:38:47AM +0200, holger krekel wrote: > What about rather doing a single clean 'sys.pypy' module namespace such > that we can do: > > a) hasattr(sys, 'pypy') > b) sys.pypy.version_info >= (x,y) > c) expose the __pypy__ builtin module as sys.pypy? > > Semantically, the sys module already presents an interaction > API with the interpreter. Doing a single namespace looks more > elegant to me than of cluttering sys with an artifical 'pypy_*' > prefixed namespace and having to (try-except)import __pypy__. You don't have to put the "import __pypy__" in a try-except, if you already checked that "__pypy__" in sys.builtin_module_names. But your solution looks clean, and the point a) becomes shorter too :-) I would like to avoid having the semi-internal interface of PyPy change nearly as much as, say, the one from the py lib one (and I'm not exagerating there: there are *6* different versions of "try: from py.internal.stuff import x" in my own conftest.py :-) . That said, your suggestion seems nice enough. Comments from others? A bientot, Armin. | https://mail.python.org/pipermail/pypy-dev/2010-May/005856.html | CC-MAIN-2016-36 | refinedweb | 184 | 64.61 |
I am doing two talks at the Win-Dev 2004 Conference on the Web Services track and the Databases and Data Access so if you are going to the conference or live in the Boston area and want to meet up to have a chat, drop me a mail. The talks are;
WS6 - Whidbey System.XmlMark Fussell
Microsoft's System.Xml proved to be revolutionary for working with XML in a variety of different ways. This innovation has continued in the new Whidbey release with various enhancements and new features that simplify development and increase flexibility. This session will introduce you to the various improvements found in Whidbey's System.Xml.
D4 - XQuery in SQL Server 2005 and System.XmlMark Fussell
XML brings with it some powerful query languages for dealing with the hierarchical format that it typical of an XML document. The newest and richest query language is known as XQuery. This talk provides an overview of the XQuery language and explores XQuery functions and XQuery DML inside SQL Server 2005. It also details the XQuery support in the .NET Framework as part of System.Xml namespace that enables the querying of XML sources stored outside of the database such as locally stored files or XML received via webservices. By combining queries over SQL Server 2005 and other XML sources XQuery can be used as a data integration language. | http://blogs.msdn.com/b/mfussell/archive/2004/10/05/237964.aspx | CC-MAIN-2015-48 | refinedweb | 230 | 63.8 |
Hi again! Not posting for too much long.
Well, this time we will explore the clojure’s ability to load arbitrary files as code.
This is such an amazing feature, but you should be careful. Don’t start reading anyones files and evaluating them into your app. Be wise and use it for specific situation like this: I wanted to load a bunch of configurations (and even funtion calls) depending on the environment my app is running.
To do the conditional evaluation, I decided to add an extra key to
:immutant entry in my project definition. The entry
:env is an arbitrary configuration value. Lets take a look:
(defproject tserver "0.1.0-SNAPSHOT" :description "A foo project" :url "" :license {:name "Eclipse Public License" :url ""} :dependencies [[org.clojure/clojure "1.4.0"] [compojure "1.0.2"] ;... and many other dependecies :jvm-opts ["-Xmx2g" "-server"] :immutant {:init "tserver.init/init"} ;; our custo immutant init function :profiles {:dev {:immutant {:context-path "/" :nrepl-port 4242 :lein-profiles [:dev] :env :dev}}}) ;:dev will identify which config file to load
In this sample
project.clj you find
:immutant directly under the project definition. This key is used to, regardless of the environment, inform immutant which funtion to call when your app starts up. In this case
tserver.init/init, that we will further analyze.
Pay attention to the
:env entry. It is located under
:immutant that is under
[:profiles :dev]. Here enters a leiningen’s profiles feature. Where you can even specify dependencies or anything you want by profile. In this case, the immutant config is being configured by profile.
Why not simply load a config per profile?
Because you can combine n profiles at the sime time. So, which one to use as the enviroment reference? That is why I decided to use an specific entry for that.
Below the initial function being called by immutant. Here goes intereting stuff. One of them is the use of
in-ns,
use and
require. This is awesome because I’m calling what could be “equivalent to a java import” in the middle of a clojure file, and even better: I’m doing this to another namespace that differs from the code that is actually calling the “imports”.
So,
in-ns will create the namespace
tserver.config and “import” the appropriate functions and namespaces.
The
init funtion here will simply call the
load-config, that is in charge of loading the config file. Look:
(ns tserver.init (:use [clojure.tools.logging :only (info error debug)])) (defn setup-config-ns [e] (binding [*ns* *ns*] (in-ns 'tserver.config) (refer-clojure) (use '[clojure.main :only (load-script)]) (require '[immutant.messaging :as msg] '[immutant.web :as web] '[immutant.util :as util]))) (defn load-config "Attempts to evaluate the specified env file defined by `:env` in the `project.clj`. `:env` is a immutant custom config. `:env` MUST be a keyword: Ex.: :dev, :prod :office Uses :dev by default. Note: The absence of the requrested file will prevent the server to start. These siles MUST be located at `src/tserver/config/%s.clj" [] (binding [*ns* *ns*] (in-ns 'tserver.config) (let [ev (get-in (immutant.registry/get :config) [:env] :dev) config-file (format "src/tserver/config/%s.clj" (name ev))] (setup-config-ns ev) (info "Using config file " config-file) (load-file config-file) (immutant.registry/put :env ev)))) (defn init [] ;;may do some stuff before (load-config)) ;;may do some stuff after
And finally, our config file containing the required configurations. It can be anything you need.
(defn handler [r] ((build-routes) r)) (web/start handler :reload true) (msg/start "/queue/delivery.status") (msg/respond "/queue/delivery.status" handle-delivery-status) (register-job #'import-job) (register-job #'check-import) ;register-job is function not provided here ;since the intention is tho show the configuration solution
Now, to deploy and start the app with the given profile we simply do:
lein with-profile dev immutant deploy lein immutant run
Voila! This will load your
dev.clj file and set up your queues, jobs, web-context, whatever you want. This is useful, and I would risk to say mandatory today. You probably have sereval environments where your app resides before going to prodution, and each of them with different names, addresses, pool sizes, queue names, database to connect, etc. And you can easily give to your app the intelligence to load what is more appropriate. | https://paulosuzart.github.io/blog/2013/02/07/configuring-clojure-immutant-by-environment/ | CC-MAIN-2021-21 | refinedweb | 732 | 60.31 |
The QTextLine class represents a line of text inside a QTextLayout. More...
#include <QTextLine>
The QTextLine class represents a line of text inside a QTextLayout.
A text line is usually created by QTextLayout::createLine().
After being created, the line can be filled using the layout() function. A line has a number of attributes including the rectangle it occupies, rect(), its coordinates, x() and y(), its textLength(), width() and naturalTextWidth(), and its ascent() and decent() cpos will be modified to point to this valid cursor position.
See also xToCursor().
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Returns the line's descent.
See also ascent() and height().
Draws a line on the given painter at the specified position. The selection is reserved for internal use.
Returns the line's height. This is equal to ascent() + descent() + 1.
See also ascent() and descent().
Returns true if this text line is valid; otherwise returns false. bounding rectangle.
See also x(), y(), textLength(), and width().
Lays out the line with the given width. The line is filled from it's starting position with as many characters as will fit into the line.
Lays out the line. The line is filled from it's starting position with as many characters as are specified by numColumns..
See also cursorToX().
Returns the line's y position.
See also x(), rect(), textLength(), and width(). | http://doc.trolltech.com/4.0/qtextline.html | crawl-001 | refinedweb | 234 | 70.29 |
Search network for HTTP servers using a regular expression filter
Project description
Search network for HTTP servers using a regular expression filter.
Use httpfind to obtain the IP addresses of specified devices on a network. HTTP requests for a user specified page are sent in parallel. Responses are compared against a user specified regular expression pattern. Qualified results are returned as a list. The module is readily imported for use in other projects, and it also includes a convenient command line interface.
Installation
pip install httpfind
Examples
Basic import example
import httpfind result = httpfind.survey( network='192.168.0.0/24', pattern='(A|a)ccess (P|p)oint', path='login.php', log=False) # Results printed as full URLs print(result) # Results printed as IP addresses print([x.hostname for x in result])
Yields
['', '', ''] ['192.168.0.190', '192.168.0.191', '192.168.0.192']
Command line example
$> httpfind -h usage: httpfind [-h] [-p PATH] [-f PATTERN] [-l] network Search 'network' for hosts with a response to 'path' that matches 'filter' positional arguments: network IP address with optional mask, e.g. 192.168.0.0/24 optional arguments: -h, --help show this help message and exit -p PATH, --path PATH URL path at host, e.g. index.html -f PATTERN, --filter PATTERN Regular expression pattern for filter -l, --log Enable logging $> httpfind 192.168.0.0/24 -f "Access Point" -p login.php Scanning, please wait ... Found 3 matches for Access Point on 192.168.0.0/24 192.168.0.190 192.168.0.191 192.168.0.192
Parameters
def survey(network=None, path='', pattern='', log=False):
- network - IP address and subnet mask compatible with ipaddress library
- path - Path portion of a URL as defined by url(un)split
- pattern - A regular expression pattern compatible with re.compile
- log - boolean to control logging level
Consequently, the network can be defined in either subnet mask (x.x.x.x/255.255.255.0) or CIDR notation (x.x.x.x/24). Presently, httpfind only scans networks of upto 256 addresses as shown in most of the examples. Of course, a single IP address may be specified either by x.x.x.x or x.x.x.x/32.
There are numerous resources for regular expressions, such as the introduction provided by the Python Software Foundation. For the simple cases, using the default or ‘’ will match any pages while a word such as ‘Access’ will match if it’s found in the returned HTML provided it’s the same case.
Performance
As discoverhue utilizes the excellent aiohttp package, requests are sent simultaneously rather than iteratively. More accurately, the requests are sent randomly over a 2.5s interval so as to not spike traffic. The timeout is set for 5.0s, so typical execution time is about 8.0s.
Contributions
Welcome at
Status
Released.
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/httpfind/ | CC-MAIN-2020-45 | refinedweb | 502 | 58.08 |
Using Reflection to Dump Objects
How to Use Reflection to Dump Objects
In this article, I will show how to write some .Net code to use a feature called "reflection" to generate a String containing values from all object fields. Please feel free to e-mail me for any comment or question regarding any detail or explanation about this source code.
First of all, what is reflection? Well, it is a set of classes defined in the namespace System.Reflection. With these classes (and mainly with static methods), at runtime, you can inspect any object without knowing its type and discover its methods, fields, properties, and constructors. Then, you can invoke these methods, read/write property (or field) values or create another object like the source one invoking the constructors.
What we are writing is a simple class named Dumper that will work in a very similar way. This is only a little sample of what is possible when you use reflection. Try to think about the other great potentials (and also to the security risks) of accessing every private field in any class not written by you (adding buttons to toolbars, changing forms layout, invoking private methods, and so on).
The following image shows the demo project output. As you can see, it is simpler than what you can see in Visual Studio, but it is quite useful if you think to implement some kind of logging in your applications. Simply, you can think to trap exceptions, display a generic error message to users, and then save detailed object data in some log file.
External Visible Interfaces
The Dumper class is the typical utility class. So, every method must be declared as static. This class must never be instantiated. For this motivation, we declare a protected empty constructor. If we don't provide a constructor, the compiler automatically adds an empty constructor invoking the Object constructor. We choose the protected modifier because we want to allow someone to inherit from our class. If the constructor is private, the class is not inheritable because there is no way for the child object to construct its father.
We provide dump features through an overloaded method called DumpObject. Mainly, it would be enough to pass it the object to dump but, seeing that an object can contain many other big objects hosting other objects and so on, it is better to also provide another version of this method where we can specify the maximum allowed nesting level.
Then, we will write some other methods basically used internally. The following image shows the Dumper class.
How the Dumper Works
Our starting point would be a class like the following one (Table 1):
As you can see, the DumpObject version with no maximum allowed nesting level will simply call the other version with a special parameter value (-1). The other version will do the following thing:
- It instantiates a StringBuilder object used to host the partially generated dump (rows 1 and 2). This is a better solution than using a String object because every time you append something to a String, a new String object is generated and the reference to the previous object is lost. This is a memory waste.
- Check whether the object to dump is a valid reference (rows 3-9)
- Call an internal function to physically dump the object (row 7).
Everything is summarized in the following code (Table 2):
The PrivDump function is shown next (Table 3):
Let's try to look at the code. Obviously, the algorithm must be recursive, so we have to insert a recursion termination check. If the object is null or if we have reached the maximum nesting level, we have to exit immediately (rows 4-7).
Then, we generate a padding string composed by many pipe symbols as the reached nesting level less one and a plus symbol (rows 8-14). This is done to build a string similar to the Visual Studio .Net tree structure. We append to the StringBuilder (rows 15-27) something composed by this padding string, the field name, the type name, and the string representation of the field (obtained calling the ToString method).
Here, we have to add another termination check. If we have a field that is a value type (in this simple class, we don't care about fields that are structs), we already have fully dumped it, so we can exit from the function (rows 28-29). In all the other cases, we have to call another internal function named DumpType. This function will retrieve every field of this object instance to make their dump (row 30).
Now, we have to print every field value for this object but from the parent class point of view. So (in rows 31-46) we obtain the base class type; if it is valid we call DumpType, passing it the same object but the parent class type.
Finally, there is the DumpType method (See Table 4).
This is our class core method. The first thing we have to test is whether this field is a delegate (row 4). A delegate is a typed function pointer. Obviously, we cannot obtain a delegate value, so we have to exit immediately.
In all the other cases, we obtain fields' information by invoking the GetFields method from the type. This method returns a FieldInfo array (rows 5-7). Here, we specify that we want to retrieve every field (public, protected, private, and static).
To dump the field values (rows 8-9), we can call the PrivDump method again passing to it the field value obtained by invoking the GetValue method from a FieldInfo reference.
If the object to dump is an array (rows 10-22), we have to dump every array cell by calling the PrivDump method.
How to Test Our Work
The code to test the class is very simple. You have to call the DumpObject method by passing a valid object as in the following code fragment (Table 5). | https://www.codeguru.com/csharp/csharp/cs_syntax/reflection/article.php/c5885/Using-Reflection-to-Dump-Objects.htm | CC-MAIN-2019-35 | refinedweb | 999 | 61.46 |
Details
Description
from
import re @outputSchema("y:bag{t:tuple(word:chararray)}") def strsplittobag(content,regex): return re.compile(regex).split(content).
Activity
- All
- Work Log
- History
- Activity
- Transitions
i forgot to svn add my unit test that contains a lot of useful tests and comments.
it's included in this patch. it has a timing loop at the end that you can enable by adding an annotation etc. or running it directly in eclipse etc. to show the performance difference between the methods.
I think this is a very good idea, it will make it easier to write python udfs.
The patch is like one that introduces several new API's. Each type conversion behavior introduced here will need to be retained to preserve backward compatibility. I think we should restrict the conversions to the cases where we are sure it makes sense (return either null+warning or error in other cases).
Review of 1942_with_junit.patch
- I think when the tuple schema and python udf return value are not compatible (for example when number of fields in schema are less than number of fields in object returned by udf), it should return null + warning. The case where the number of fields in object returned by python udf is fewer than ones in schema, null fields should be appended to new tuple to match schema.
- In JythonUtils.asBag, I am not sure if the automatic decision made for the type converting using contents of udf output object is worth the increase in complexity and potential for surprises. I think the user should wrap the 'list type' within another list type for the case when the schema represents a bag of tuples. ie do type conversions for only the cases where compatible == true.
- In JythonUtils.asBag, Why are the null values skipped ? This behavior is not consistent to behavior in other places in pig.
- Why does the patch do type conversions for non python datatypes ? Are these expected from python udf output ?
I think your feedback raises some fair questions, but I have some reasons for disagreeing:
wrt schema has fewer fields than actual:
this is a common case for me b/c pig doesn't allow specification of *-tuple i.e. all rows of data will have the same number of (int) elements, but it's not known how many. This is a week area of pig in general imho. If there is only 1 element in the tuple it can be seen to infer some type information for the remaining rows. (at least i think this is how 'tuple(int)' shows up). I think that when there are more than 1 columns in a tuple, then it's not a generic tuple, then i can see an error being appropriate. but for 1-tuples i appreciate the flexibility of using it for the type and writing udfs that accept tuples of arbitrary dimension, even if the args-to-function stuff is to simplistic to apply in this scenario it's easy enough to write useful udfs that utilize tuple dimension flexibility.
I am against the idea of returning null and WARN (nearly as a rule). I think a reasonable interpretation is always better than NULL (with WARN). I would only advocate for an actual error that forces a user to rectify their code. This may be where reasonable people disagree, but i think null rather than a tuple reflecting the returned data is less expected.
The whole reporting of 'schema != data' could be improved tho. I am not sure of the best way to reflect that anything "grey/WARN" is happening. It seems liking logging 1 line per encountered edge case is major overkill, and prone to generate huge log output. We could count each WARN scenario and log/counter that information to give a more succinct description of execution behavior that a simple user can fix, and an advanced user can ignore judiciously. Possibly more specific counters and only 1 warn per type per execution.
Pig schemas are often so.. imprecise, that i think best effort coercion is useful, but i think a fine compromise would be to support only a specific set of conversions that would be a subset of this patch, but perform the others b/c they are mostly intuitive and useful, but a WARN will be generated when executed if we think it's too esoteric. We may draw lines in slightly different places, but i tried to cover a fair number of cases in the test code, which is think is a fairly survey of expected coercions.
wrt JU.asBag, i think auto-tupling is a must. This is one of the most common mistakes for jython udf devs. "why must i wrap tokens inside of tuples" is a very common refrain, and just silly 99.9% of the time. Plus it's a bunch of extra unnecessary objects that one must create, and causes a bit slower execution for simple udfs.
I'd have to re-read the code again to examine the edge cases. I do recall the disambiguation for embedded bags being a pain to write and describe. Documentation being the remaining concern. That said, i think it does something reasonable and still executes faster than existing rigid code. Also in the code is a decent synopsis of the disambiguations that are intended.
wrt skipping nulls: can you cite the line number? do you mean skipping null bags? or null element/tuples when creating a bag? This might just be me not understanding something properly. I thought bags didn't have null tuples, just tuples with null elements?
wrt various types:
jython is fully capable of returning any jvm type. so that means anything really.
I decided to cover the collections classes, lang classes, base types, and PY* classes.
Jython is nice in that many classes implement the collections ifaces, but not always as efficiently as using the python classes directly.
this is common in python/jython of course. not in udfs as of yet... b/c it wasn't allowed. But i began doing it pretty quickly once it was possible.
wrt schema has fewer fields than actual:
I think pig schema needs to support the feature of specifying partial schemas, or types for schemas with variable number of fields of certain/unspecified type. But I think it is better to have this feature in schema, rather than doing conversions based on a schema that is not compatible. Also, I think it is a good thing to check for schema consistency, so that the user knows when they make a mistake.
I am against the idea of returning null and WARN (nearly as a rule). I think a reasonable interpretation is always better than NULL (with WARN). I would only advocate for an actual error that forces a user to rectify their code.
Returning null+WARN is the convention followed in load funcs like PigStorage and in type conversion code. But I see that the situation in type conversion is different because there is no reasonable interpretation if the type conversion fails.
Does any body else have opinions on this ?
Re: logging 1 line per warning.
PigLogger.warn(..) can be used to aggregate the warnings.
Regarding auto-tupling, I agree that it is useful when -
1. output schema is a tuple
2. output schema is a bag of tuples with single fields.
But if it is a bag of tuples that have multiple fields, I think it is makes sense for the output value to have a list type representing the tuple.
If output schema is {(int, int)} I think the output value should look like - ((1,2),(3,4)). I don't see a need to convert (1,2) into ((1,2)).
I also have concern that with auto tupling, python udf users will have an incorrect understanding of pig bags of primitive types. They might not realize that the bags always contain a tuple. How much of a performance difference did you notice while adding adding tuple wrappers for fields in a bag? I am trying to evaluate the option of providing utility libraries that python udfs can use to convert to pig type.
Regarding skipping nulls in JythonUtils.asBag, it is at line 491. I am not sure about if pig actually works with null tuples in a bag, I need to check that.
if (it != null) { while (first == null && it.hasNext()) { first = it.next(); } }
Unlinking from 0.10 as we don't seem to have agreement on how to proceed yet.. | https://issues.apache.org/jira/browse/PIG-1942 | CC-MAIN-2017-47 | refinedweb | 1,426 | 64.71 |
(For more resources related to this topic, see here.)
Quick start – Creating your first Play application
Now that we have a working Play installation in place, we will see how easy it is to create and run a new application with just a few keystrokes.
Besides walking through the structure of our Play application, we will also look at what we can do with the command-line interface of Play and how fast modifications of our application are made visible.
Finally, we will take a look at the setup of integrated development environments ( IDEs ).
Step 1 – Creating a new Play application
So, let's create our first Play application. In fact, we create two applications, because Play comes with the APIs for Java and Scala, the sample accompanying us in this book is implemented twice, each in one separate language.
Please note that it is generally possible to use both languages in one project.
Following the DRY principle, we will show code only once if it is the same for the Java and the Scala application. In such cases we will use the play-starter-scala project.
First, we create the Java application. Open a command line and change to a directory where you want to place the project contents. Run the play script with the new command followed by the application name (which is used as the directory name for our project):
$ play new play-starter-java
We are asked to provide two additional information:
The application name, for display purposes. Just press the Enter key here to use the same name we passed to the play script. You can change the name later by editing the appName variable in play-starter-java/project/Build.scala.
The template we want to use for the application. Here we choose 2 for Java.
Repeat these steps for our Scala application, but now choose 1 for the Scala template. Please note the difference in the application name:
$ play new play-starter-scala
The following screenshot shows the output of the play new command:
On our way through the next sections, we will build an ongoing example step-by-step. We will see Java and Scala code side-by-side, so create both projects if you want to find out more about the difference between Java and Scala based Play applications.
Structure of a Play application
Physically, a Play application consists of a series of folders containing source code, configuration files, and web page resources. The play new command creates the standardized directory structure for these files:
/path/to/play-starter-scala
└app source code
| └controllers http request processors
| └views templates for html files
└conf configuration files
└project sbt project definition
└public folder containing static assets
| └images images
| └javascripts javascript files
| └stylesheets css style sheets
└test source code of test cases
During development, Play generates several other directories, which can be ignored, especially when using a version control system:
/path/to/play-starter-scala
└dist releases in .zip format
└logs log files
└project THIS FOLDER IS NEEDED
| └project but this...
| └target ...and this can be ignored
└target generated sources and binaries
There are more folders that can be found in a Play application depending on the IDE we use. In particular, a Play project has optional folders on more involved topics we do not discuss in this book. Please refer to the Play documentation for more details.
The app/ folder
The app/ folder contains the source code of our application. According to the MVC architectural pattern, we have three separate components in the form of the following directories:
- app/models/: This directory is not generated by default, but it is very likely present in a Play application. It contains the business logic of the application, for example, querying or calculating data.
- app/views/: In this directory we find the view templates. Play's view templates are basically HTML files with dynamic parts.
- app/controllers/: This controllers contain the application specific logic, for example, processing HTTP requests and error handling.
The default directory (or package) names, models, views, and controllers, can be changed if needed.
The conf/ directory
The conf/ directory is the place where the application's configuration files are placed. There are two main configuration files:
application.conf: This file contains standard configuration parameters
routes – This file defines the HTTP interface of the application
The application.conf file is the best place to add more configuration options if needed for our application.
Configuration files for third-party libraries should also be put in the conf/ directory or an appropriate sub-directory of conf/.
The project/ folder
Play builds applications with the Simple Build Tool ( SBT ). The project/ folder contains the SBT build definitions:
- Build.scala: This is the application's build script executed by SBT
- build.properties: This definition contains properties such as the SBT version
- plugins.sbt: This definition contains the SBT plugins used by the project
The public/ folder
Static web resources are placed in the public/ folder. Play offers standard sub-directories for images, CSS stylesheets, and JavaScript files. Use these directories to keep your Play applications consistent.
Create additional sub-directories of public/ for third-party libraries for a clear resource management and to avoid file name clashes.
The test/ folder
Finally, the test/ folder contains unit tests or functional tests. This code is not distributed with a release of our application.
Step 2 – Using the Play console
Play provides a command-line interface (CLI), the so-called Play console. It is based on the SBT and provides several commands to manage our application's development cycle.
Starting our application
To enter the Play console, open a shell, change to the root directory of one of our Play projects, and run the play script.
$ cd /path/to/play-starter-scala
$ play
On the Play console, type run to run our application in development (DEV) mode.
[play-starter-scala] $ run
Use ~run instead of run to enable automatic compilation of file changes. This gives us an additional performance boost when accessing our application during development and it is recommended by the author.
All console commands can be called directly on the command line by running play <command>. Multiple arguments have to be denoted in quotation marks, for example, play "~run 9001"
A web server is started by Play, which will listen for HTTP requests on localhost:9000 by default. Now open a web browser and go to this location.
The page displayed by the web browser is the default implementation of a new Play application.
To return to our shell, type the keys Ctrl + D to stop the web server and get back to the Play console.
Play console commands
Besides run , we typically use the following console commands during development:
clean: This command deletes cached files, generated sources, and compiled classes
compile: This command compiles the current application
test: This command executes unit tests and functional tests
We get a list of available commands by typing help play in the Play development console.
A release of an application is started with the start command in production (PROD) mode. In contrast to the DEV mode no internal state is displayed in the case of an error.
There are also commands of the play script, available only on the command line:
- clean-all: This command deletes all generated directories, including the logs.
- debug: This command runs the Play console in debug mode, listening on the JPDA port 9999. Setting the environment variable JDPA_PORT changes the port.
- stop: This command stops an application that is running in production mode.
Closing the console
We exit the Play console and get back to the command line with the exit command or by simply typing the key Ctrl + D .
Step 3 – Modifying our application
We now come to the part that we love the most as impatient developers: the rapid development turnaround cycles. In the following sections, we will make some changes to the given code of our new application visible.
Fast turnaround – change your code and hit reload!
First we have to ensure that our applications are running. In the root of each of our Java and Scala projects, we start the Play console. We start our Play applications in parallel on two different ports to compare them side-by-side with the commands ~run and ~run 9001. We go to the browser and load both locations, localhost:9000 and I
Then we open the default controller app/controllers/Application.java and app/controllers/Application.scala respectively, which we created at application creation, in a text editor of our choice, and change the message to be displayed in the Java code:
public class Application extends Controller {
public static Result index() {
return ok(index.render("Look ma! No restart!"));
}
}
and then in the Scala code:
object Application extends Controller {
def index = Action {
Ok(views.html.index("Look ma! No restart!"))
}
}
Finally, we reload our web pages and immediately see the changes:
That's it. We don't have to restart our server or re-deploy our application. The code changes take effect by simply reloading the page.
Step 4 – Setting up your preferred IDE
Play takes care of automatically compiling modifications we make to our source code. That is why we don't need a full-blown IDE to develop Play applications. We can use a simple text editor instead.
However, using an IDE has many advantages, such as code completion, refactoring assistance, and debugging capabilities. Also it is very easy to navigate through the code. Therefore, Play has built-in project generation support for two of the most popular IDEs: IntelliJ IDEA and Eclipse .
IntelliJ IDEA
The free edition, IntelliJ IDEA Community , can be used to develop Play projects. However, the commercial release, IntelliJ IDEA Ultimate , includes Play 2.0 support for Java and Scala. Currently, it offers the most sophisticated features compared to other IDEs.More information can be found here: and also here:
We generate the required IntelliJ IDEA project files by typing the idea command on the Play console or by running it on the command line:
$ play idea
We can also download the available source JAR files by running idea with-source=true on the console or on the command line:
$ play "idea with-source=true"
After that, the project can be imported into IntelliJ IDEA. Make sure you have the IDE plugins Scala, SBT , and Play 2 (if available) installed.
The project files have to be regenerated by running play idea every time the classpath changes, for example, when adding or changing project dependencies. IntelliJ IDEA will recognize the changes and reloads the project automatically. The generated files should not be checked into a version control system, as they are specific to the current environment.
Eclipse
Eclipse is also supported by Play. The Eclipse Classic edition is fine, which can be downloaded here:.
It is recommended to install the Scala IDE plugin, which comes up with great features for Scala developers and can be downloaded here:. You need to download Version 2.1.0 (milestone) or higher to get Scala 2.10 support for Play 2.1.
A Play 2 plugin exists also for Eclipse, but it is in a very early stage. It will be available in a future release of the Scala IDE. More information can be found here:
The best way to edit Play templates with Eclipse currently is by associating HTML files with the Scala Script Editor. You get this editor by installing the Scala Worksheet plugin, which is bundled with the Scala IDE.
We generate the required Eclipse project files by typing the eclipse command on the Play console or by running it on the command line:
$ play eclipse
Analogous to the previous code, we can also download available source JAR files by running eclipse with-source=true on the console or on the command line:
$ play "eclipse with-source=true"
Also, don't check in generated project files for a version control system or regenerate project files if dependencies change. Eclipse (Juno) is recognizing the changed project files automatically.
Other IDEs
Other IDEs are not supported by Play out of the box. There are a couple of plugins, which can be configured manually. For more information on this topic, please consult the Play documentation.
Summary
We saw how easy it is to create and run a new application with just a few keystrokes.
Besides walking through the structure of our Play application, we also looked at what we can do with the command-line interface of Play and how fast modifications of our application are made visible.
Finally, we looked at the setup of integrated development environments ( IDEs ).
Resources for Article :
Further resources on this subject:
- Play! Framework 2 – Dealing with Content [Article]
- Play Framework: Data Validation Using Controllers [Article]
- Play Framework: Binding and Validating Objects and Rendering JSON Output [Article] | https://www.packtpub.com/books/content/so-what-play | CC-MAIN-2015-22 | refinedweb | 2,139 | 53.21 |
Today I learned that you can build web apps with Python using streamlit.
Streamlit is, according to their website, “the fastest way to build and share data apps”.
I don't know if it is the fastest, but I did go through their “getting started” guide in just a few minutes.
With just a bit of code:
# uber.py import streamlit as st import pandas as pd import numpy as np DATE_COLUMN = "date/time" DATA_URL = ( "" + "streamlit-demo-data/uber-raw-data-sep14.csv.gz" ) @st.cache def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) data.rename(str.lower, axis="columns", inplace=True) data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN]) return data st.title("Uber pickups in NYC") data_load_state = st.text("Loading data...") data = load_data(1000) data_load_state.text("Loading data... done! (using cache)") if st.checkbox("Show raw data"): st.subheader("Raw data") st.write(data) st.subheader("Number of pickups by hour") hist_values = np.histogram( data[DATE_COLUMN].dt.hour, bins=24, range=(0,24) )[0] st.bar_chart(hist_values) hour_to_filter = st.slider("hour", 0, 23, 17) # min, max, default filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter] st.subheader(f"Map of all pickups at {hour_to_filter}.") st.map(filtered_data)
I created a basic web app that loads pickup Uber data from New York City, plots a histogram to show the activity per hour, and lets me plot that data after filtering by the hour of that pickup.
To run the web app, first you need to install
streamlit.
This may (or may not) be as simple as
> python -m pip install streamlit
If/when you have
streamlit installed, just run the app with
> python -m streamlit run uber.py
This is more or less what the app looks like:
That's it for now! Stay tuned and I'll see you around!]]>
Today I learned that the reverse of some flag emoji are other flags!
I'm used to getting nerd-sniped by Will McGugan on Twitter, and recently he asked, on Twitter, if we could come up with a string that could not be reversed with the appropriate methods:
>>> "Python"[::-1] 'nohtyP' >>> "".join(reversed("Python")) 'nohtyP'
Here is the original tweet:
Can anyone give me an example of a string that can not be reversed like this?— Will McGugan (@willmcgugan) January 20, 2022
Thankfully, for me, I am already used to getting nerd-sniped by Will and I managed to understand where this was going.
I managed to show that reversing doesn't work with coloured emoji, because the colour is kind of defined by having the regular yellow emoji plus the colour. So, when we reverse it, the colour and the hand change sides, and the colouring doesn't get applied:
>>> "".join(reversed("👍👍🏾")) '🏾👍👍'
This may not display properly, so here is a screenshot of this online Python REPL:
Another way to show what is happening is by surrounding a coloured hand with two yellow ones. Notice how the colour moves out of the middle hand:
>>> "".join(reversed("👍👍🏾👍")) '👍🏾👍👍'
Another person, replying to Will, figured out that the emoji flags were actually represented by a 2-letter country code. So, when reversing, some flags would start spelling a 2-letter country code from a different country, as shown in the picture at the beginning of this article, and below:
>>> "🇧🇬"[::-1] '🇬🇧' >>> "🇬🇪"[::-1] '🇪🇬'
Quite interesting, right?
Because it may be hard to play with emoji in your REPL, you can also try this online.
That's it for now! Stay tuned and I'll see you around!]]>
Today I learned how to cook with
asyncio and async code in Python.
I started learning about async code, the keywords
async and
await,
coroutines, the module
asyncio, etc, a couple of days ago.
Now that I reached enlightenment with regards to the point of async code, and the intuition behind it, I wrote a huge thread on Twitter about it.
I copied the thread and pasted it here (very little editing involved), for this TIL article. I hope it is useful.
For reference, here is the original thread:
I just came up with the perfect analogy to help you understand asyncio in Python 🐍— Rodrigo 🐍📝 (@mathsppblog) January 20, 2022
You can thank me later 😊
Buckle up 🚀 pic.twitter.com/SQNjGUOkuF
I just came up with the perfect analogy to help you understand asyncio in Python 🐍
You can thank me later 😊
Buckle up 🚀
Let me tell you about my lunch today.
For lunch, I had some pasta, some meatloaf, and some avocado. The meatloaf was in the fridge, I only had to reheat it. The avocado needed peeling. I had no pasta already cooked, so I had to cook it before lunch.
Here's how I did it:
I got up from the computer, walked into the kitchen. Filled a pot with water, brought the water to a boil, and put some pasta in. Stared at the pot while the pasta cooked for like 10min, or something. When done, I put the pasta aside.
Then, I opened the fridge, took some meatloaf, put it on my plate. Put the plate in the microwave. Stared at it.
DING 🛎️
Got the plate out. Served some recently-cooked pasta.
Went to the fridge, grabbed an avocado 🥑. Peeled it and sliced it. Served it on my plate. Had lunch. 🍽️
Now, if you are ANYTHING like me, you are staring at your screen, screaming 😨😨😨
Why the heck did I stare at the pot of cooking pasta? Why didn't I take care of the meatloaf while the pasta cooked? Or peeled the avocado?
You know why? Because this is MY ANALOGY.
In my cooking analogy, the story I just told you about is that of a program that does things one after the other, always in sequence.
It's a synchronous program.
Here is what this could look like in code 👇
import time def cook_pasta(): print("Filled pot with water. Pasta will now cook.") time.sleep(10) # Pasta takes 10 min to cook. print("Pasta ready.") def heat_meatloaf(): print("Took meatloaf out of the fridge. Into the microwave it goes.") time.sleep(3) # Meatloaf takes 3 min to heat. print("Meatloaf heated.") def peel_avocado(): print("Grabbed avocado. Now peeling and slicing.") time.sleep(2) # Avocado takes 2 min to peel <- I'm slow. print("Avocado sliced.") def lunch(): print("Preparing lunch.") start = time.time() cook_pasta() heat_meatloaf() peel_avocado() end = time.time() print(f"Eating after {round(end - start)} min of prep time.") lunch()
By the time the...]]>
Today I learned how to use the
namedtuple from the module
collections.
namedtuple
The module
collections
is a gold mine of useful Python tools,
and one of those tools is the
namedtuple.
A named tuple is like a tuple, with the added functionality that you can access the contents of the tuple by name, instead of just by position.
For example, the tuple
>>> me = ("Rodrigo", "mathsppblog")
can represent me, in the sense that
me[0] is my first name and
me[1] is my Twitter handle.
If
me were a named tuple, I would not have to remember the order of the items inside the tuple,
I could just do something like
>>> me.name 'Rodrigo' >>> me.twitter 'mathsppblog'
Of course you could also do this with a class:
class Person: def __init__(self, name, twitter): self.name = name self.twitter = twitter
This also works, but that's also more work!
namedtuple
So, how do you create a
namedtuple?
After the appropriate imports, you just need to call the factory function
namedtuple:
>>> from collections import namedtuple >>> Person = namedtuple("Person", ["name", "twitter"]) >>> me = Person("Rodrigo", "mathsppblog") >>> me.name 'Rodrigo' >>> me.twitter 'mathsppblog' >>> me[1] 'mathsppblog'
That's all it takes!
Reading the docs will show you how powerful named tuples can be, and even shows two nice use cases for them. I'll reproduce one here.
Suppose you have the following CSV file
twitter_people.csv:
Rodrigo,mathsppblog Mike,driscollis Will,willmcgugan
You want to read this data in, and use this data to build
Person named tuples like the named tuple
me above.
By using the module
csv (to read the CSV data) and the
_make function of the named tuple, this is possible:
>>> from collections import namedtuple >>> Person = namedtuple("Person", ["name", "twitter"]) >>> import csv >>> with open("twitter_people.csv", "r") as f: ... reader = csv.reader(f) ... for person in map(Person._make, reader): ... print(f"{person.name} is on Twitter @{person.twitter}!") ... Rodrigo is on Twitter @mathsppblog! Mike is on Twitter @driscollis! Will is on Twitter @willmcgugan!
That's it for now! Stay tuned and I'll see you around!]]>
Today I learned about the Python module
selectors to manage multiple socket connections.
selectors
Following up on some of my recent efforts to learn socket programming,
I learned about the Python module
selectors.
This module is very helpful when you need to manage multiple socket connections
and you don't want to spawn a new thread to handle each socket separately.
The relevance of this module arises from the fact that, if nothing else is done,
calling the method
recv method of a client socket – or the method
accept of a server socket – blocks.
For example, for the server socket, this means that the call to
accept won't return while no connection is accepted.
Try pasting this code in a script and run it:
# server.py import socket server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("localhost", 7342)) server.listen() print("About to accept:") server.accept() print("Call to `accept` returned.")
If you run this with
python server.py, the message
"About to accept:" gets printed,
but not the message
"Call to `accept` returned.".
Why?
Because there is no connection to be accept, and so the call to
accept blocks,
waiting for a connection.
Thus, we can't just call the method
recv on the different clients we have,
because if one doesn't have anything for us, we will block!
A common way to deal with this is by spawning a thread for each client,
and do the blocking calls in those separate threads.
Another way to deal with this is with the module
selectors.
Here is my intuitive understanding of what the module
selectors does:
you take all the sockets that you care about, and you put them in a big bag of sockets.
Then, the module
selectors can take a look at the bag and give you the sockets
that are ready to be read from/written to; you just have to ask.
For example, here is how you can use the module
selectors to only
try accepting a connection to the server socket when one is ready:
# server.py import selectors import socket # Set up the server server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("localhost", 7342)) server.listen() # Set up the selectors "bag of sockets" selector = selectors.DefaultSelector() selector.register(server, selectors.EVENT_READ) while True: events = selector.select() for key, _ in events: sock = key.fileobj print("About to accept.") client, _ = sock.accept() print("Accepted.")
If you paste this code in a file
server.py and run it with
python server.py,
you will see that it hangs once more, but it didn't hang in the call to the method
accept.
If you open a new REPL, create a client socket, and connect to the server,
you will see that the two messages
"About to accept." and
"Accepted." get printed back to back.
The GIF below shows that the two messages get printed pretty much at the same time,
proving that the code is not hanging because of the call to
accept:
There are many, many details I didn't cover about the module...]]>
Today I learned about Spouge's formula to approximate the factorial.
Spouge's formula allows one to approximate the value of the gamma function. In case you don't know, the gamma function is like a generalisation of the factorial.
In fact, the following equality is true:
\[ \Gamma(z + 1) = z!\]
where \(\Gamma\) is the gamma function.
What Spouge's formula tells us is that
\[ \Gamma(z + 1) = (z + a)^{z + \frac12}e^{-z-a}\left( c_0 + \sum_{k=1}^{a-1} \frac{c_k}{z+k} + \epsilon_a(z) \right)\]
In the equality above, \(a\) is an arbitrary positive integer and \(\epsilon_a(z)\) is the error term. Thus, if we drop \(\epsilon_a(z)\), we get
\[ \Gamma(z + 1) = z! \approx (z + a)^{z + \frac12}e^{-z-a}\left( c_0 + \sum_{k=1}^{a-1} \frac{c_k}{z+k} \right)\]
The coefficients \(c_k\) are given by:
\[ \begin{cases} c_0 = \sqrt{2\pi} \\ c_k = \frac{(-1)^{k-1}}{(k - 1)!}(-k + a)^{k - \frac12}e^{-k+a}, ~ k \in \{1, 2, \cdots, a-1\} \end{cases}\]
By picking a suitable value of \(a\), one can approximate the value of \(z!\) up to a desired number of decimal places. Although we need the factorial function to compute the coefficients \(c_k\), those coefficients only need the factorial of numbers up to \(a - 2\). If we are approximating \(z!\), where \(a << z\), then this approximation saves us some work.
In order to determine the number of correct decimal places of the result, one needs to control the error term \(\epsilon_a(z)\). If \(a > 2\) and the \(Re(z) > 0\) (which is always true if \(z\) is a positive integer), then
\[ \epsilon_a(z) \leq a^{-\frac12}(2\pi)^{-a-\frac12}\]
By determining the value of \(a^{-\frac12}(2\pi)^{-a-\frac12}\), we can tell how many digits of the result will be correct. For example, with \(a = 10\), we get
\[ a^{-\frac12}(2\pi)^{-a-\frac12} \approx 1.31556 \times 10^{-9} ~ ,\]
meaning we will get 8 correct digits.
However, notice that the approximating formula must, itself, be computed with enough precision for the final result to hold as many correct digits as expected. In other words, if a higher value of \(a\) is picked so that the final result is more accurate, then we need to control the accuracy used when computing the coefficients \(c_k\) and the formula itself.
I'll leave it as an exercise for you, the reader, to implement this approximation in your favourite programming language.
In APL, (and disregarding the accuracy issues) it can look something like this:
⍝ Computes the `c_k` coefficients: Cks ← {(.5*⍨○2),((!ks-1)÷⍨¯1*ks-1)×((⍵-ks)*ks-.5)×*⍵-ks←1+⍳⍵-1} ⍝ Computes the approximation of the gamma function: GammaApprox ← {((⍵+⍺)*⍵+.5)×(*-⍵+⍺)×(⊢÷1,⍵+1↓⍳∘≢)Cks ⍺} ⍝ Computes an upper bound for the error term: Err ← {(⍵*¯.5)×(○2)*-⍵+.5} a ← 10 Err a 1.315562187E¯9 ⍝ Thus, we expect 8 decimal places to be correct. z ← 100 a GammaApprox z 9.332621544E157 !z 9.332621544E157
That's it for now! Stay tuned and I'll see you around!]]>
Today I learned you can read from stdin with
open(0).
In Python, we typically use the function
In particular, the construct
with open(filepath, mode) as f: ...
is very common in Python.
Well, today I learned that the function
open can accept the integer
0 to read from standard input.
That's because the function
open accepts file descriptors as its argument,
and
0 is the file descriptor for standard input.
1 is the file descriptor for standard output,
and
2 is the file descriptor for standard error,
so you can also write to these two streams by using the built-in
open:
>>> stdout.write("Hello, world!\n") Hello, world! 14 >>> stdout.close()
Knowing that you can read from stdin with
open(0), you can type in multiline input in the REPL with ease:
>>> msg = open(0).read() Hello, world! ^Z >>> msg 'Hello,\nworld!\n'
To stop reading, you need to go to an empty new line and press some magic key(s). (On Windows, it's Ctrl+Z. On Linux/Mac OS it may be Ctrl+D, not sure.)
That's it for now! Stay tuned and I'll see you around!]]>
Today I learned the basics of socket programming (in Python).
When the day started, I had very little knowledge about sockets. My intuitive understanding was that they were like tunnels that allowed different programs to communicate between themselves.
Now that the day is ending, I still don't know much about sockets, but I did spend the day reading about them and experimenting with them.
I have been documenting the process publicly:
Today, I'm spending the day learning in public about socket programming (in Python 🐍).— Rodrigo 🐍📝 (@mathsppblog) January 4, 2022
My starting point is this:
“I think sockets are like tunnels/roads that allow different programs to talk to each other directly.”
This 🧵 will evolve as I learn and experiment 👇
This helps me make sure I learn as much as possible. It also helps, because others chime in with interesting suggestions quite often.
So, “today I learned about sockets”.
I'll show you how you can create two sockets that communicate with each other.
In order to do this, let's open two Python terminals, and put them side by side.
I'll walk you through the things you have to do, just make sure to write each piece of code in the correct REPL:
To create the server, we
# (SERVER) >>> import socket >>> server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> server.bind(("localhost", 7342)) # 1 >>> server.listen() # 2 >>> client, address = server.accept() # 3
At this point, the code hangs because we are waiting for a client to connect.
To create a client, we do the exact same first step, but then we connect to the host and port:
# (CLIENT) >>> import socket >>> client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> client.connect(("localhost", 7342)) # 4
At this point, the server side is no longer hanging, because a client connected and the connection was automatically accepted.
Now, either side can send the first message. If this were a communication through an established protocol, we would know the socket that is expected to send the first message. For example, on the web, with the browsers, browsers are expected to send the first message (the request) to the server. Only then the server replies.
For our toy experiment, let's have the client send the first (and only) message with some data, which the server will give back in reverse.
Sending the data means calling the method
.send:
# (CLIENT) >>> client.send(b"Hello, world!") # 5 13
Now that we sent some data, the server can receive it and handle it. In our case, we receive the data, and then return it reversed.
After we reverse the data and send it back, we close the socket. In our toy example, we assume that...]]>
Today I learned that the module
contextlib provides with a context manager to suppress specified errors.
contextlib
The module
contextlib
contains many utilities to deal with context managers.
In particular, it contains some useful context managers.
One example of a useful context manager that
contextlib possesses is
suppress:
the context manager
suppress does exactly what it says:
it suppresses errors of the specified types.
For example, the code
from contextlib import suppress with suppress(KeyError): ...
prepares a context manager in which
KeyErrors are ignored.
This context manager is a great replacement for the following pattern:
try: # ... except SomeError: pass
When we want to try to do something and want do nothing in case it fails,
the context manager
suppress is great because it reduces the boilerplate you have to write.
As an example, consider a function that deletes a key from a dictionary. If you try to delete a key from a dictionary that doesn't contain that key, you get an error:
>>> del {}["non-existing"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'non-existing'
Thus, we could write our function in one of two ways:
def dictionary_key_delete(a_dict, key): if key in a_dict: del a_dict[key] # or def dictionary_key_delete(a_dict, key): try: del a_dict[key] except KeyError: pass
Because Python prefers a EAFP coding style,
the approach with
try is often preferred in Python.
However, with
contextlib.suppress, it becomes more concise:
from contextlib import suppress def dictionary_key_delete(a_dict, key): with suppress(KeyError): del a_dict[key]
At the same time, this makes the code very expressive, because we know beforehand that we will ignore that specific type of error, giving a hint that we really just want to try to do something but we won't be bothered if it fails.
Another good example is for a function that removes an element from a list.
The built-in type
list has a method that does almost what we want, called
.remove.
The only issue is that the method throws a
ValueError if the element is not in the list.
We can work around this in several ways:
# (LBYL) Look before you leap: def remove_from_list(a_list, element): if element in a_list: a_list.remove(element) # (EAFP) Easier to ask forgiveness than permission: def remove_from_list(a_list, element): try: a_list.remove(element) except ValueError: pass # Also EAFP but more concise: from contextlib import suppress def remove_from_list(a_list, element): with suppress(ValueError): a_list.remove(element)
Both these examples leverage greatly (although implicitly, because I'm not talking about it here) the debate between the EAFP and LBYL coding styles, that you can read about in this article.
Thank you, @loicteixeira, for teaching me this, while discussing the Python Problem-Solving Bootcamp.
That's it for now! Stay tuned and I'll see you around!]]>
Today I learned about the symmetry in indexing from the beginning and end of a list with the bitwise invert operator.
As you might be aware of, Python allows indexing with negative indices:
>>>>> s[-1] '!'
In case this is new to you, you can check out this Pydon't on the subject.
One thing to note is that the index for the
nth element is
n - 1,
but the index for the
nth element from the end is
-n.
This is just “how it works”, but it is kind of a bummer because it is very asymmetrical:
>>>>> seq[0], seq[-1] # 0 and -1 ('A', 'A') >>> seq[1], seq[-2] # 1 and -2 ('B', 'B') >>> seq[2], seq[-3] # 2 and -3 ('C', 'C') >>> seq[3], seq[-4] # 3 and -4 ('D', 'D')
By looking at the correspondences above,
we can see that the positive index
n pairs up with the index
-n - 1.
Python has a couple of bitwise operations, one of them being bitwise invert
~.
Bitwise invert
~n is defined as
-(n+1):
>>> n = 38 >>> ~n -39 >>> -(n+1) -39 >>> n = -73 >>> ~n 72 >>> -(n+1) 72
Now, maybe you can see where I'm going with this, but
-(n+1) simplifies to
-n - 1.
If we put these two pieces of knowledge together,
we can see how we can use bitwise inversion
~ to index symmetrically from the beginning
and end of a sequence, like a string or a list:
>>>>> seq[1], seq[~1] ('b', 'b') >>> for i in range(len(seq) // 2): ... print(seq[i], seq[~i]) ... a a b b c c
Doesn't this look beautiful?
I feel like this is one of those things that you really won't use that often,
but there will come a time in your life when you'll want to exploit this symmetry!
And, you either remember what you just learned about
~, or you'll be writing the uglier version with subtractions:
>>>>> seq[1], seq[~1] ('b', 'b') >>> for i in range(len(seq) // 2): ... print(seq[i], seq[-i - 1]) ... a a b b c c
Thanks a lot to Tushar Sadhwani from bringing this to my attention:
🐍Python Tip of the day:— Tushar Sadhwani (@sadhlife) November 28, 2021
You can use `~i` to index a list in python from behind, instead of `-1 - i`: pic.twitter.com/cVm4JE2aZA
That's it for now! Stay tuned and I'll see you around!]]> | https://mathspp.com/blog/til.atom | CC-MAIN-2022-05 | refinedweb | 3,954 | 65.22 |
Brisingr Aerowing wrote:a compiler toolchain (GCC)
Sampath Lokuge wrote:why you have decided to learn Ruby on Rails instead of ASP.net MVC ?
Marc Clifton wrote:Because RoR is interpreted, it means that I don't have to recompile the app to see changes -- I can make changes to the model, controllers, and of course the views without having to restart the server. Makes development a breeze.
Dan Neely wrote:and am finding about 2/3rds of my debug time is being spent on issues that a compiled/strongly typed language would've called me out on immediately;
# Given comma separated values in a string, returns an array of strings, stripping leading
# and trailing whitespace.
def csv_to_array(csv)
array = csv.split(',').collect{|s| s.strip}
array
end
# Adds children (given in csv format) to an entity.
def add_children(entity, csv_children)
child_list = csv_to_array(csv_children)
entity.add_children(child_list, self.project_id)
end
Dan Neely wrote:when trying to wade though multi-hundred line method failure
Dan Neely wrote:Did git hork up the auto merge badly? ... is my second biggest pain point on the project atm.
Marc Clifton wrote:Dan Neely wrote:when trying to wade though multi-hundred line method failure
Ugh, sounds like you've inherited some really bad code. I tend to find that myself, which has led me to develop my own "best practices" when writing Ruby code.
Marc Clifton wrote:Dan Neely wrote:Did git hork up the auto merge badly? ... is my second biggest pain point on the project atm.
Don't even get me started regarding Git.
Dan Neely wrote:...I think if I really got going I'd end up needing a Nagy's worth of gin, a Dalek's worth of beer, and MM's worth of rum, and a few bottles of Rodger's scotch before I finished; and probably a liver transplant too.
Marc Clifton wrote:Probably would be easier re-writing Git to something that was usable. Oh wait, we have usable source control systems already!
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Lounge.aspx?msg=4736071 | CC-MAIN-2016-30 | refinedweb | 366 | 62.78 |
This question already has an answer here:
No, Java does not have the equivalence. It only has accessor and mutator methods, fancy names for getter and setter methods. For example:
public class User { private String name; public String getName() { return this.name; } public void setName(String name) { this.name = name; } }
You could have a look at Project Lombok as it tries to take the pain out of writing boiler plate Java code. It allows you to either use @Getter and @Setter annotations, which will provide getBlah() and setBlah() methods:
public class GetterSetterExample { @Getter @Setter private int age = 10; }
Or you can just use @Data and it will automatically implement your hashCode(), equals(), toString() and getter methods, along with setters on non-final fields:
@Data public class DataExample { private String name; }
Problems I have found with the project, however, are that it’s all a bit voodoo, which can be off-putting, and that you have to install an eclipse (or what ever) plugin to get auto compilation to work.
Properties are not only convenient in terms of writing
getters and
setters encapsulated in a unit , but also they provide a good syntax at the point of call.
Window.Title = "New"; //which looks natural
while with
getters and
setters it is usually
Window.setTitle("New");
There has been a proposal to add C#-like support for properties (and events) to Java, but it looks like this is rejected for the next version of Java (Java 7).
See:
You can just declare a private variable, and write the methods by hand. However, if you are using Eclipse, you can click on a variable, select “Source” and “Generate getters and setters.” This is about as convenient as C# properties. | https://exceptionshub.com/does-java-have-something-similar-to-c-properties-duplicate.html | CC-MAIN-2021-21 | refinedweb | 286 | 56.59 |
Q. C Program to Find Gcd of Two Numbers.
Here you will find an algorithm and program in C programming language to find GCD of two numbers. First let us understand what is GCD.
Explanation : GCD stands for Greatest Common Divisor, GCD of two numbers is the largest number that can exactly divide both numbers. It is also called as HCF.
For Example : GCD of 60 and 45 is 15. 15 is the greatest number which can divide both 60 and 45. Therefore GCD of 60 and 45 is 15.
Algorithm to find GCD of two numbers
START 1. Declare/Read 2 Numbers A and B and declare variable GCD which holds the result. 2. Run Loop i from 1 to i <= A and i <=B Check if A & B are completely divisible by i or not if yes then Assign GCD = i Loop End 3. Output GCD STOP
C Program to Find Gcd of Two Numbers
#include <stdio.h> int main() { int num1=60, num2=45, i, gcd; for(i=1; i <= num1 && i <= num2; i++) { if(num1%i==0 && num2%i==0) gcd = i; } printf("GCD of %d and %d is %d", num1, num2, gcd); return 0; }
Output
GCD of 60 and 45 is 15 | https://letsfindcourse.com/c-coding-questions/c-program-to-find-gcd-of-two-number | CC-MAIN-2022-40 | refinedweb | 207 | 81.63 |
initstate, random, setstate, srandom - pseudorandom number functions
#include <stdlib.h> char *initstate(unsigned int seed, char *state, size_t size); long random(void); char *setstate(const char *state); void srandom(unsigned int seed);
The random() function uses increases the period.
With 256 bytes of state information, the period of the random-number generator is greater than 269.
Like rand(), random() produces by default a sequence of numbers that can be duplicated by calling srandom() with 1 as the seed.
The srandom() function initialises the current state array using the value of seed.
The initstate() and setstate() functions handle restarting and changing random-number generators. The initstate() function allows a state array, pointed to by the state argument, to be initialised greater than or equal to 8, or less than 32 8 <= size <32, then random() uses a simple linear congruential random number generator.
Once a state has been initialised, setstate() allows switching between state arrays. The array defined by the state argument is used for further random-number generation until initstate() is called or setstate() is called again. The setstate() function returns a pointer to the previous state array.>. | http://pubs.opengroup.org/onlinepubs/007908775/xsh/initstate.html | CC-MAIN-2014-41 | refinedweb | 188 | 53.21 |
I'm working on a program that rounds and adds two real numbers provided by the user. All is going well, except that one of my sample runs is producing an undesired result, and I can't figure out how to fix it for the life of me. The code itself is rather simple, but one problem just. Won't. Work.
1.674 + 1.322 produces:
1.67
1.32
---------
3.00
It should be producing 2.99! D: Please, any advice on how to get it to produce the desired output would be very, very much appreciated.
Here's the code, for your referrence. Sorry about any formatting issues.
Code:#include <iostream> #include <iomanip> using namespace std; int main() { double a, b, sum; cout << "Enter two real numbers to be rounded and added: "; cin >> a >> b; sum = a + b; cout << endl << setw(30) << setiosflags(ios::fixed) << setprecision(2) << a << endl << setw(30) << b << endl << setw(30) << "---------" << setw(30) << endl << sum << endl; return 0; } | http://cboard.cprogramming.com/cplusplus-programming/70554-hmm-quandary-rounding-adding-problem.html | CC-MAIN-2015-18 | refinedweb | 164 | 71.95 |
radish-bdd 0.01.31
Behaviour-Driven-Development tool for python
======
``radish`` is a "Behavior-Driven Developement"-Tool written in
python Version: 0.01.29
--------------
**Author:** Timo Furrer tuxtimo@gmail.com\ **License:** GPL
**Version:** 0.01.31
Table of contents
-----------------
1. `What is radish <#whatis>`__
2. `Installation <#installation>`__
1. `Missing dependencies <#missing_dependencies>`__
2. `Simple installation with pip <#installation_pip>`__
3. `Manual installation from source <#installation_source>`__
4. `Update source installation <#installation_update>`__
5. `Install on Windows <windows_installation_guide.md>`__
3. `How to use? <#usage>`__
4. `Writing tests <#write_tests>`__
5. `Contribution <#contribution>`__
6. `Infos <#infos>`__
What is ``radish`` ?
--------------------
``radish`` is a "Behavior-Driven Developement"-Tool written in python.
It is inspired by other ``BDD``-Tools like ``cucumber`` or ``lettuce``.
`[⬆] <#TOC>`__
Installation
------------
There are several ways to install ``radish`` on your computer:
`[⬆] <#TOC>`__
Missing dependencies
~~~~~~~~~~~~~~~~~~~~
``radish`` needs ``libxml`` to generated xunit files. So, if you haven't
already installed it:
::
apt-get install libxml2 lixbml2-dev libxslt1-dev
On some computers I've seen the problem that ``zlib1g-dev`` was not
installed, which is used to compile lxml. It result in the error:
::
/usr/bin/ld: cannot find -lz
You can fix it with:
::
apt-get install zlib1g-develop
`[⬆] <#TOC>`__
Simple installation with pip
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is probably the simplest way to install ``radish``. Since the
``radish`` releases are hostet as well on
`pip <https: pypi.python.`__ you can use the following
command to install ``radish``:
::
pip install radish
*Note: On some systems you have to be root to install a package over
pip.*
`[⬆] <#TOC>`__
Manual installation from source
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you always want to be up to date with the newest commits you may want
to install ``radish`` directly from `source
code <https: github.`__. Use the following
command sequence to clone the repository from github and install
``radish`` afterwards:
.. code:: bash
git clone ~/radish
cd ~/radish
git submodule init
git submodule update
python setup.py install
*Note: On some systems you have to be root to install a package over
setuptools.*
`[⬆] <#TOC>`__
Update source installation
^^^^^^^^^^^^^^^^^^^^^^^^^^
If you have once installation ``radish`` from source you might want to
update it from time to time. Change into the directory where you have
cloned ``radish`` into (default: ``~/radish``) and pull the newest
commit from github. When you've done this you need to re-install
``radish`` again. So, in summary:
.. code:: bash
cd ~/radish
git pull
python setup.py install
*Note: On some systems you have to be root to install a package over
setuptools.*
`[⬆] <#TOC>`__
How to use?
-----------
.. code:: bash
mkdir testprj
cd testprj
radish -c
.. code:: bash
creating radish/
creating radish/steps.py
creating radish/terrain.py
.. code:: bash
mkdir tests
cat > tests/001-howto.feature <<eof<br> Feature: Provide a first test as example for using radish
In order to be a good program, provide an example how to write a test.
Scenario: Getting started using radish
# Show the steps that need to be done to get testing with radish.
Given I have radish version 0.01.15 installed
EOF
.. code:: bash
radish tests/001-howto.feature
.. code:: bash
tests/001-howto.feature:7: error: no step definition found for 'Given I have radish version 0.01.15 installed'
you might want to add the following to your steps.py:
@step(u'I have radish version 0.01.15 installed')
def I_have_radish_version_0_01_15_installed(step):
assert False, "Not implemented yet"
add these 3 lines to radish/steps.py and run radish again:
.. code:: bash
radish tests/001-howto.feature
1. Provide a first test as example for using radish # 001-howto.feature
In order to be a good program, provide an example how to write a
test.
1. Getting started using radish
1. Given I have radish version 0.01.15 installed AssertionError:
Not implemented yet
1 features (0 passed, 1 failed) 1 scenarios (0 passed, 1 failed) 1 steps
(0 passed, 1 failed) (finished within 0 minutes and 0.00 seconds)
`[⬆] <#TOC>`__
Writing tests
-------------
`[⬆] <#TOC>`__
Contribution
------------
Use virtualenv
~~~~~~~~~~~~~~~
I recommend you to develop ``radish`` in a virtualenv, because than you
can easily manage all the requirements.
.. code:: bash
virtualenv radish-env --no-site-packages
. radish-env/bin/activate
pip install -r requirements.txt
More coming soon ...
`[⬆] <#TOC>`__
Infos
-----
The files which are currently in the testfiles-folder are from lettuce -
another TDD tool!
`[⬆] <#TOC>`__
- Downloads (All Versions):
- 53 downloads in the last day
- 612 downloads in the last week
- 3091 downloads in the last month
- Author: Timo Furrer
- Download URL:
- License: GPL
- Platform: Linux,Windows,MAC OS X
- Categories
- Development Status :: 4 - Beta
- Environment :: Console
- Intended Audience :: Developers
- Intended Audience :: Education
- Intended Audience :: Other Audience
- License :: OSI Approved :: GNU General Public License v3 (GPLv3)
- Natural Language :: English
- Operating System :: MacOS :: MacOS X
- Operating System :: Microsoft :: Windows
- Operating System :: Microsoft :: Windows :: Windows 7
- Operating System :: Microsoft :: Windows :: Windows XP
- Operating System :: OS Independent
- Operating System :: POSIX
- Operating System :: POSIX :: Linux
- Programming Language :: Python
- Programming Language :: Python :: 2.6
- Programming Language :: Python :: 2.7
- Programming Language :: Python :: 3
- Programming Language :: Python :: 3.2
- Programming Language :: Python :: Implementation
- Topic :: Education :: Testing
- Topic :: Software Development
- Topic :: Software Development :: Testing
- Package Index Owner: tuxtimo
- DOAP record: radish-bdd-0.01.31.xml | https://pypi.python.org/pypi/radish-bdd/0.01.31 | CC-MAIN-2016-07 | refinedweb | 872 | 59.19 |
using System;
namespace ns{
class aa{
static void Main(string[] args){ string[] starray = new string[]{"Down the way nights are dark", "And the sun shines daily on the mountain top", "I took a trip on a sailing ship", "And when I reached Jamaica", "I made a stop"}; string aa= String.Join(".",starray); Console.WriteLine(aa); Console.ReadKey() ;
}
}
}
错误:
Down the way nights are dark.And the sun shines daily on the mountain top.I took a trip on a sailing ship.And when I reached Jamaica.I made a stop
Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.
at System.Console.ReadKey(Boolean intercept)
at ns.aa.Main(String[] args) | https://q.cnblogs.com/q/114213/ | CC-MAIN-2022-40 | refinedweb | 130 | 65.83 |
Updates
- 11/18: Cleaning up unused header files. Files changed: calcDepthNaive.c, check.c. To update to the latest files, use the following command:
\cp ~cs61c/proj/03/part2/{benchmark.c,calcDepthNaive.c,calcDepthNaive.h,calcDepthOptimized.h,check.c,depthMap.c,Makefile,qsubScript.sh,utils.c,utils.h} .
- 11/17: Updated correctness check. Files changed: utils.c.
- 11/16: Project 3 Part 2 release.
Clarifications/Reminders
- Start Early!
- This project should be done on the hive machines. The code will not compile on non-x86 machines and will likely perform differently on other machines not configured similarly to the hive machines.
- You are required to work with one partner for this project. You may share code with your partner, but ONLY your partner. The submit command will ask you for your partner's name, so only one partner needs to submit.
- Make sure you read through the project spec before starting.
- Please refrain from using hive26, hive27, or hive28 for anything other than PBS scheduling.
Goals
In Project 1, you wrote a program that would generate a depth map from stereo images. You then optimized this depth map generator in Project 3 Part 1. However, your Project 3 Part 1 code only improved the performance using SSE/SIMD instructions. In Part 2, you will further optimize the performance of your code by parallelizing your code using OpenMP.
Background
Refer to the Project 3 Part.
Part 2 (Due 11/23 @ 23:59:59)
Optimize your depth map generator using any of the techniques you learned including OpenMP. For full credit, the program needs to achieve an average performance of 20 GFlop/s for varying sizes of images. This requirement is worth 35 pts. Your output should remain correct, and we have provided utilities for your to check the correctness of your code. Please remember, however, that the code provided is not a guarantee of correctness and we expect you to test your code yourself. Code that is incorrect will be considered to run at 0 GFlop/s for grading purposes.
Your code will also be tested with varying parameters (nothing too small) and must achieve an average performance of 15 GFlop/s. This requirement is worth 15 pts.
Getting started
Copy the files in the directory
~cs61c/proj/03/part2/ to your
proj3/part2 directory, by entering the following command:
mkdir -p ~/proj3/part2 cp -r ~cs61c/proj/03/part2/* ~/proj3/part2 cp -r ~/proj3/part1/calcDepthOptimized.c ~/proj3/part2
You will need to add the following OpenMP headers to your
calcDepthOptimized.c
to enable OpenMP support:
// include OpenMP #if !defined(_MSC_VER) #include <pthread.h> #endif #include <omp.h>
The only file you need to modify and submit is
calcDepthOptimized.c. It is your job to implement an optimized version of
calcDepthNaive in
calcDepthOptimized.
You should copy your code from part.
qsubScript.sh: Script for submitting jobs to PBS queue. Glop/s point values are linearly interpolated based on the point values of the two determined neighbors. Note that heavy emphasis is placed on the middle Gflop/s, with the last couple being worth relatively few points. So don't sweat it if you are having trouble squeezing those last few floating point operations out of the machine!
Here are some suggestions for improving the performance of your code:
- Factor out common calculations and keep the result.
- Avoid recalculating values you have already calculated.
- Unroll loops so that you can use SSE and perform 4 operations at a time.
- Don't be afraid to restructure the loops or change the ordering of some operations.
- Padding the matrices may give better performance for odd sized matrices.
- Use OpenMP to multithread your code.
- Avoid forking and joining too many times, and avoid critical sections, barriers, and single sections.
- Avoid false sharing and data dependencies between processors.
While you are working on the project, we encourage you to keep your code under version control. However, if you are using a hosted repository, please make sure that it is private, or else it could be viewed as a violation of academic integrity.
Before you submit, make sure you test your code on the hive machines. We will be grading your code there. IF YOUR PROGRAM FAILS TO COMPILE, YOU WILL AUTOMATICALLY GET A ZERO . There is no excuse not to test your code.
Submission
The full proj3-2 is due Sunday 11/23 @ 23:59:59. Please make sure only ONE partner submits. To submit proj3-2, enter in the following:
submit proj3-2
Your changes should be limited to
calcDepthOptimized.c. If you have any issues submitting please e-mail your TA. Good luck!
Portable Batch System (PBS)26, hive27, and hive28.
Important: These machines have been restricted to just cs61c account logins and they are to be used only for testing code. In order to keep these machines completely free for benchmarking, you are forbidden from developing on hive26, hive27, and hive28 throughout the duration of Project 3. Only log on to these servers when you are ready to submit a job to the queue.
You will submit jobs to the queue by running a short shell script we have provided. Read the following instructions carefully to make sure you can properly test your program.
- Log into hive26, hive27, or hive28 via ssh.
- Type
make clean, then recompile your project using the Makefile. This step may be unnecessary if you were developing on the other hive machines.
- Edit the file
qsubScript.shwith your information. There are only 2 lines you need to edit:
- At the top of the file, fill in your e-mail here to get a notification when the job begins and completes:
#PBS -M [email]@berkeley.edu
- At the bottom of the file, put whatever command you want your job to run: The default line is
./benchmark > bench-output.txtwhich will run the
benchmarkexecutable and place the output in a text file named
bench-output.txt.
You can now submit your job to the PBS.
qsub qsubScript.sh
This command will respond with the job number followed by the hostname of the PBS server machine. "16.hive26.cs.berkeley.edu" means that job number 16 has been submitted to the PBS server running on hive26.cs.berkeley.edu.
Once you have submitted your job, you can check on the status by using the "qstat" command. The output will look something like this:
qstat Job id Name User Time Use S Queue ------------------------- ---------------- --------------- -------- - ----- 12.hive26 CS61C cs61c-ti 00:00:14 C batch 16.hive26 CS61C cs61c-ti 00:00:27 C batch 17.hive26 CS61C cs61c-ti 0 R batch
This output indicates that the job id 12.hive26 was submitted by "cs61c-ti" and is now complete "C". Other useful state indicators are "Q" (queued) and "R" (running). So job 17.hive26 is still running in the example above.
- Once your job is complete, the output of your job will be found in the file you specified in
qsubScript.sh(default
bench-output.txt)
Competition
There will be a performance competition for this project. The winners of this competition will receive recognition and EPA, and will be announced in class on the last day. The details will be announced later. The competition will be due near the end of the class (in December). | https://inst.eecs.berkeley.edu/~cs61c/fa14/projs/03/part2/ | CC-MAIN-2018-51 | refinedweb | 1,213 | 67.15 |
Unit testing Houdini Python plugins with nose and coverageThu 20 March 2014
We all know how important unit testing is, right? But often you wonder how can you test a not so straight forward tool. In this case we're talking about a Python script intended to run inside Houdini. In my specific case the python script is launched from a script on a node when the user clicks a button on the OTL. I want to run unit tests on this script, but the problem is that the script parses a set of nodes and does various things according to the types of nodes and layout of the nodes. It's clear that the HOM is required in the unit tests. So I need to somehow run my unit tests inside houdini and have some nodes available for my testing. Fortunately this isn't difficult to do, but it does require a little setup and some fiddling in order to get it to work.
I'll be using nose tests as my test runner and coverage for coverage testing. Because I want to make sure I test as much code as possible. I created a hip file that contains whatever nodes and connections I need to run most of the tests and saved this to the same directory as my test script.
Before we write some code you will need to install
nose and
coverage and make sure they work.
Now that we have all our dependencies installed, we need to import all the modules we need and set some things up.
import nose import sys sys.path.insert(0, '../path_of_module') import os os.environ['NOSE_WITH_COVERAGE'] = '1' os.environ['NOSE_COVER_PACKAGE'] = 'module_to_test' import hou import module_to_test
We import the
nose module and then we need to tell nose to make use of the coverage package.
os.environ['NOSE_WITH_COVERAGE'] = '1' does just that, and
os.environ['NOSE_COVER_PACKAGE'] = 'module_to_test' restricts our test results to the module(s) we want to test. If you want to specify multiple modules simply separate them with commas:
os.environ['NOSE_COVER_PACKAGE'] = 'module_to_test,another_module'
Unfortunately for this to work properly you need to patch nose's cover plugin. There's a small bug in older versions, so depending on your distro you may need to make the following change to
nose/plugins/cover.py
Change these lines
for pkgs in [tolist(x) for x in options.cover_packages]: self.coverPackages.extends(pkgs)
to these lines
for pkgs in tolist(options.cover_packages): self.coverPackages.append(pkgs)
Otherwise the
NOSE_COVER_PACKAGE variable won't work properly.
I also setup the
sys.path so that I load my local module rather than the globally installed one. Depending on how your directories are laid out you might not need this.
After this we need to import the
hou module and finally the module(s) we want to test.
Then we write our main function which will load our hip file and start our tests
if __name__ == '__main__': hou.hipFile.load('/path/to/test.hip') nose.run(argv=[__file__], '--cover_html'])
As you can see, you can pass the commandline argments for nose into the run function. With
--cover_html we automatically generate the html coverage information. You could omit this and run
coverage html after the tests complete to generate the html coverage pages instead. The output from the two methods is slightly different, so pick the one that you prefer.
The next bits are up to you now, here you write your tests following a format like
def test_afunction(): node = hou.node('/obj/geo/box1') result = module_to_test.do_stuff(node) assert (result == 4)
You can access any and all
hou. calls from your tests, so do what you must.
Once you are happy with your tests, or you just want to go ahead and test a single one, we need to run the tests through hython. Bear in mind that you'll consume a batch license when you run these tests.
hython ./test.py
where
test.py is the name of the file that contains the tests you wrote. After a while you'll see your tests run and the coverage output. It should look a little like this
... Name Stmts Miss Cover Missing ------------------------------------------- module_to_test 25 14 44% 1-2, 6, 9, 12-15, 21, 27-32 another_module 314 173 45% 4-20, 24, 37-38, 46 ------------------------------------------- TOTAL 339 187 45% ---------------------------------------------------------------------- Ran 3 tests in 0.053s OK
You'll also have a directory called
cover which will contain the html output, assuming you have the
--cover_html flag on. If not, run
coverage html and after a short wait you will have a
htmlcov directory with the html coverage info.
I hope this helps you out if you ever wanted to unit test your Houdini Python script. It's not as difficult as I thought, but it does take a little bit of setting up to get everything to work right. There will still be some limitations as to what you can test and get results for, but any testing is always better than none at all I say.
And the
test.py file as a whole
import nose import sys sys.path.insert(0, '../path_of_module') import os os.environ['NOSE_WITH_COVERAGE'] = '1' os.environ['NOSE_COVER_PACKAGE'] = 'module_to_test' import hou import module_to_test def test_afunction(): node = hou.node('/obj/geo/box1') result = module_to_test.do_stuff(node) assert (result == 4) if __name__ == '__main__': hou.hipFile.load('/path/to/test.hip') nose.run(argv=[__file__], '--cover_html']) | https://www.unlogic.co.uk/2014/03/20/unit-testing-houdini-python-plugins-with-nose-and-coverage/ | CC-MAIN-2018-22 | refinedweb | 904 | 65.42 |
Finally I solved it. The problem was that I used one array for vertices, normals and texture coordinates instead of storing in separate arrays and bind them separately.
Finally I solved it. The problem was that I used one array for vertices, normals and texture coordinates instead of storing in separate arrays and bind them separately.
I changed my code, I'm suing VAO and I put the glUniform1i in the init. The result is still the same. Maybe the problem is somewhere else? I'm suing SDL for handling the window and load images.
I'm...
Thanks for the help. I've never used VAO so it is a bit confusing. I know what it is used for, but I don't really understand what should I put in the init and put in the draw.
For example the...
I tried, draw only the first, then I draw only the second. The texture was the same noisy image.
What is wrong exactly? Here is the whole class with the init method to get a clearer picture of my code:
#include "global.h"
#include "CModel.h"
#include "CModelLoader.h"
#include...
You should open a new thread and describe exactly what is you problem, copy some sample from the code. We can't find out what is your home work, and it would be great to not spoil my thread.:)
Do you say that instead of using glActiveTexture(GL_TEXTURE0) before the loop I should call it inside the loop before glBindTexture and in each loop set different unit?
I tried it but it doesn't...
Hello,
This problem may not be related directly to shaders, but I don't even know exactly where the problem is. Since I moved from fixed pipeline to shaders, the texture appears wrong. Here is a... | https://www.opengl.org/discussion_boards/search.php?s=57764d69b9c664dd8552e96846742101&searchid=1367799 | CC-MAIN-2015-32 | refinedweb | 300 | 76.72 |
From: Alexander Viro <viro@math.psu.edu> To: linux-kernel@vger.kernel.org Subject: [CFT] initramfs patch Date: Mon, 30 Jul 2001 02:05:55 -0400 (EDT) Cc: Linus Torvalds <torvalds@transmeta.com>, linux-fsdevel@vger.kernel.org Folks, IMO initramfs (aka. late boot in userland) is suitable for testing. Patches are on, namespaces-a-S8-pre2 and initramfs-a-S8-pre2 (the latter is against 2.4.8-pre2 + namespaces). It is supposed to be a drop-in replacement - any boot setup that works with vanilla 2.4 should work with it, initrd or not, with or without devfs, with loading from floppies, etc. In other words, if you boot normally with 2.4 and something breaks with initramfs - I want to know about that. Stuff that went in userland: choosing and mounting root, unpacking/loading initrd, running /linuxrc, handling nfsroot, finding and starting final init - basically, everything after do_basic_setup(). The thing unpacks cpio archive (currently - linked into the kernel image) on root ramfs and execs /init. After that we are in userland code. Said code (source in init/init.c and init/nfsroot.c) emulates the vanilla 2.4 behaviour. You can replace it with your own - that's just the default that gives (OK, is supposed to give) a backwards-compatible behaviour. Thing that had not gone into the userland, but should be there: ipconfig.c. If somebody feels like writing a userland equivalent - I'd be very grateful to see it. Currently it's still in the kernel. Another thing that is definitely needed is less crude RPC (for nfsroot). Currently it's _very_ quick-and-dirty. At that stage I'm mostly interested in bug reports regarding the cases when behaviour differs from the vanilla tree. I _know_ that we need more elegant way to add initial archive to the kernel image. That's a separate issue and I'd rather deal with that once userland implementation of late-boot is decently debugged. Right now it's x86-only, but that's the matter of adding minimal replacement of crt1.o for other platforms (i.e. code that picks argc, argv and envp and calls main() - 7 lines of assembler for x86 and probably about the same on other platforms). Equivalents of arch/i386/kernel/start.S (see the patch) are welcome. It should be pretty safe to debug, for a change - it either gets to starting /sbin/init (in which case we are done and safe) or it breaks before any local fs is mounted r/w. Linus, I'm not putting these patches in the posting - each of them is above 100Kb and that's way beyond any sane l-k limits. If you want to get them in email - tell and I'll send them. And yes, I'm going to split this stuff in small chunks when it will come to submitting it. Al - To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.kernel.org More majordomo info at Please read the FAQ at | http://lwn.net/2001/0802/a/initramfs.php3 | crawl-003 | refinedweb | 514 | 67.25 |
This talk is about clean architecture and our experiences with introducing it into our Android app at Buffer.
My name is Joe, and I’m an Android Engineer at Buffer. At Buffer, we create a Social Media scheduling tool so you can write posts and send them out to multiple social networks throughout the week at any time.
When There Is No Architecture
With Buffer there was a rush to get features to production to test the market. Without a period to plan the architecture, it can be easy to make the wrong decisions. The issues we faced included:
Having a high level of technical debt. This means that issues take longer to resolve and new features take longer to ship as a consequence of bad choices in the past.
Classes were over coupled to each other.
No unit or UI tests.
Not knowing the origin of bugs.
If your project isn’t structured or architected properly, as the team grows, it’s going to get more complicated for you and developers to work on the project.
Buffer for Android
Joining Buffer, it was difficult for me to jump in and know what was going on where. New people joined and they didn’t understand what was going on; they were building on top of stuff that was already at fault. The debt was getting even greater.
There was little structure, and the Activities were often bloated with multiple responsibilities. There was a lot of code duplication - custom views and custom logic. The bugs we fixed would often appear elsewhere where we did not expect weeks later.
Moving to MVP (Model View Present)
With a fear of changing too much, when I joined we decided to start using MVP (Model View Present). We introduced MVP to keep it simple and not change too much at once. This has allowed us to create a clear line of separation between our framework and our presentation logic. We moved all our data operations into data manager classes. In turn, this allowed us to increase our test coverage.
But MVP Alone Was Not Enough
But we had this data manager class, which was already becoming bloated with multiple responsibilities. It was accessing the API, accessing the cache. It felt a bit like oh we got this data operation, let’s stick it in that data manager class. It’s messy.
Get more development news like this
There was a data manager class with multiple responsibilities - it was accessing the API and accessing the cache alongside preference helper classes. Despite splitting these out into a composer and user data manager, it was still bloated and unorganized.
In the instance of the data manager, if we wanted to take the app offline in the future, how would we be able to accomplish that based on its current state? As a way to solve this, we decided we needed to change the architecture.
Architecture
It was clear we needed something that allowed us to be flexible, and allowed us to maintain the app and have a higher level of test coverage. Having a good architecture on Android should be intuitive. For example, you should be able to look at a package structure and understand how it’s organized. I often think about this from the perspective of writing open source code: would my code be apparent to I don’t know, and who isn’t on my team?
Clean Architecture
There is no specific way for implementing good architecture. But, there is a classic diagram of clean architecture. In particular, there are four sections:
- The domain logic: entities, data, models.
- Business rules: use cases.
- Interface adapters: presenters and presentation logic.
- Frameworks/drivers: UI, networking, databases.
With clean architecture, dependencies have to point inward. For example, presenters cannot know about interfaces, and entities cannot know about use cases.
Separation of Concerns
You can have more focused test classes, with each independent. In our Android app, the only layer that knows anything about the Android framework in our project is the UI layer. Our presenters and entities are unaware of the Android framework. As a result of the refactor:
Our code is more testable, and our classes are and more focused and maintainable.
Our inner layers are independent of the user interface. Because the UI can be the most sensitive part of Android development, these decoupled makes a big difference.
The inner layers are independent of any external parties.
Our bugs are more isolated because everything’s layered and everything has its own responsibilities. This helped out track down the origin of the bugs.
Layer Models
Enterprise Business Rules
The first layer is the
enterprise business rules, the core business rules of our application. For example, Twitter’s rules might be a profile or a tweet. Unless the needs of your business change, you should never need to touch these once they have been created. These can also be created before you write your UI.
public class TournamentModel { public String id; public String name; @SerializedName("full_name") public String status; @SerializedName("date_start") public String dateStart; @SerializedName("date_end") public String dateEnd; public int size; }
Application Business Rules
The
application business rules are rules that are specific to our application. These are defined by use cases, e.g. tasks that our application will carry out. For example, you might want to save a photo or get a profile.
An example of a use case in our application is where users have to get schedules.
public class GetSchedules extends UseCase<ProfileSchedules> { private final SchedulesRepository schedulesRepository; @Inject public GetSchedules(SchedulesRepository schedulesRepository) { this.schedulesRepository = schedulesRepository; } @Override public Single<ProfileSchedules> buildUseCaseObservable() { return schedulesRepository.getSchedules(); } }
In this layer, we provide an interface to define how the outside layers will communicate with this layer. The outside layer will pass in a concrete implementation of that repository. This makes things more clear and easier to test.
Interface Adapters
The third layer is
interface adapters. This contains the presentation logic of our application. In our case, it contains the MVP side of things, e.g. the views and presenters. These presenters contain callbacks to define how we retrieve the data from the other layers. In our case we are using RxJava:
public class UpdatesPresenter extends BasePresenter<UpdatesMvpView> implements SingleObserver<List<Update>> { @Override public void onSubscribe(Disposable d) { ... } @Override public void onSuccess(List<Match> matches) { ... } @Override public void onError(Throwable e) { ... } }
Frameworks & Drivers
Our final layer is the
frameworks and drivers. This contains all of our UI components such as the activities, fragments, and views. These can be outside layers, and eventually, these can be moved into other layers with a repository pattern to help with the interaction.
Layer Boundaries
With our different layers, we now have a clear layer boundary - interfaces with concrete implementations that we pass in to provide more flexibility. These interfaces dictate how others will communicate with them. This is known as the dependency inversion principle.
With clean architecture we’re not limited to these layers. You can easily have three layers instead, and you do not need to have a separate enterprise business rules (these can be merged into application business rules). In our case, we may separate out the database and analytics and have five layers instead of four.
Test Coverage
The great advantages that good architecture brings are test coverage. We are now able to write much more focused test classes, as everything has been separated out into its own responsibilities.
You are able to test use cases along with the models in each layer, including tests that cross the layer boundaries.
Lessons
We are still learning and are making mistakes as we go. Clean and good architecture is a general term, but it means using more abstractions and writing focused classes. Even if you don’t use clean architecture as a whole, there are things you can learn to benefit from it in your projects.
Advantages of Clean Architecture
- A higher percentage of code test coverage.
- Increased ease to navigate the package structure.
- The project is easier to maintain, as classes are more focused.
- Clean architecture allowed for being able to add features more quickly.
- Future proofing implementations.
- Clean architecture is a clear discipline and overall a good practice to follow.
Disadvantages of Clean Architecture
Trying to implement clean architecture adds substantial overhead in the beginning. New interfaces and implementations needed to be added, along with separate modules. During our transition, it was often we forget to reuse models throughout our project. These habits can take time to form.
Resources
We have a blog post about clean architecture and how have used it. The google samples is good if you want a solid sample of clean architecture. Clean Architecture: A Craftsman’s Guide to Software Structure and Design (Robert C. Martin), is also good.
Questions
Q: Could talk more about the models and implementing them in every single layer, and what the adapters between those different layers look like? Joe: The enterprise business rules have models, and the layer outside has a mapper class in addition to its own models, so that mapper class will have a builder pattern. The debate here will be about efficiency - because if you’re doing that with multiple models it’s not too efficient.
Q: Do you use clean architecture on iOS, and what’s the experience? Joe: We don’t at the moment, but I’m trying to push this.
Q: What happened to the data manager classes, and where do you now do the API calls and caching? Joe: In the repositories, the presenters have been injected with a use case and that use case has reference to the repositories. Those repository implementations are passed in.
Our data stores have a remote data store and a cache data store which will both implement this interface, and they have exactly the same operations.
Q: For your outer two layers, the presentation layer and your UI layer, do you expose everything in that, or give exposure to Android for both those layers?? Joe: We pass. The presentation layer we do have participle to pass that through to the view layer.
Q: With all this data transfer between layers, are you doing a parcelization or are you doing a capsulation between the layers? Joe: Not as of yet. We’re guilty of that. We’re passing them through, and then converting them using mapper classes.
About the content
This talk was delivered live in April 2017 at Droidcon Boston. The video was recorded, produced, and transcribed by Realm, and is published here with the permission of the conference organizers. | https://academy.realm.io/posts/converting-an-app-to-use-clean-architecture/ | CC-MAIN-2018-13 | refinedweb | 1,761 | 56.76 |
Release Mixed Effects Models¶
Linear
NA-handling with formulas is now correctly handled. Issue #805, Issue #1877.
Better error messages when an array with an object dtype is used. Issue #2013.
ARIMA forecasts were hard-coded for order of integration with
d = 1. Issue #1562..
Issues closed in the 0.6.0 development cycle¶
Issues closed in 0.6.0¶
GitHub stats for 2013/08/14 - 2014/10/15 (tag: v0.5.0)
We closed a total of 528 issues, 276 pull requests and 252 regular issues;
this is the full list (generated with the script
tools/github_stats.py):
This list is automatically generated and may be incomplete.
Pull Requests (276):
PR #2044: ENH: Allow unit interval for binary models. Closes #2040.
PR #1426: ENH: Import arima_process stuff into tsa.api
PR #2042: Fix two minor typos in contrast.py
PR #2034: ENH: Handle missing for extra data with formulas
PR #2035: MAINT: Remove deprecated code for 0.6
PR #1325: ENH: add the Edgeworth expansion based on the normal distribution
PR #2032: DOC: What it is what it is.
PR #2031: ENH: Expose patsy eval_env to users.
PR #2028: ENH: Fix numerical issues in links and families.
PR #2029: DOC: Fix versions to match other docs.
PR #1647: ENH: Warn on non-convergence.
PR #2014: BUG: Fix forecasting for ARIMA with d == 2
PR #2013: ENH: Better error message on object dtype
PR #2012: BUG: 2d 1 columns -> 1d. Closes #322.
PR #2009: DOC: Update after refactor. Use code block.
PR #2008: ENH: Add wrapper for MixedLM
PR #1954: ENH: PHReg formula improvements
PR #2007: BLD: Fix build issues
PR #2006: BLD: Do not generate cython on clean. Closes #1852.
PR #2000: BLD: Let pip/setuptools handle dependencies that are not installed at all.
PR #1999: Gee offset exposure 1994 rebased
PR #1998: BUG/ENH Lasso emptymodel rebased
PR #1989: BUG/ENH: WLS generic robust cov_type did not use whitened,
PR #1587: ENH: Wrap X12/X13-ARIMA AUTOMDL. Closes #442.
PR #1563: ENH: Add plot_predict method to ARIMA models.
PR #1995: BUG: Fix issue #1993
PR #1981: ENH: Add api for covstruct. Clear __init__. Closes #1917.
PR #1996: DEV: Ignore .venv file.
PR #1982: REF: Rename jac -> score_obs. Closes #1785.
PR #1987: BUG tsa pacf, base bootstrap
PR #1986: Bug multicomp 1927 rebased
PR #1984: Docs add gee.rst
PR #1985: Bug uncentered latex table 1929 rebased
PR #1983: BUG: Fix compat asunicode
-
PR #1980: DOC: Documentation fixes
PR #1974: REF/Doc beanplot change default color, add notebook
PR #1978: ENH: Check input to binary models
-
PR #1976: ENH: Add _repr_html_ to SimpleTable
PR #1977: BUG: Fix import refactor victim.
PR #1975: BUG: Yule walker cast to float
PR #1973: REF: Move and expose webuse
PR #1972: TST: Add testing against NumPy 1.9 and matplotlib 1.4
PR #1939: ENH: Binstar build files
-
PR #1940: REF: refactor and speedup of mixed LME
PR #1937: ENH: Quick access to online documentation
PR #1942: DOC: Rename Change README type to rst
PR #1938: ENH: Enable Python 3.4 testing
PR #1924: Bug gee cov type 1906 rebased
PR #1870: robust covariance, cov_type in fit
PR #1859: BUG: Do not use negative indexing with k_ar == 0. Closes #1858.
PR #1914: BUG: LikelihoodModelResults.pvalues use df_resid_inference
PR #1899: TST: fix assert_equal for pandas index
PR #1895: Bug multicomp pandas
PR #1894: BUG fix more ix indexing cases for pandas compat
PR #1889: BUG: fix ytick positions closes #1561
PR #1887: Bug pandas compat asserts
PR #1888: TST test_corrpsd Test_Factor: add noise to data
PR #1886: BUG pandas 0.15 compatibility in grouputils labels
PR #1885: TST: corr_nearest_factor, more informative tests
PR #1884: Fix: Add compat code for pd.Categorical in pandas>=0.15
PR #1883: BUG: add _ctor_param to TransfGen distributions
PR #1872: TST: fix _infer_freq for pandas .14+ compat
PR #1867: Ref covtype fit
PR #1865: Disable tst distribution 1864
PR #1856: _spg_optim returns history of objective function values
PR #1854: BLD: Do not hard-code path for building notebooks. Closes #1249
PR #1851: MAINT: Cor nearest factor tests
PR #1847: Newton regularize
PR #1623: BUG Negbin fit regularized
PR #1797: BUG/ENH: fix and improve constant detection
PR #1770: TST: anova with -1 noconstant, add tests
PR #1837: Allow group variable to be passed as variable name when using formula
-
-
PR #1832: TST error with scipy 0.14 location distribution class
PR #1827: fit_regularized for linear models rebase 1674
PR #1825: Phreg 1312 rebased
-
PR #1824: Lme profile 1695 rebased
PR #1823: Gee cat subclass 1694 rebase
PR #1781: ENH: Glm add score_obs
PR #1821: Glm maint #1734 rebased
PR #1820: BUG: revert change to conf_int in PR #1819
-
PR #1772: REF: cov_params allow case of only cov_params_default is defined
PR #1771: REF numpy >1.9 compatibility, indexing into empty slice closes #1754
-
PR #1766: TST: TestProbitCG increase bound for fcalls closes #1690
PR #1709: BLD: Made build extensions more flexible
PR #1714: WIP: fit_constrained
PR #1706: REF: Use fixed params in test. Closes #910.
PR #1701: BUG: Fix faulty logic. Do not raise when missing=’raise’ and no missing data.
PR #1699: TST/ENH StandardizeTransform, reparameterize TestProbitCG
PR #1697: Fix for statsmodels/statsmodels#1689
PR #1692: OSL Example: redundant cell in example removed
PR #1688: Kshedden mixed rebased of #1398
PR #1629: Pull request to fix bandwidth bug in issue 597
PR #1666: Include pyx in sdist but do not install
PR #1683: TST: GLM shorten random seed closes #1682
PR #1681: Dotplot kshedden rebased of 1294
PR #1679: BUG: Fix problems with predict handling offset and exposure
PR #1677: Update docstring of RegressionModel.predict()
PR #1635: Allow offset and exposure to be used together with log link; raise except…
-
PR #1671: ENH: avoid hard-listed bandwidths – use present dictionary (+typos fixed)
PR #1643: Allow matrix structure in covariance matrices to be exploited
PR #1657: BUG: Fix refactor victim.
PR #1630: DOC: typo, “intercept”
PR #1619: MAINT: Dataset docs cleanup and automatic build of docs
PR #1612: BUG/ENH Fix negbin exposure #1611
PR #1610: BUG/ENH fix llnull, extra kwds to recreate model
PR #1582: BUG: wls_prediction_std fix weight handling, see 987
PR #1613: BUG: Fix proportions allpairs #1493
PR #1607: TST: adjust precision, CI Debian, Ubuntu testing
PR #1603: ENH: Allow start_params in GLM
PR #1600: CLN: Regression plots fixes
PR #1592: DOC: Additions and fixes
PR #1520: CLN: Refactored so that there is no longer a need for 2to3
PR #1585: Cor nearest 1384 rebased
PR #1553: Gee maint 1528 rebased
PR #1583: BUG: For ARMA(0,0) ensure 1d bse and fix summary.
PR #1580: DOC: Fix links. [skip ci]
PR #1572: DOC: Fix link title [skip ci]
PR #1566: BLD: Fix copy paste path error for >= 3.3 Windows builds
PR #1524: ENH: Optimize Cython code. Use scipy blas function pointers.
PR #1560: ENH: Allow ARMA(0,0) in order selection
PR #1559: MAINT: Recover lost commits from vbench PR
PR #1554: Silenced test output introduced in medcouple
PR #1234: ENH: Robust skewness, kurtosis and medcouple measures
PR #1484: ENH: Add naive seasonal decomposition function
PR #1551: COMPAT: Fix failing test on Python 2.6
PR #1472: ENH: using human-readable group names instead of integer ids in MultiComparison
PR #1437: ENH: accept non-int definitions of cluster groups
PR #1550: Fix test gmm poisson
PR #1549: TST: Fix locally failing tests.
PR #1121: WIP: Refactor optimization code.
PR #1547: COMPAT: Correct bit_length for 2.6
PR #1545: MAINT: Fix missed usage of deprecated tools.rank
PR #1196: REF: ensure O(N log N) when using fft for acf
PR #1154: DOC: Add links for build machines.
PR #1546: DOC: Fix link to wrong notebook
PR #1383: MAINT: Deprecate rank in favor of np.linalg.matrix_rank
PR #1432: COMPAT: Add NumpyVersion from scipy
PR #1438: ENH: Option to avoid “center” environment.
PR #1544: BUG: Travis miniconda
PR #1510: CLN: Improve warnings to avoid generic warnings messages
PR #1543: TST: Suppress RuntimeWarning for L-BFGS-B
PR #1507: CLN: Silence test output
PR #1540: BUG: Correct derivative for exponential transform.
PR #1536: BUG: Restores coveralls for a single build
PR #1535: BUG: Fixes for 2.6 test failures, replacing astype(str) with apply(str)
PR #1523: Travis miniconda
PR #1533: DOC: Fix link to code on github
PR #1531: DOC: Fix stale links with linkcheck
-
PR #1527: DOCS: Update docs add FAQ page
PR #1525: DOC: Update with Python 3.4 build notes
PR #1518: DOC: Ask for release notes and example.
PR #1516: DOC: Update examples contributing docs for current practice.
PR #1517: DOC: Be clear about data attribute of Datasets
PR #1515: DOC: Fix broken link
PR #1514: DOC: Fix formula import convention.
PR #1506: BUG: Format and decode errors in Python 2.6
PR #1505: TST: Test co2 load_data for Python 3.
PR #1504: BLD: New R versions require NAMESPACE file. Closes #1497.
PR #1483: ENH: Some utility functions for working with dates
PR #1482: REF: Prefer filters.api to __init__
PR #1481: ENH: Add weekly co2 dataset
PR #1474: DOC: Add plots for standard filter methods.
PR #1471: DOC: Fix import
PR #1470: DOC/BLD: Log code exceptions from nbgenerate
PR #1469: DOC: Fix bad links
PR #1468: MAINT: CSS fixes
PR #1463: DOC: Remove defunct argument. Change default kw. Closes #1462.
PR #1452: STY: import pandas as pd
PR #1458: BUG/BLD: exclude sandbox in relative path, not absolute
PR #1447: DOC: Only build and upload docs if we need to.
PR #1445: DOCS: Example landing page
PR #1436: DOC: Fix auto doc builds.
PR #1431: DOC: Add default for getenv. Fix paths. Add print_info
PR #1429: MAINT: Use ip_directive shipped with IPython
PR #1427: TST: Make tests fit quietly
PR #1424: ENH: Consistent results for transform_slices
PR #1421: ENH: Add grouping utilities code
PR #1419: Gee 1314 rebased
PR #1414: TST temporarily rename tests probplot other to skip them
PR #1403: Bug norm expan shapes
PR #1417: REF: Let subclasses keep kwds attached to data.
PR #1416: ENH: Make handle_data overwritable by subclasses.
PR #1410: ENH: Handle missing is none
PR #1402: REF: Expose missing data handling as classmethod
PR #1387: MAINT: Fix failing tests
PR #1406: MAINT: Tools improvements
PR #1404: Tst fix genmod link tests
PR #1396: REF: Multipletests reduce memory usage
PR #1380: DOC :Update vector_ar.rst
PR #1381: BLD: Do not check dependencies on egg_info for pip. Closes #1267.
-
PR #1375: STY: Remove unused imports and comment out unused libraries in setup.py
PR #1143: DOC: Update backport notes for new workflow.
PR #1374: ENH: Import tsaplots into tsa namespace. Closes #1359.
PR #1369: STY: Pep-8 cleanup
PR #1370: ENH: Support ARMA(0,0) models.
PR #1368: STY: Pep 8 cleanup
PR #1367: ENH: Make sure mle returns attach to results.
PR #1365: STY: Import and pep 8 cleanup
PR #1364: ENH: Get rid of hard-coded lbfgs. Closes #988.
-
PR #1361: ENH: Attach mlefit to results not model.
PR #1360: ENH: Import adfuller into tsa namespace
PR #1346: STY: PEP-8 Cleanup
PR #1344: BUG: Use missing keyword given to ARMA.
PR #1340: ENH: Protect against ARMA convergence failures.
PR #1334: ENH: ARMA order select convenience function
-
PR #1336: REF: Get rid of plain assert.
PR #1333: STY: __all__ should be after imports.
PR #1332: ENH: Add Bunch object to tools.
PR #1331: ENH: Always use unicode.
PR #1329: BUG: Decode metadata to utf-8. Closes #1326.
PR #1330: DOC: Fix typo. Closes #1327.
PR #1185: Added support for pandas when pandas was installed directly from git trunk
PR #1315: MAINT: Change back to path for build box
PR #1305: TST: Update hard-coded path.
PR #1290: ENH: Add seasonal plotting.
PR #1296: BUG/TST: Fix ARMA forecast when start == len(endog). Closes #1295
PR #1292: DOC: cleanup examples folder and webpage
PR #1286: Make sure PeriodIndex passes through tsa. Closes #1285.
PR #1271: Silverman enhancement - Issue #1243
PR #1264: Doc work GEE, GMM, sphinx warnings
PR #1179: REF/TST: ProbPlot now uses resettable_cache and added some kwargs to plotting fxns
-
PR #1258: Gmm new rebased
PR #1255: ENH add GEE to genmod
PR #1254: REF: Results.predict convert to array and adjust shape
PR #1192: TST: enable tests for llf after change to WLS.loglike see #1170
-
PR #1233: sandbox kernels bugs uniform kernel and confint
PR #1240: Kde weights 1103 823
PR #1228: Add default value tags to adfuller() docs
-
PR #1230: BUG: numerical precision in resid_pearson with perfect fit #1229
PR #1214: Compare lr test rebased
PR #1200: BLD: do not install *.pyx *.c MANIFEST.in
PR #1202: MAINT: Sort backports to make applying easier.
PR #1157: Tst precision master
PR #1161: add a fitting interface for simultaneous log likelihood and score, for lbfgs, tested with MNLogit
PR #1160: DOC: update scipy version from 0.7 to 0.9.0
PR #1147: ENH: add lbfgs for fitting
PR #1156: ENH: Raise on 0,0 order models in AR(I)MA. Closes #1123
PR #1149: BUG: Fix small data issues for ARIMA.
PR #1092: Fixed duplicate svd in RegressionModel
PR #1139: TST: Silence tests
-
PR #1088: ENH: add predict_prob to poisson
PR #1125: REF/BUG: Some GLM cleanup. Used trimmed results in NegativeBinomial variance.
PR #1124: BUG: Fix ARIMA prediction when fit without a trend.
PR #1118: DOC: Update gettingstarted.rst
PR #1117: Update ex_arma2.py
PR #1107: REF: Deprecate stand_mad. Add center keyword to mad. Closes #658.
PR #1089: ENH: exp(poisson.logpmf()) for poisson better behaved.
PR #1077: BUG: Allow 1d exog in ARMAX forecasting.
PR #1075: BLD: Fix build issue on some versions of easy_install.
PR #1071: Update setup.py to fix broken install on OSX
PR #1052: DOC: Updating contributing docs
PR #1136: RLS: Add IPython tools for easier backporting of issues.
PR #1091: DOC: minor git typo
PR #1082: coveralls support
PR #1072: notebook examples title cell
PR #1056: Example: reg diagnostics
PR #1057: COMPAT: Fix py3 caching for get_rdatasets.
PR #1045: DOC/BLD: Update from nbconvert to IPython 1.0.
PR #1026: DOC/BLD: Add LD_LIBRARY_PATH to env for docs build.
Issues (252):
Issue #2040: enh: fractional Logit, Probit
Issue #1220: missing in extra data (example sandwiches, robust covariances)
Issue #1877: error with GEE on missing data.
Issue #805: nan with categorical in formula
Issue #2036: test in links require exact class so Logit cannot work in place of logit
Issue #2010: Go over deprecations again for 0.6.
Issue #1303: patsy library not automatically installed
Issue #2024: genmod Links numerical improvements
Issue #2025: GEE requires exact import for cov_struct
Issue #2017: Matplotlib warning about too many figures
Issue #724: check warnings
Issue #1562: ARIMA forecasts are hard-coded for d=1
Issue #880: DataFrame with bool type not cast correctly.
Issue #1992: MixedLM style
Issue #322: acf / pacf do not work on pandas objects
Issue #1317: AssertionError: attr is not equal [dtype]: dtype(‘object’) != dtype(‘datetime64[ns]’)
Issue #1875: dtype bug object arrays (raises in clustered standard errors code)
Issue #1842: dtype object, glm.fit() gives AttributeError: sqrt
Issue #1300: Doc errors, missing
Issue #1164: RLM cov_params, t_test, f_test do not use bcov_scaled
Issue #1019: 0.6.0 Roadmap
Issue #554: Prediction Standard Errors
Issue #333: ENH tools: squeeze in R export file
Issue #1990: MixedLM does not have a wrapper
Issue #1897: Consider depending on setuptools in setup.py
Issue #2003: pip install now fails silently
Issue #1852: do not cythonize when cleaning up
Issue #1991: GEE formula interface does not take offset/exposure
Issue #442: Wrap x-12 arima
Issue #1993: MixedLM bug
Issue #1917: API: GEE access to genmod.covariance_structure through api
Issue #1785: REF: rename jac -> score_obs
Issue #1969: pacf has incorrect standard errors for lag 0
Issue #1434: A small bug in GenericLikelihoodModelResults.bootstrap()
Issue #1408: BUG test failure with tsa_plots
Issue #1337: DOC: HCCM are now available for WLS
Issue #546: influence and outlier documentation
Issue #1532: DOC: Related page is out of date
Issue #1386: Add minimum matplotlib to docs
Issue #1068: DOC: keeping documentation of old versions on sourceforge
Issue #329: link to examples and datasets from module pages
Issue #1804: PDF documentation for statsmodels
Issue #202: Extend robust standard errors for WLS/GLS
Issue #1519: Link to user-contributed examples in docs
Issue #1053: inconvenient: logit when endog is (1,2) instead of (0,1)
Issue #1555: SimpleTable: add repr html for ipython notebook
Issue #1366: Change default start_params to .1 in ARMA
Issue #1869: yule_walker (from statsmodels.regression) raises exception when given an integer array
Issue #1651: statsmodels.tsa.ar_model.ARResults.predict
Issue #1738: GLM robust sandwich covariance matrices
Issue #1779: Some directories under statsmodels dont have __init_.py
Issue #1242: No support for (0, 1, 0) ARIMA Models
Issue #1571: expose webuse, use cache
Issue #1860: ENH/BUG/DOC: Bean plot should allow for separate widths of bean and violins.
Issue #1831: TestRegressionNM.test_ci_beta2 i386 AssertionError
Issue #1079: bugfix release 0.5.1
Issue #1338: Raise Warning for HCCM use in WLS/GLS
Issue #1430: scipy min version / issue
Issue #276: memoize, last argument wins, how to attach sandwich to Results?
Issue #1943: REF/ENH: LikelihoodModel.fit optimization, make hessian optional
Issue #1957: BUG: Re-create OLS model using _init_keys
Issue #1905: Docs: online docs are missing GEE
Issue #1898: add python 3.4 to continuous integration testing
Issue #1684: BUG: GLM NegativeBinomial: llf ignores offset and exposure
Issue #1256: REF: GEE handling of default covariance matrices
Issue #1760: Changing covariance_type on results
Issue #1906: BUG: GEE default covariance is not used
Issue #1931: BUG: GEE subclasses NominalGEE do not work with pandas exog
Issue #1904: GEE Results does not have a Wrapper
Issue #1918: GEE: required attributes missing, df_resid
Issue #1919: BUG GEE.predict uses link instead of link.inverse
Issue #1858: BUG: arimax forecast should special case k_ar == 0
Issue #1903: BUG: pvalues for cluster robust, with use_t do not use df_resid_inference
Issue #1243: kde silverman bandwidth for non-gaussian kernels
Issue #1866: Pip dependencies
Issue #1850: TST test_corr_nearest_factor fails on Ubuntu
Issue #292: python 3 examples
Issue #1868: ImportError: No module named compat [ from statsmodels.compat import lmap ]
Issue #1890: BUG tukeyhsd nan in group labels
Issue #1891: TST test_gmm outdated pandas, compat
Issue #1561: BUG plot for tukeyhsd, MultipleComparison
Issue #1864: test failure sandbox distribution transformation with scipy 0.14.0
Issue #576: Add contributing guidelines
Issue #1873: GenericLikelihoodModel is not picklable
Issue #1822: TST failure on Ubuntu pandas 0.14.0 , problems with frequency
Issue #1249: Source directory problem for notebook examples
Issue #1855: anova_lm throws error on models created from api.ols but not formula.api.ols
Issue #1853: a large number of hardcoded paths
Issue #1792: R² adjusted strange after including interaction term
Issue #1794: REF: has_constant, k_constant, include implicit constant detection in base
Issue #1454: NegativeBinomial missing fit_regularized method
Issue #1615: REF DRYing fit methods
Issue #1453: Discrete NegativeBinomialModel regularized_fit ValueError: matrices are not aligned
Issue #1836: BUG Got an TypeError trying to import statsmodels.api
Issue #1829: BUG: GLM summary show “t” use_t=True for summary
Issue #1828: BUG summary2 does not propagate/use use_t
Issue #1812: BUG/ REF conf_int and use_t
Issue #1835: Problems with installation using easy_install
Issue #1801: BUG ‘f_gen’ missing in scipy 0.14.0
Issue #1803: Error revealed by numpy 1.9.0r1
Issue #1834: stackloss
Issue #1728: GLM.fit maxiter=0 incorrect
Issue #1795: singular design with offset ?
Issue #1730: ENH/Bug cov_params, generalize, avoid ValueError
Issue #1754: BUG/REF: assignment to slices in numpy >= 1.9 (emplike)
Issue #1409: GEE test errors on Debian Wheezy
Issue #1521: ubuntu failures: tsa_plot and grouputils
Issue #1415: test failure test_arima.test_small_data
Issue #1213: df_diff in anova_lm
Issue #1323: Contrast Results after t_test summary broken for 1 parameter
Issue #109: TestProbitCG failure on Ubuntu
Issue #1690: TestProbitCG: 8 failing tests (Python 3.4 / Ubuntu 12.04)
Issue #1763: Johansen method does not give correct index values
Issue #1761: doc build failures: ipython version ? ipython directive
Issue #1762: Unable to build
Issue #1745: UnicodeDecodeError raised by get_rdataset(“Guerry”, “HistData”)
Issue #611: test failure foreign with pandas 0.7.3
Issue #1700: faulty logic in missing handling
Issue #1648: ProbitCG failures
Issue #1689: test_arima.test_small_data: SVD fails to converge (Python 3.4 / Ubuntu 12.04)
Issue #597: BUG: nonparametric: kernel, efficient=True changes bw even if given
Issue #1606: BUILD from sdist broken if cython available
Issue #1246: test failure test_anova.TestAnova2.test_results
Issue #50: t_test, f_test, model.py for normal instead of t-distribution
Issue #1655: newey-west different than R?
Issue #1682: TST test failure on Ubuntu, random.seed
Issue #1614: docstring for regression.linear_model.RegressionModel.predict() does not match implementation
Issue #1318: GEE and GLM scale parameter
Issue #519: L1 fit_regularized cleanup, comments
Issue #651: add structure to example page
Issue #1067: Kalman Filter convergence. How close is close enough?
Issue #1281: Newton convergence failure prints warnings instead of warning
Issue #1628: Unable to install statsmodels in the same requirements file as numpy, pandas, etc.
Issue #617: Problem in installing statsmodels in Fedora 17 64-bit
Issue #935: ll_null in likelihoodmodels discrete
Issue #704: datasets.sunspot: wrong link in description
Issue #1222: NegativeBinomial ignores exposure
Issue #1611: BUG NegativeBinomial ignores exposure and offset
Issue #1608: BUG: NegativeBinomial, llnul is always default ‘nb2’
Issue #1221: llnull with exposure ?
Issue #1493: statsmodels.stats.proportion.proportions_chisquare_allpairs has hardcoded value
Issue #1260: GEE test failure on Debian
Issue #1261: test failure on Debian
Issue #443: GLM.fit does not allow start_params
Issue #1602: Fitting GLM with a pre-assigned starting parameter
Issue #1601: Fitting GLM with a pre-assigned starting parameter
Issue #890: regression_plots problems (pylint) and missing test coverage
Issue #1598: Is “old” string formatting Python 3 compatible?
Issue #1589: AR vs ARMA order specification
Issue #1134: Mark knownfails
Issue #1259: Parameterless models
Issue #616: python 2.6, python 3 in single codebase
Issue #1586: Kalman Filter errors with new pyx
Issue #1565: build_win_bdist*_py3*.bat are using the wrong compiler
Issue #843: UnboundLocalError When trying to install OS X
Issue #713: arima.fit performance
Issue #367: unable to install on RHEL 5.6
Issue #1548: testtransf error
Issue #1478: is sm.tsa.filters.arfilter an AR filter?
Issue #1420: GMM poisson test failures
Issue #1145: test_multi noise
Issue #1539: NegativeBinomial strange results with bfgs
Issue #936: vbench for statsmodels
Issue #1153: Where are all our testing machines?
Issue #1500: Use Miniconda for test builds
Issue #1526: Out of date docs
Issue #1311: BUG/BLD 3.4 compatibility of cython c files
Issue #1513: build on osx -python-3.4
Issue #1497: r2nparray needs NAMESPACE file
Issue #1502: coveralls coverage report for files is broken
Issue #1501: pandas in/out in predict
Issue #1494: truncated violin plots
Issue #1443: Crash from python.exe using linear regression of statsmodels
Issue #1462: qqplot line kwarg is broken/docstring is wrong
Issue #1457: BUG/BLD: Failed build if “sandbox” anywhere in statsmodels path
Issue #1441: wls function: syntax error “unexpected EOF while parsing” occurs when name of dependent variable starts with digits
Issue #1428: ipython_directive does not work with ipython master
Issue #1385: SimpleTable in Summary (e.g. OLS) is slow for large models
Issue #1399: UnboundLocalError: local variable ‘fittedvalues’ referenced before assignment
Issue #1377: TestAnova2.test_results fails with pandas 0.13.1
Issue #1394: multipletests: reducing memory consumption
Issue #1267: Packages cannot have both pandas and statsmodels in install_requires
Issue #1359: move graphics.tsa to tsa.graphics
Issue #356: docs take up a lot of space
Issue #988: AR.fit no precision options for fmin_l_bfgs_b
Issue #990: AR fit with bfgs: large score
Issue #14: arma with exog
Issue #1348: reset_index + set_index with drop=False
Issue #1343: ARMA does not pass missing keyword up to TimeSeriesModel
Issue #1326: formula example notebook broken
Issue #1327: typo in docu-code for “Outlier and Influence Diagnostic Measures”
Issue #1309: Box-Cox transform (some code needed: lambda estimator)
Issue #1059: sm.tsa.ARMA making ma invertibility
Issue #1295: Bug in ARIMA forecasting when start is int len(endog) and dates are given
Issue #1285: tsa models fail on PeriodIndex with pandas
Issue #1269: KPSS test for stationary processes
Issue #1268: Feature request: Exponential smoothing
Issue #1250: DOCs error in var_plots
Issue #1032: Poisson predict breaks on list
Issue #347: minimum number of observations - document or check ?
Issue #1170: WLS log likelihood, aic and bic
Issue #1187: sm.tsa.acovf fails when both unbiased and fft are True
Issue #1239: sandbox kernels, problems with inDomain
Issue #1231: sandbox kernels confint missing alpha
Issue #1245: kernels cosine differs from Stata
Issue #823: KDEUnivariate with weights
Issue #1229: precision problems in degenerate case
Issue #1219: select_order
Issue #1206: REF: RegressionResults cov-HCx into cached attributes
Issue #1152: statsmodels failing tests with pandas master
Issue #1195: pyximport.install() before import api crash
Issue #1066: gmm.IV2SLS has wrong predict signature
Issue #1186: OLS when exog is 1d
Issue #1113: TST: precision too high in test_normality
Issue #1159: scipy version is still >= 0.7?
Issue #1108: SyntaxError: unqualified exec is not allowed in function ‘test_EvalEnvironment_capture_flag
Issue #1116: Typo in Example Doc?
Issue #1123: BUG : arima_model._get_predict_out_of_sample, ignores exogenous of there is no trend ?
Issue #1155: ARIMA - The computed initial AR coefficients are not stationary
Issue #979: Win64 binary cannot find Python installation
Issue #1046: TST: test_arima_small_data_bug on current master
Issue #1146: ARIMA fit failing for small set of data due to invalid maxlag
Issue #1081: streamline linear algebra for linear model
Issue #1138: BUG: pacf_yw does not demean
Issue #1127: Allow linear link model with Binomial families
Issue #1122: no data cleaning for statsmodels.genmod.families.varfuncs.NegativeBinomial()
Issue #658: robust.mad is not being computed correctly or is non-standard definition; it returns the median
Issue #1076: Some issues with ARMAX forecasting
Issue #1073: easy_install sandbox violation
Issue #1115: EasyInstall Problem
Issue #1106: bug in robust.scale.mad?
Issue #1102: Installation Problem
Issue #1084: DataFrame.sort_index does not use ascending when then value is a list with a single element
Issue #393: marginal effects in discrete choice do not have standard errors defined
Issue #1078: Use pandas.version.short_version
Issue #96: deepcopy breaks on ResettableCache
Issue #1055: datasets.get_rdataset string decode error on python 3
Issue #46: tsa.stattools.acf confint needs checking and tests
Issue #957: ARMA start estimate with numpy master
Issue #62: GLSAR incorrect initial condition in whiten
Issue #1021: from_formula() throws error - problem installing
Issue #911: noise in stats.power tests
Issue #472: Update roadmap for 0.5
Issue #238: release 0.5
Issue #1006: update nbconvert to IPython 1.0
Issue #1038: DataFrame with integer names not handled in ARIMA
Issue #1036: Series no longer inherits from ndarray
Issue #1028: Test fail with windows and Anaconda - Low priority
Issue #676: acorr_breush_godfrey undefined nlags
Issue #922: lowess returns inconsistent with option
Issue #425: no bse in robust with norm=TrimmedMean
Issue #1025: add_constant incorrectly detects constant column | https://www.statsmodels.org/stable/release/version0.6.html | CC-MAIN-2020-29 | refinedweb | 4,478 | 51.28 |
Alright.. let me give it a try. I was not seeing the NPE in the tests I ran. -- bk On 01/25/2010 01:15 PM, frederic dangtran orange-ftgroup com wrote:
On Jan 18, 2010, at 3:44 PM, Bryan Kearney wrote:I have just released 0.4.1 of libvirt java. There are 2 main items in this release: - Better null checking in for Scheduled Parameters which should fix the issues reported on the list. - Error Callbacks to provide better handling of errors encountered by libvirt (virConnSetErrorFunc and virSetErrorFunc). You can access the latest version via the following means: Source Code:;a=summary Bundled Source (tarball and SRPM): Maven: RPMS are making their way through F-11 and F12 build systems Thank you! -- bk -- libvir-list mailing list libvir-list redhat com <mailto:libvir-list redhat com> for the update, Bryan, but the problem still persists. In my setup (Xen hosts): Domain.getSchedulerParameters() still raises a NPE. In libvirt.h, _virSchedParameter is defined as follows using a union for the value: struct _virSchedParameter { char field[VIR_DOMAIN_SCHED_FIELD_LENGTH]; /* parameter name */ int type; /* parameter type */ union { int i; /* data for integer case */ unsigned int ui; /* data for unsigned integer case */ long long int l; /* data for long long integer case */ unsigned long long int ul; /* data for unsigned long long integer case */ double d; /* data for double case */ char b; /* data for char case */ } value; /* parameter value */ }; I believe the Java mapping of virSchedParameterValue should be a Union instead of a Structure: public class virSchedParameterValue extends Union {...} Regards, Frederic ------------------ Orange Labs 38-40 rue du General Leclerc 92794 Issy Moulineaux Cedex 9 FRANCE *********************************. ******************************** | https://www.redhat.com/archives/libvir-list/2010-January/msg00934.html | CC-MAIN-2014-15 | refinedweb | 272 | 50.06 |
Archive.
Review: MSDN Enhanced Search
For the past week and a half, I’ve been using, and evaluating, the new MSDN Enhanced Search.
The task? For Microsoft-based queries, use the MSDN search for a week (rather than google.com with site:msdn.microsoft.com) and compare expectations, results, and usability.
For the review, I’ll use a single query to provide comparison.
Search: “Sys.Application.add_init()”
Likes
1. I really like the RSS feeds. I can think of several ways, especially by product or technology, to consume those RSS feeds on our technical portals at the office and on my blog.
2. The autocomplete feature is very useful if you’re unsure of how something is spelt or want to browse through a namespace. For example, if you knew what you were looking for was in System.Web.Caching, you could type that in to the search box and let autocomplete simply return what falls under there. I’m not sure if this was the intended use, but it works quite nicely.
In addition, for those who know exactly what they’re looking for, the delay is enough that it doesn’t hinder a quick search.
Dislikes
1. I wish I could pre-refine my topics from the initial search page. Searching and THEN refining requires two steps, two page reloads, and, in it’s current build, about 15–20 seconds in page loads. If I’m searching for a query and know ahead of time that I just want to look at the MSDN Documentation, let me set that. 🙂
2. Filtering by Language sometimes filters out “correct” results. After our discussions, this appears to be less of a matter of the search engine and more to how articles and posts are tagged within the libraries. With this in mind, filtering by a specific version of language is almost useless.
3. Not being able to use the autocomplete functionality with FireFox is a real drag. I’m honestly not sure if this is an issue with FF3 or the MSDN search site, but from Firebug’s POV, I get a 400 error when I try to query.
UPDATE: 4–5 refreshes of the page in FireFox and it seems to work. Why? I’m not really sure. It seems the 400 error is more of a timeout than an actual error, but the GET request is only 200ms each time it fails. Odd.
4. Not so much a “dislike” as an “hmm”—I use the browser built-in search bars a lot. I rarely open up to a “search page” because of it. Unfortunately, the cool features of MSDN Enhanced Search (autocomplete, refinements, etc) require you to be on the page to use them. Perhaps a new searcher toolbar that adds these features into IE and FireFox could be made available OR a search bar (similar to Desktop Search) for Windows that I could toss down and always have access to MSDN resources.
Suggestions
1. Work on reducing the number of requests and load times (already discussions about this in the forums, but adding it to the list). We’re on a dedicated OC-3 line here at the office, but I’m impatient. 🙂
For example, the Google query requires 5 requests and 948 B for the first result page to come up (905 B of that from cache).
The MSDN Enhanced search requires 30 requests, 183 KB, and almost 5 seconds to download.
Repeating the same query over again narrows it down to only 7 requests (65 KB), but doesn’t seem to speed up the returns.
2. It’d be great if “Refine By’s” allowed you to toggle them on and off. In the current build, refining is an all or nothing. You can’t refine by “Blogs and Forums” by checking each one—you have to refine by Blogs, check the results, go back, refine by Forums, check the results. Time consuming and painful. On the forums, they’ve already noted that they’re checking into this—and I’m excited to see the results.
3. Work with the MSDN Documetation groups—if I parse out and am searching just for C# results, then have those preslugged as the language settings on the MSDN documentation. That’d be great! Per #2 in Dislikes, it’d be nice if I searched for “Func<T>” and filtered by C# 2008, that I’d get the C# 2008 (or .net 3.5) documentation for Func<T>.
4. It’d be great if, in future versions of MSDN, that searching for help in Visual Studio and other Microsoft products worked similar to Enhanced Search. Currently, the “help” in most Microsoft products leaves much to be desired and, like VS2008, is simply redirecting to msdn.microsoft.com anyway.
5. Different versions of documents are hard to disseminate unless you look at the URLs—which gets painfully slow if looking for a quick answer. In the example below, both documents point to information on System.Net.Mail; however, the first is for VS2008/.net 3.5 and the second is for VS2005/.net 2.0. You can only tell by the URL.
Conclusions
On a matter of scope—I see MSDN Enhanced Search as a means of searching MSDN documentation and, to a degree, forums. If I need to know what methods are part of an object or a specific syntax, this will be the place to come. I really do like the Enhanced Search over all other existing Microsoft searches.
Unfortunately, 9/10 of the information I search for tends to come from sources outside Microsoft (non-MSFT blogs, forums, etc)—non usage/technique queries. It’s hard to justify using MSDN Enhanced Search to JUST search Microsoft materials and then go “oh, well, didn’t find it, guess I’ll hit Google”—and then have to wade through those same Microsoft materials as well as the rest of the world. Just food for thought.
I want to thank Chris Slemp for the opportunity to provide feedback and test out the new functionality for the MSDN Enhanced Search. While I’m a Googler to the core, I look forward to seeing how the MSDN search evolves and improves—and how I can integrate it into my searches.
Lost in translation…
Michael sent me this line of text in German yesterday…
Auslieferung oder Würfel!
Now, me knowing absolutely ZERO German (except swear words, of course), hit up Google Translate. Google returned:
Gmail –.
Custom
Creating | https://tiredblogger.wordpress.com/category/google/ | CC-MAIN-2017-34 | refinedweb | 1,083 | 71.14 |
Introduction to the Reactive Framework Part IV
In the previous post in this series, we covered how to turn .NET events into first class values through IObservable instances. By doing so, we were able to do much more interesting things than just subscribe and unsubscribe, instead we were able to create a mouse drag event with little effort through composition. In this post, let’s look at going from push to pull by turning collections into IObservable<T> instances.
Let’s get caught up to where we are today:
- Part I – Introduction
- Part II – Duality of Enumerable/Observable
- Part III – From Events to Observables
From IEnumerables To Observables
As you may remember from the first post and second post in this series, we covered going from IEnumerable<T> to IObservable<T> and the duality between the two. But, how can we switch back and forth between them? Remember that we can create an IObservable from a couple of angles. Let’s first create one by using the chaining together Empty and StartsWith combinators on the Observable class to create an IObservable<T>. Note that this is not the publicly available release of the Reactive Framework, so bear with any name changes.
var observable = Observable.Empty<int>() .StartWith(1) .StartWith(2) .StartWith(3);
This allows me to start out with an empty IObservable<int> and then pre-append the value to the front of the instance, so in this case it would render 3, 2, 1. Next, let’s look at how we might generate a sequence IObservable from 1 to 10.
var observable = Observable.Generate( 1, // Initial value value => value <= 10, // Predicate value => value, // Selector value => value + 1); // Iterator observable.Subscribe(Console.WriteLine);
In this instance, we supply an initial value, then a predicate to determine when to stop, a result selector, and then finally an iterator. There are plenty of overloads as well on the Generate to suit your needs when creating IObservable<T> values. But, what about taking existing IEnumerable<T> values and converting them to IObservable<T> values? One could use the the Create function which allows us to create arbitrary IObservable<T> instances.
var enumerable = Enumerable.Range(1, 10); var observable = Observable.Create<int>(observer => { try { foreach (var item in enumerable) observer.OnNext(item); observer.OnCompleted(); } catch (Exception exception) { observer.OnError(exception); } return () => { }; }); observable.Subscribe( value => Console.WriteLine(value), exn => Console.WriteLine(exn.ToString()));
What we’re doing in the above code is using the Create method which gives us an IObserver<T> that we can post values to. In this case, we’re iterating through a collection and for each item, we’re calling OnNext. At the end of the iteration, we call the OnCompleted method which indicates that there are no more values. If there were some sort of exception when iterating the values, it would be caught and the exception posted to the observer. We can then decide how to handle it during our Subscribe method call, if at all. Finally, we return an Action which is to be called once we unsubscribe from the given IObserver<T>, which in this instance, we do nothing. That’s all fine and good, but there is an easier way of course, by using the ToObservable extension method.
var enumerable = Enumerable.Range(1, 10); var observable = enumerable.ToObservable(); observable.Subscribe(Console.WriteLine);
Going from IEnumerable<T> to IObservable<T> as you an see is quite easy. Just as well, going back is easy as well through either of two methods, one being calling the ToEnumerable extension method, and the other being the GetEnumerator method.
// To Observable var enumerable = Enumerable.Range(1, 10); var observable = enumerable.ToObservable(); // And back again var enumerableAgain = observable.ToEnumerable(); var enumerator = observable.GetEnumerator();
This ultimately leaves us in control of when we want to switch between the pull and push model, depending on our circumstances. It’s sort of like a buy one get one free in that respect. What makes this interesting is to take a collection and spread it out to multiple instances, for example reading in a file and then you could have multiple subscriptions each process the data in turn. Those possibilities are endless if we want to do certain actions concurrently.
var text = File.ReadAllLines("DocumentToProcess.txt"); var textObservable = text.AsObservable(); // Process concurrently var textLetterSub = text.Subscribe(CountLetters); var textWordSub = text.Subscribe(CountWords); var textVowelSub = text.Subscribe(CountVowels);
There are also more things to come when dealing with collections that we’ll get into in later posts in this series, but this is enough for as well as turning Tasks and Asynchronous Methods into Observables. | https://weblogs.asp.net/podwysocki/introduction-to-the-reactive-framework-part-iv | CC-MAIN-2017-47 | refinedweb | 768 | 57.37 |
Three years ago I wrote this tutorial. Things have changed in the Java and Spring landscape, so let’s see how much easier it is now to write a simple Spring webapplication.
Project setup
A while back you had to setup your own Maven project, import all the dependencies you need, set the correct Maven plugins, … . With Spring Boot it’s a lot easier. You go to start.spring.io and you just select the dependencies you want, you import the project and you’re done! Neat, don’t you think? According to Josh Long it is the second greatest place on the web and you should keep it under your pillow!
Now, since I’m going to create a web project, all I need to do is to enter “Web” in the dependencies textbox and click the Web dependency to add it to your application.
Do the same now for “Thymeleaf” and then you can generate the project, unzip it and import it in your IDE. You now have a completely working Spring application! You don’t even have to download Maven, because it comes with a Maven wrapper (mvnw) that can be executed and will install Maven for you.
Model
For this application I’m going to write a simple model class called Superhero, in which I will define four fields with getters/setters and a constructor to initialize the fields:
public class Superhero { private String firstName; private String lastName; private String name; private boolean good; public Superhero(String firstName, String lastName, String name, boolean good) { super(); this.firstName = firstName; this.lastName = lastName; this.name = name; this.good = good; }; } }
Controller
The next part is the controller. With Spring Web MVC you can easily follow the MVC design pattern. Simply create a new class called SuperheroController and annotate it with
@Controller.
Another annotation I’m going to add to the class is
@RequestMapping("/superhero") to make sure that the requests for the controller are all beneath the
"/superhero" path.
Inside the controller I’m going to write a single method to return two superheroes/villains:
@RequestMapping public ModelAndView getSuperheroes() { return new ModelAndView("superheroes", "superheroes", Arrays.asList( new Superhero("Clark", "Kent", "Superman", true), new Superhero("Siobhan", "McDougal", "Silver Banshee", false) )); }
Obviously in real life code you will create proper services to encapsulate the data, but in this tutorial I’m just gonna use it this way.
We use
ModelAndView to define:
- the view name, which is the HTML template that we will define later. In this case we use `”superheroes”` which will resolve to a file called superheroes.html inside the src/main/resources/public folder
- The model name, which is the name of the model (in this case the list of superheroes) that can be referred to in the view
- The model itself, in this case a list of two superheroes/villains.
View
The last part of the application is the view itself. If you used start.spring.io you will already have a folder called src/main/resources/templates, create a file called superheroes.html inside it, open it and add the following content:
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="" /> </head> <body> <div class="container"> <table class="table"> <thead> <tr> <th>#</th> <th>Hero name</th> <th>Real name</th> <th>Good</th> </tr> </thead> <tbody> <!-- TODO: Content --> </tbody> </table> </div> </body> </html>
I’m using a simple table here to show the list of heroes and villains. There’s nothing special yet in this HTML file. We’re just using Twitter Bootstrap here to make our page look a bit decent.
Anyways, inside the
<tbody> tag we now have to dynamically add rows. With Thymeleaf you use the
th:each attribute for that. Inside the row we have to show each property, which can easily be done with the
th:text attribute.
To show the row I use the following code:
>
As you can see, we use
th:each to loop over the superheroes. The name
${superheroes} comes from the model name, which we provided earlier in the controller. Also, we define
hero to be the current hero during the loop, and with the
status object we can easily retrieve extra information, like
${status.count} to have a counter for each iteration.
The bottom side uses
th:if and
th:unless to show a different icon for when the
${hero.good} property is
true or not.
Running the application
Running the
Application class as a Java application, or executing the
mvn spring-boot:run command will run the application. For several IDE’s you can also download a plugin that allows you to run the application as a Spring boot app.
If you go to, you’ll see that the application already works.
Configuring Spring Boot
While the application isn’t really fancy, we only wrote about 70 lines of Java code, of which more than half of it are getters and setters and other code that could be generated, but we have a functional web application without having to install anything else except an IDE and a JDK.
Spring Boot does a lot of stuff out of the box, but you can usually configure this as well.
For example, if you look at the src/main/resources folder you’ll see that there is an application.properties file. If we edit this file and add the following properties:
server.context-path=/my-app server.port=9000
And you run the application again, you’ll see that the previous URL will no longer work, in stead of that you have to go to.
Also, Thymeleaf can be strict sometimes, and it caches the templates which makes development a bit harder. To disable caching you can add the following property:
spring.thymeleaf.cache=false
If you don’t close a tag (for example
<br> or
<link rel="" href="">), or you use a custom element or a custom attribute (like AngularJS directives as
ng-app,
ng-if, …), it will fail to compile. To make it less strict you can use the following property:
spring.thymeleaf.mode=LEGACYHTML5
You will also have to add the nekhohtml5 dependency:
<dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.15</version> </dependency>
If you would be using special HTML attributes, or you’re not properly closing your elements, then your code will now be working again! You can test it out by changing the
<link /> tag for the Bootstrap CSS, remove the
/> and simply replace it by
>. While browsers can perfectly render it, Thymeleaf will throw an error (unless you use LEGACYHTML5).
Conclusion
Three years ago I wrote a similar article to this, but using vanilla Spring 2.5, XML bean configurations, web descriptors, … . The world change a lot and became a lot easier.
In the next few months I will be rewriting most of my old Spring-related articles, translating them from Dutch to English and updating the content to reflect the current state of the Spring framework. | http://g00glen00b.be/spring-webapp/ | CC-MAIN-2017-26 | refinedweb | 1,163 | 62.68 |
A Button Graphicsitem for use in Stellarium's graphic widgets. More...
#include <StelGuiItems.hpp>
A Button Graphicsitem for use in Stellarium's graphic widgets.
Definition at line 65 of file StelGuiItems.hpp.
Button states.
Definition at line 99 of file StelGuiItems.hpp.
Constructor.
Constructor.
Get the width of the button image.
The width is based on pixOn.
Definition at line 106 of file StelGuiItems.hpp.
Emitted when the hover state change.
Get whether the button is checked.
Definition at line 102 of file StelGuiItems.hpp.
Set the background pixmap of the button.
set whether the button is checked
Set the button opacity.
Definition at line 109 of file StelGuiItems.hpp.
Triggered when the button state changes.
Triggered when the button state changes. | http://stellarium.org/doc/0.13/classStelButton.html | CC-MAIN-2017-51 | refinedweb | 122 | 63.76 |
Using Thumbnail Images in a List Control
Introduction:This purpose of this article is to show you how to display thumbnail images in a list control.
The demo project is very straightforward:
- It goes through a directory user specified to search for all the bitmap files, and store their names in a dynamic vector, "m_VectorImageNames".
- On clicking the "Load" button, It draws the thumbnails of the bitmaps in the list control by calling the function "DrawThumbnails ()".
- Draw the selected thumbnail image to fit into the image display area.
Acknowledgements:
- Encapsulated Dib API - by Jorge Lodos
- Class for Browsing shell namespace with your own dialog - by Selom Ofori
Implementing Brightness to this applicationPosted by wencong on 03/15/2004 11:14pm
hi..anyone have any ideas on how to implement brightness adjustment into this application.. for example : user is able to adjust the brightness of the selected thumbnail image in the picture box. thanks
HELP!Posted by wencong on 03/17/2004 09:54pm
some1 who read this comment pls do try to help me...thanks =pReply
HelpPosted by Legacy on 02/19/2004 12:00am
Originally posted by: yves
When i change this project to VC++ 7.0, it gt an error saying nCount>=0. this error occurs when i press the browse button... Anyone can help me
thank a lotReply
How to print the imagePosted by Legacy on 05/20/2003 12:00am
Originally posted by: Daniel
How can I print The Image??Reply
Demo project using GDI+ to display BMP, JPEG, GIF, TIFF, PNG thumbnailsPosted by Legacy on 04/08/2003 12:00am
Originally posted by: Yi Ren
A lof people ask me to give a demo. project to show the thumbnails of images other than BMP. This demo. program uses the new GDI+ to manipulate the images with BMP. JPEG, GIF, TIFF and PNG formats. If you want to know something about GDI+, refer to an article in the MSDN magzine at the link below:
Yi
Please give a Demo code about use JPG image. Thanks!Posted by Legacy on 02/17/2003 12:00am
Originally posted by: chequan
Thanks!Reply
Please give a Demo code about use JPG image. Thanks!Posted by Legacy on 02/17/2003 12:00am
Originally posted by: chequan
Thanks!Reply
Fantastic!!Posted by Legacy on 10/31/2002 12:00am
Originally posted by: Denis
Fantastic
Reply
Selected item(s)Posted by Legacy on 10/15/2001 12:00am
Originally posted by: Enrico Fichtner
How to render the selected item(s) differently than they are in your app? The standard style of selection looks ugly with 'real' images (my oppinion).Reply
TESTPosted by Legacy on 07/31/2001 12:00am
Originally posted by: jane doe
TESTReply
Using Thumbnail Images in a List ControlPosted by Legacy on 05/09/2001 12:00am
Originally posted by: Bath
How to load tiff files insted of bmp???????Reply | http://www.codeguru.com/cpp/controls/listview/usingimages/article.php/c4159/Using-Thumbnail-Images-in-a-List-Control.htm | CC-MAIN-2014-41 | refinedweb | 482 | 60.85 |
Sent from my iPhone > On Aug 29, 2017, at 11:22 AM, Keith Miller <keith_mil...@apple.com> wrote: > > I doubt anyone is going to run such a script before they go to upload a > patch to bugzilla.
EWS was what I was hoping for; likely to be sufficient. But it could also be integrated into the development process as, say, check-webkit-style is. > So developers will still hit the name collision issue randomly throughout > development. Sure. But I don’t think that required extensive use of namespaces is the best way to greatly mitigate this. Mistakes will still happen. So I think we shouldn’t go too far in ruining readability of code for something that is not necessary to solve the problem. Recommending either namespaces or globally unique names and clarifying that file local scope doesn’t exist are both good. But again I think people already handle these problems fine in headers so we don’t need too tight a straitjacket, at least not out of the gate. — Darin _______________________________________________ webkit-dev mailing list webkit-dev@lists.webkit.org | https://www.mail-archive.com/webkit-dev@lists.webkit.org/msg27820.html | CC-MAIN-2022-40 | refinedweb | 182 | 64.41 |
This article explores a trick in C# for looking up values based on types, much like a
Dictionary<Type, T> only it's almost 10x faster! You probably don't need this trick and even if you need it, it will only work in a few very specific scenarios. But it's a neat trick that might be fun to read about. I don't know if this pattern has a name, and I'm not very good at naming things, so maybe I'll just refer to it as the private static generic inner class trick. If you know of a better name, please let me know.
It's a bit tricky to explain exactly how and when to use this trick, so I'll look at a specific use-case and work our way towards a specific solution. From there we can generalize it until we hit on the limitations of this pattern and find other specific use-cases for it within those limitations.
Let's imagine we are working on an ORM library, one that will be really good. It will work like many other ORMs, where a C# class maps to a table in our database. Let's ignore if this is a good or bad idea and focus on just a tiny part of the implementation, the way we map the class to the table. We can use the
[Table] attribute like so:
[Table("BlogPosts")] public class BlogPost { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public DateTime Published { get; set; } }
The class
BlogPost maps to the table
BlogPosts in the database through the attribute
[Table]. How can our code find out this? We need to use reflection.
public static class Reflections { public static string GetTableName<T>() => typeof(T) .CustomAttributes .OfType<TableAttribute>() .First() .Name; }
This looks up all the attributes applied to a type, finds the
Table attributes and takes the first one and gets the
Name property from it. If you have used reflection in C# then this will look familiar and straight forward. But you will then also know that it's not very efficient.
Reflection is slow. If we run this method every time we query the database then we are not being as efficient as we could be. The
Name property of the
Table attribute applied to a specific type will not change while the code is running, so we have a method that will slowly find the same answer every time we call it. We can speed it up by saving the result in a dictionary, so that we don't need to use reflection every time:
public static class Reflections { private static ConcurrentDictionary<Type, string> TableNames = new ConcurrentDictionary<Type, string>(); public static string GetTableName<T>() => TableNames.GetOrAdd(typeof(T), type => type .GetCustomAttributes(typeof(TableAttribute), true) .Cast<TableAttribute>() .FirstOrDefault() ?.Name); }
(I use
ConcurrentDictionary here only to get the very useful
GetOrAdd method, which doesn't exist on
IDictionary. In a real implementation of this I would probably use just a normal dictionary and a lot more error checking and fallback.)
This way we only use reflection for a type once, after that the result is stored in the dictionary
TableNames. Benchmarking, which is often wrong, will show that this is 100s or 1000s of times faster for repeated lookups! We have reduced the CPU time a lot by slightly increasing memory usage, a good tradeoff. But we have only reduced the CPU usage, we haven't removed it. That is, there are still further improvements, and this is where the finely named private static generic inner class trick can be used.
So let's do what the name implies and add a private static generic inner class:
public static class Reflections { public static string GetTableName<T>() => TableName<T>.Name; private static class TableName<T> { public static readonly string Name = typeof(T) .GetCustomAttributes(typeof(TableAttribute), true) .Cast<TableAttribute>() .FirstOrDefault() ?.Name; } }
Here finally we see the trick in action. The inner class
TableName<T> is generic, so the static field
Name will be created once per type
T. The way generics work in C# is that at runtime a class is created for each specific type of the generic class. The initializer of this field will only be called the first time, just like the way we set up our dictionary in the previous example.
Is this faster than the dictionary? Yes, from simple benchmarks it seems to be almost 10x faster! This is because we have replaced hashcode calculation and dictionary lookup with a single static field read from a class. It's unlikely that we can make this any faster.
Here is the full code sample for the benchmark, written in BenchmarkDotNet. This is very simple, probably not the best way to do it, but I think it gives a good indication of how this trick works:
[public class Program { [ ] public string Reflection() => GetFromReflection<BlogPost>(); [ ] public string Dictionary() => GetFromDictionary<BlogPost>(); [ ] public string Inner() => GetFromInner<BlogPost>(); public static void Main() => BenchmarkRunner.Run<Program>(); private static string GetFromReflection<T>() => typeof(T) .GetCustomAttributes(typeof(TableAttribute), true) .Cast<TableAttribute>() .FirstOrDefault() ?.Name; private static Dictionary<Type, string> _dictionary = new Dictionary<Type, string>(); private static string GetFromDictionary<T>() => _dictionary.TryGetValue(typeof(T), out var result) ? result : _dictionary[typeof(T)] = GetFromReflection<T>(); private static string GetFromInner<T>() => InnerClass<T>.Name; private static class InnerClass<T> { public static readonly string Name = GetFromReflection<T>(); } }] [ ]
This is the result I get on my machine:
BenchmarkDotNet=v0.11.5, OS=Windows 10.0.18362 Intel Core i7-3517U CPU 1.90GHz (Ivy Bridge), 1 CPU, 4 logical and 2 physical cores .NET Core SDK=2.2.300 [Host] : .NET Core 2.2.5 (CoreCLR 4.6.27617.05, CoreFX 4.6.27618.01), 64bit RyuJIT Core : .NET Core 2.2.5 (CoreCLR 4.6.27617.05, CoreFX 4.6.27618.01), 64bit RyuJIT Job=Core Runtime=Core | Method | Mean | Error | StdDev | Rank | |----------- |-------------:|------------:|------------:|-----:| | Reflection | 5,426.419 ns | 120.0703 ns | 328.6905 ns | 3 | | Dictionary | 32.038 ns | 0.1739 ns | 0.1627 ns | 2 | | Inner | 3.844 ns | 0.0532 ns | 0.0471 ns | 1 |
While the Dictionary code takes about 32ns to complete the Inner class version runs in 3.8ns, or more than 8x as fast! It varies a bit, and this is a very simple scenario where the dictionary contains only a single item, so I suspect the Inner method will be even more performant, compared to the Dictionary method, in the real world.
I found this trick first used in the Array.Empty
Empty class in our extension methods nuget package at work.
I haven't seen it used any other place, probably because of its many limitations.
I've called this article the type-dictionary trick and compared it against the performance of a dictionary, but the code above doesn't much behave like a dictionary. In particular:
Typeas its key
The result is that you probably only want to use this trick to store some values that don't change and are fixed at compile time, like the value of the attribute in the example above. Reflection caching seems to be a good scenario for this trick, since it works on types and we often use reflection on types, and the result won't change at runtime.
A place where reflection is often used is for dependency injection, like the
IServiceProvider in .NET core. We can use the trick to make a super fast service lookup, like this:
public class FastServiceProvider { public void AddService<TService>(Func<TService> factory) => Inner<TService>.ServiceFactory = factory; public TService GetService<TService>() => Inner<TService>.ServiceFactory(); private static class Inner<TService> { public static Func<TService> ServiceFactory; } }
This is a very limited example that only lets you register a factory function and look up a service using the generic
GetService<TService>() function. But it has a bigger problem, namely that you can't have multiple instances of
FastServiceProvider with different services, since it all relies on the static inner class. How can we work around this problem? First, we need some way to differentiate different instances of
FastServiceProvider, and we can do that by making it too generic. The inner class is now unique per two generic type parameters, so as long as we create a
new FastServiceProvider<TypeA> and a
FastServiceProvider<TypeB> then they will have different inner classes and different "dictionaries" of services.
public class FastServiceProvider<T> { public void AddService<TService>(Func<TService> factory) => Inner<TService>.ServiceFactory = factory; public TService GetService<TService>() => Inner<TService>.ServiceFactory(); private static class Inner<TService> { public static Func<TService> ServiceFactory; } }
But, we have to make sure to always use a new type every time we create a new instance of
FastServiceProvider<T>, or else two instances will share services! We need some way to create the generic
FastServiceProvider<T> with a different type
T each time. We can do that by dynamically creating types, at runtime, when we need one. The code for doing just that look something like this:
public static class MyTypeBuilder { private static int Counter { get; set; } = 0; private static AssemblyName MyAssemblyName { get; } = new AssemblyName("MyAssembly"); private static AssemblyBuilder MyAssembly { get; } = AssemblyBuilder.DefineDynamicAssembly(MyAssemblyName, AssemblyBuilderAccess.Run); private static ModuleBuilder MainModule { get; } = MyAssembly.DefineDynamicModule("MainModule"); public static Type CreateType() => GetTypeBuilder($"MyType{Counter++}") .CreateType(); private static TypeBuilder GetTypeBuilder(string name) => MainModule.DefineType(name, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, null); }
Don't worry too much about this code, it is mostly copied from a Stack Overflow answer. It creates a new Type in an assembly created at runtime. The type we create here is empty, since we don't need it for anything apart from being unique. The
Counter that increments ensures that the name is unique.
Now that we have a way to create new unique types whenever we need them we just have to combine it with the generic
FastServiceProvider<T> somehow. We've used inner classes to solve all kinds of problems so far, so why stop now? We can take the generic class we have and put it inside a new class, one that is static and only has a single public method,
Create(). This creates a new instance using a new type. The way it does it is through reflection and to make it all easy to use I've created an interface that we can rely on.
public interface IFastServiceProvider { void AddService<TService>(Func<TService> factory); TService GetService<TService>(); } public static class FastServiceProvider { public static IFastServiceProvider Create() => (IFastServiceProvider) typeof(FastServiceProvider) .GetMethod("CreateInner", BindingFlags.NonPublic | BindingFlags.Static) .MakeGenericMethod(MyTypeBuilder.CreateType()) .Invoke(null, null); private static InnerFast<T> CreateInner<T>() => new InnerFast<T>(); private class GenericServiceProvider<T> { public void AddService<TService>(Func<TService> factory) => Inner<TService>.ServiceFactory = factory; public TService GetService<TService>() => Inner<TService>.ServiceFactory(); private static class Inner<TService> { public static Func<TService> ServiceFactory; } } }
Ok, that's quite a bit of convoluted code. I don't know if this is at all useful or just too complicated for any practical use. Since this uses reflection in the
Create method it is not very fast to create new instances, but once the instances have been made they are lightning fast!
We can work around some of the other limitations in similar convoluted ways, but this is already getting a bit out of hand, so I'll leave that as an excercise for the reader.
I've shown here how to use a generic inner class to store data per type in a program. I think this is a neat way to get high performance code, and I've seen it used in the wild, but only a few places. I don't know if this trick has a name, or if it is used other places, but if you do, please let me know. Oh, and if you find mistakes or spelling errors, let me know as well by creating an issue or pull-request here. | https://mariusgundersen.com/type-dictionary-trick/ | CC-MAIN-2021-31 | refinedweb | 1,989 | 55.24 |
a dataset from an HDF5 file created from a CSV file, using PyTorch's data loading utilities. For a more in-depth discussion, please see the official
An Hierarchical Data Format (HDF) is a convenient way that allows quick access to data instances during minibatch learning if a dataset is too large to fit into memory. The approach outlined in this notebook uses uses the common HDF5 format and should be accessible to any programming language or tool with an HDF5 API.
In this example, we are going to use the Iris dataset for illustrative purposes. Let's pretend it's our large training dataset that doesn't fit into memory.
import pandas as pd import numpy as np import h5py import torch from torch.utils.data import Dataset from torch.utils.data import DataLoader
In this first step, we are going to process a CSV file (here, Iris) into an HDF5 database:
# suppose this is a large CSV that does not # fit into memory: csv_path = '' # Get number of lines in the CSV file if it's on your hard drive: #num_lines = subprocess.check_output(['wc', '-l', in_csv]) #num_lines = int(nlines.split()[0]) num_lines = 150 num_features = 4 class_dict = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} # use 10,000 or 100,000 or so for large files chunksize = 10 # this is your HDF5 database: with h5py.File('iris.h5', 'w') as h5f: # use num_features-1 if the csv file has a column header dset1 = h5f.create_dataset('features', shape=(num_lines, num_features), compression=None, dtype='float32') dset2 = h5f.create_dataset('labels', shape=(num_lines,), compression=None, dtype='int32') # change range argument from 0 -> 1 if your csv file contains a column header for i in range(0, num_lines, chunksize): df = pd.read_csv(csv_path, header=None, # no header, define column header manually later nrows=chunksize, # number of rows to read at each iteration skiprows=i) # skip rows that were already read df[4] = df[4].map(class_dict) features = df.values[:, :4] labels = df.values[:, -1] # use i-1 and i-1+10 if csv file has a column header dset1[i:i+10, :] = features dset2[i:i+10] = labels[0]
After creating the database, let's double-check that everything works correctly:
with h5py.File('iris.h5', 'r') as h5f: print(h5f['features'].shape) print(h5f['labels'].shape)
(150, 4) (150,)
with h5py.File('iris.h5', 'r') as h5f: print('Features of entry no. 99:', h5f['features'][99]) print('Class label of entry no. 99:', h5f['labels'][99])
Features of entry no. 99: [5.7 2.8 4.1 1.3] Class label of entry no. 99: 1
Now, we implement a custom
Dataset for reading the training examples. The
__getitem__ method will
index(more on batching later)
Note that we will keep an open connection to the database for efficiency via
self.h5f = h5py.File(h5_path, 'r') -- you may want to close it when you are done (more on this later).
class Hdf5Dataset(Dataset): """Custom Dataset for loading entries from HDF5 databases""" def __init__(self, h5_path, transform=None): self.h5f = h5py.File(h5_path, 'r') self.num_entries = self.h5f['labels'].shape[0] self.transform = transform def __getitem__(self, index): features = self.h5f['features'][index] label = self.h5f['labels'][index] if self.transform is not None: features = self.transform(features) return features, label def __len__(self): return self.num_entries
Now that we have created our custom Dataset class, we can initialize a Dataset instance for the training examples using the 'iris.h5' database file. Then, we initialize a
DataLoader that allows us to read from the dataset.
train_dataset = Hdf5Dataset(h5_path='iris.h5', transform=None) train_loader = DataLoader(dataset=train_dataset, batch_size=50, shuffle=True, num_workers=4)
That's it! Now we can iterate over an epoch using the train_loader as an iterator and use the features and labels from the training dataset for model training as shown in the next section
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") torch.manual_seed(0) num_epochs = 5 for epoch in range(num_epochs): for batch_idx, (x, y) in enumerate(train_loader): print('Epoch:', epoch+1, end='') print(' | Batch index:', batch_idx, end='') print(' | Batch size:', y.size()[0]) x = x.to(device) y = y.to(device) # do model training on x and y here
Epoch: 1 | Batch index: 0 | Batch size: 50 Epoch: 1 | Batch index: 1 | Batch size: 50 Epoch: 1 | Batch index: 2 | Batch size: 50 Epoch: 2 | Batch index: 0 | Batch size: 50 Epoch: 2 | Batch index: 1 | Batch size: 50 Epoch: 2 | Batch index: 2 | Batch size: 50 Epoch: 3 | Batch index: 0 | Batch size: 50 Epoch: 3 | Batch index: 1 | Batch size: 50 Epoch: 3 | Batch index: 2 | Batch size: 50 Epoch: 4 | Batch index: 0 | Batch size: 50 Epoch: 4 | Batch index: 1 | Batch size: 50 Epoch: 4 | Batch index: 2 | Batch size: 50 Epoch: 5 | Batch index: 0 | Batch size: 50 Epoch: 5 | Batch index: 1 | Batch size: 50 Epoch: 5 | Batch index: 2 | Batch size: 50
Remember that we kept an open connection to the HDF5 database in the
Hdf5Dataset (via
self.h5f = h5py.File(h5_path, 'r')). Once we are done, we may want to close this connection:
train_dataset.h5f.close()
%watermark -iv
torch 1.0.0 pandas 0.23.4 numpy 1.15.4 h5py 2.8.0 | https://nbviewer.jupyter.org/github/rasbt/deeplearning-models/blob/master/pytorch_ipynb/mechanics/custom-data-loader-csv.ipynb | CC-MAIN-2020-40 | refinedweb | 876 | 64.91 |
Debugger?
Question: Does Pythonista include a debugger? If so, I haven't managed to locate it yet, but then again, I'm pretty new to Python in general, and to Pythonista in particular.
In particular, ways of setting breakpoints, seeing where in the code it's executing, single-stepping into vs. over method calls, viewing expressions, watchpoints on data change, and so forth?
import pdb ; print(dir(pdb))
Ah, OK, good deal, thanks!
Also, just for the record:
nice, I wasn't aware of the pdb module!
nice, I wasn't aware of the pdb module!
I suspect I'll be needing it. Never buy a pencil without an eraser!
import pdb; pdb.pm()i have it on speed dial! | https://forum.omz-software.com/topic/2162/debugger | CC-MAIN-2017-47 | refinedweb | 120 | 78.35 |
Description
AnyAPI is a library that helps you to write any API wrappers with ease and in pythonic way.
AnyAPI alternatives and similar packages
Based on the "HTTP" category.
Alternatively, view AnyAPI alternatives based on common mentions on social networks and blogs.
requests9.9 6.4 L3 AnyAPI VS requestsA simple, yet elegant HTTP library.
urllib37.7 9.0 L4 AnyAPI VS urllib3Python HTTP library with thread-safe connection pooling, file post support, user friendly, and more.
grequests7.7 0.0 L5 AnyAPI VS grequestsRequests + Gevent = <3
requests-futures6.0 1.7 AnyAPI VS requests-futuresAsynchronous Python HTTP Requests for Humans using Futures
jasmin5.3 6.9 AnyAPI VS jasminJasmin - Open source SMS gateway
Uplink4.2 4.2 AnyAPI VS UplinkA Declarative HTTP Client for Python
treq4.1 8.4 L4 AnyAPI VS treqPython requests like API built on top of Twisted's HTTP client.
httplib23.8 4.6 AnyAPI VS httplib2Small, fast HTTP client library for Python. Features persistent connections, cache, and Google App Engine support. Originally written by Joe Gregorio, now supported by community.
Tapioca-Wrapper3.2 3.7 L5 AnyAPI VS Tapioca-WrapperPython API client generator
kiss-headers1.5 5.8 AnyAPI VS kiss-headers💡Python package for HTTP/1.1 style headers. Parse headers to objects. Most advanced available structure for http headers.
txrequests1.1 0.0 AnyAPI VS txrequestsAsynchronous Python HTTP Requests for Humans using twisted
Bearer Python0.9 0.4 AnyAPI VS Bearer PythonBearer API client for Python
FGrequests0.5 1.8 AnyAPI VS FGrequestsFastest python library for making asynchronous group requests.
Doublify API Toolkit0.5 0.0 AnyAPI VS Doublify API ToolkitDoublify API toolkit for Python AnyAPI or a related project?
README
AnyAPI
AnyAPI is a library that helps you to write any API wrappers with ease and in pythonic way.
Features
- Have better looking code using dynamic method calls.
- Filters to help you to modify request, raise errors or log requests instead of writing functions everywhere.
- Scoped calls to raise errors and take action if necessary.
- Automatic retrying if the condition met with what you passed.
- Built-in rate limit proxy changer. (you can write your own proxy handler)
- Since it is built on top of requests anything compatible with it is compatible with AnyAPI.
But most importantly in AnyAPI almost everything is modular!
Examples
Making GET request to
from anyapi import AnyAPI base_url = '' api = AnyAPI(base_url) api.anything.endpoint.GET()
As you can see dots are pretended as slash and at the end you should put dot and HTTP method you want to use in capital letters.
Setting header before every request
import datetime from anyapi import AnyAPI def set_date_as_header(kwargs): now = datetime.datetime.now() kwargs['headers'].update({'date': now.strftime('%B %d %Y')}) return kwargs api = AnyAPI('') api._filter_request.append(set_date_as_header) print(api.anything.endpoint.GET().json()) # output { 'args': {}, 'data': '', 'files': {}, 'form': {}, 'headers': { 'Accept-Encoding': 'identity', 'Connection': 'close', 'Date': 'January 16 2019', 'Host': 'httpbin.org' }, 'json': None, 'method': 'GET', 'origin': 'XX.XX.XX.XX', 'url': '' }
As you can see filter worked as expected and set
Date header.
Changing proxy automatically after they reach their rate limit
from anyapi import AnyAPI from anyapi.proxy_handlers import RateLimitProxy proxy_configuration = { 'default': proxy0, 'proxies': [proxy0, proxy1, proxy2,....], # don't forget to add default proxy! 'paths': { '/anything': rate_limit0, '/anything/endpoint': rate_limit1 } } api = AnyAPI('', proxy_configuration=proxy_configuration, proxy_handler=RateLimitProxy) for i in range(10): print(api.anything.endpoint.GET().json())
If you check output of the all them you can see proxy changes when it reaches limit.
This library is not a new thing
There is a lot of libraries you can find out there for example Uplink, Hammock and many more...
Installation
Library on PyPI so just run
pip install anyapi | https://python.libhunt.com/anyapi-alternatives | CC-MAIN-2021-31 | refinedweb | 614 | 59.3 |
1Contents
1 Origins of NumPy 13
2 Object Essentials 18 2.1 Data-Type Descriptors . . . . . . . . . . . . . . . . . . . . . . . . . . 20 2.2 Basic indexing (slicing) . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.3 Memory Layout of ndarray . . . . . . . . . . . . . . . . . . . . . . 26 2.3.1 Contiguous Memory Layout . . . . . . . . . . . . . . . . . . . 26 2.3.2 Non-contiguous memory layout . . . . . . . . . . . . . . . . . 28 2.4 Universal Functions for arrays . . . . . . . . . . . . . . . . . . . . . . 30 2.5 Summary of new features . . . . . . . . . . . . . . . . . . . . . . . . 32 2.6 Summary of differences with Numeric . . . . . . . . . . . . . . . . . 34 2.6.1 First-step changes . . . . . . . . . . . . . . . . . . . . . . . . 34 2.6.2 Second-step changes . . . . . . . . . . . . . . . . . . . . . . . 37 2.6.3 Updating code that uses Numeric using alter codeN . . . . . 38 2.6.4 Changes to think about . . . . . . . . . . . . . . . . . . . . . 39 2.7 Summary of differences with Numarray . . . . . . . . . . . . . . . . 40 2.7.1 First-step changes . . . . . . . . . . . . . . . . . . . . . . . . 41 2.7.1.1 Import changes . . . . . . . . . . . . . . . . . . . . . 41 2.7.1.2 Attribute and method changes . . . . . . . . . . . . 42 2.7.2 Second-step changes . . . . . . . . . . . . . . . . . . . . . . . 43 2.7.3 Additional Extension modules . . . . . . . . . . . . . . . . . . 43
2 3.1.3 Other attributes . . . . . . . . . . . . . . . . . . . . . . . . . 51 3.1.4 Array Interface attributes . . . . . . . . . . . . . . . . . . . . 52 3.2 ndarray Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 3.2.1 Array conversion . . . . . . . . . . . . . . . . . . . . . . . . . 55 3.2.2 Array shape manipulation . . . . . . . . . . . . . . . . . . . . 60 3.2.3 Array item selection and manipulation . . . . . . . . . . . . . 62 3.2.4 Array calculation . . . . . . . . . . . . . . . . . . . . . . . . . 66 3.3 Array Special Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 72 3.3.1 Methods for standard library functions . . . . . . . . . . . . . 72 3.3.2 Basic customization . . . . . . . . . . . . . . . . . . . . . . . 73 3.3.3 Container customization . . . . . . . . . . . . . . . . . . . . . 75 3.3.4 Arithmetic customization . . . . . . . . . . . . . . . . . . . . 76 3.3.4.1 Binary . . . . . . . . . . . . . . . . . . . . . . . . . 76 3.3.4.2 In-place . . . . . . . . . . . . . . . . . . . . . . . . . 78 3.3.4.3 Unary operations . . . . . . . . . . . . . . . . . . . 79 3.4 Array indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 3.4.1 Basic Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 3.4.2 Advanced selection . . . . . . . . . . . . . . . . . . . . . . . . 82 3.4.2.1 Integer . . . . . . . . . . . . . . . . . . . . . . . . . 82 3.4.2.2 Boolean . . . . . . . . . . . . . . . . . . . . . . . . . 84 3.4.3 Flat Iterator indexing . . . . . . . . . . . . . . . . . . . . . . 85
4 Basic Routines 86 4.1 Creating arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 4.2 Operations on two or more arrays . . . . . . . . . . . . . . . . . . . . 91 4.3 Printing arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 4.4 Functions redundant with methods . . . . . . . . . . . . . . . . . . 95 4.5 Dealing with data types . . . . . . . . . . . . . . . . . . . . . . . . . 96
3 5.8 More data type functions . . . . . . . . . . . . . . . . . . . . . . . . 120 5.9 Functions that behave like ufuncs . . . . . . . . . . . . . . . . . . . . 123 5.10 Miscellaneous Functions . . . . . . . . . . . . . . . . . . . . . . . . . 123 5.11 Utility functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
4 9.4 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 9.4.1 Reduce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 9.4.2 Accumulate . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 9.4.3 Reduceat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 9.4.4 Outer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 9.5 Available ufuncs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 9.5.1 Math operations . . . . . . . . . . . . . . . . . . . . . . . . . 167 9.5.2 Trigonometric functions . . . . . . . . . . . . . . . . . . . . . 170 9.5.3 Bit-twiddling functions . . . . . . . . . . . . . . . . . . . . . . 171 9.5.4 Comparison functions . . . . . . . . . . . . . . . . . . . . . . 172 9.5.5 Floating functions . . . . . . . . . . . . . . . . . . . . . . . . 174
II C-API 211
5 12.1 New Python Types Defined . . . . . . . . . . . . . . . . . . . . . . . 213 12.1.1 PyArray Type . . . . . . . . . . . . . . . . . . . . . . . . . . 214 12.1.2 PyArrayDescr Type . . . . . . . . . . . . . . . . . . . . . . . 215 12.1.3 PyUFunc Type . . . . . . . . . . . . . . . . . . . . . . . . . . 223 12.1.4 PyArrayIter Type . . . . . . . . . . . . . . . . . . . . . . . . 226 12.1.5 PyArrayMultiIter Type . . . . . . . . . . . . . . . . . . . . . 227 12.1.6 PyArrayFlags Type . . . . . . . . . . . . . . . . . . . . . . . 228 12.1.7 ScalarArrayTypes . . . . . . . . . . . . . . . . . . . . . . . . 228 12.2 Other C-Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 12.2.1 PyArray Dims . . . . . . . . . . . . . . . . . . . . . . . . . . 229 12.2.2 PyArray Chunk . . . . . . . . . . . . . . . . . . . . . . . . . . 230 12.2.3 PyArrayInterface . . . . . . . . . . . . . . . . . . . . . . . . . 230 12.2.4 Internally used structures . . . . . . . . . . . . . . . . . . . . 232 12.2.4.1 PyUFuncLoopObject . . . . . . . . . . . . . . . . . 232 12.2.4.2 PyUFuncReduceObject . . . . . . . . . . . . . . . . 232 12.2.4.3 PyUFunc Loop1d . . . . . . . . . . . . . . . . . . . 232 12.2.4.4 PyArrayMapIter Type . . . . . . . . . . . . . . . . 232
6 13.3.1.1 Data access . . . . . . . . . . . . . . . . . . . . . . . 24013.3.2 Creating arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 241 13.3.2.1 From scratch . . . . . . . . . . . . . . . . . . . . . . 241 13.3.2.2 From other objects . . . . . . . . . . . . . . . . . . . 24413.3.3 Dealing with types . . . . . . . . . . . . . . . . . . . . . . . . 249 13.3.3.1 General check of Python Type . . . . . . . . . . . . 249 13.3.3.2 Data-type checking . . . . . . . . . . . . . . . . . . 251 13.3.3.3 Converting data types . . . . . . . . . . . . . . . . . 254 13.3.3.4 New data types . . . . . . . . . . . . . . . . . . . . 256 13.3.3.5 Special functions for PyArray OBJECT . . . . . . . 25713.3.4 Array flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 13.3.4.1 Basic Array Flags . . . . . . . . . . . . . . . . . . . 258 13.3.4.2 Combinations of array flags . . . . . . . . . . . . . . 259 13.3.4.3 Flag-like constants . . . . . . . . . . . . . . . . . . 259 13.3.4.4 Flag checking . . . . . . . . . . . . . . . . . . . . . . 26013.3.5 Array method alternative API . . . . . . . . . . . . . . . . . 261 13.3.5.1 Conversion . . . . . . . . . . . . . . . . . . . . . . . 261 13.3.5.2 Shape Manipulation . . . . . . . . . . . . . . . . . . 263 13.3.5.3 Item selection and manipulation . . . . . . . . . . . 265 13.3.5.4 Calculation . . . . . . . . . . . . . . . . . . . . . . . 26813.3.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 13.3.6.1 Array Functions . . . . . . . . . . . . . . . . . . . . 270 13.3.6.2 Other functions . . . . . . . . . . . . . . . . . . . . 27213.3.7 Array Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . 27313.3.8 Broadcasting (multi-iterators) . . . . . . . . . . . . . . . . . . 27413.3.9 Array Scalars . . . . . . . . . . . . . . . . . . . . . . . . . . . 27613.3.10 Data-type descriptors . . . . . . . . . . . . . . . . . . . . . . 27813.3.11 Conversion Utilities . . . . . . . . . . . . . . . . . . . . . . . 280 13.3.11.1 For use with PyArg ParseTuple . . . . . . . . . . 280 13.3.11.2 Other conversions . . . . . . . . . . . . . . . . . . . 28213.3.12 Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 13.3.12.1 Importing the API . . . . . . . . . . . . . . . . . . . 283 13.3.12.2 Internal Flexibility . . . . . . . . . . . . . . . . . . . 284 13.3.12.3 Memory management . . . . . . . . . . . . . . . . . 285 13.3.12.4 Threading support . . . . . . . . . . . . . . . . . . . 285 13.3.12.5 Priority . . . . . . . . . . . . . . . . . . . . . . . . . 287 13.3.12.6 Default buffers . . . . . . . . . . . . . . . . . . . . . 287
7 13.3.12.7 Other constants . . . . . . . . . . . . . . . . . . . . 287 13.3.12.8 Miscellaneous Macros . . . . . . . . . . . . . . . . . 288 13.3.12.9 Enumerated Types . . . . . . . . . . . . . . . . . . . 289 13.4 UFunc API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 13.4.1 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 13.4.2 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 13.4.3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 13.4.4 Generic functions . . . . . . . . . . . . . . . . . . . . . . . . . 293 13.5 Importing the API . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
8 15.4.1 Creating sub-types . . . . . . . . . . . . . . . . . . . . . . . . 322 15.4.2 Specific features of ndarray sub-typing . . . . . . . . . . . . . 323 15.4.2.1 The array finalize method . . . . . . . . . . . . . 323 15.4.2.2 The array priority attribute . . . . . . . . . . . . 324 15.4.2.3 The array wrap method . . . . . . . . . . . . . . 324
9 16.7.3 Boost Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 16.7.4 Instant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 16.7.5 PyInline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 16.7.6 PyFort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
10List of Tables
6.1 Array scalar types that inherit from basic Python types. The intc array data type might also inherit from the IntType if it has the same number of bits as the int array data type on your platform. . . . . . 129
11 Part I
12Chapter 1
Origins of NumPy
—John Gall
Copy from one, it’s plagiarism; copy from two, it’s research.
—Wilson Mizner
NumPy builds on (and is a successor to) the successful Numeric array object.Its goal is to create the corner-stone for a useful environment for scientific com-puting. In order to better understand the people surrounding NumPy and (itslibrary-package) SciPy, I will explain a little about how SciPy and (current) NumPyoriginated. In 1998, as a graduate student studying biomedical imaging at theMayo Clinic in Rochester, MN, I came across Python and its numerical extension(Numeric) while I was looking for ways to analyze large data sets for MagneticResonance Imaging and Ultrasound using a high-level language. I quickly fell inlove with Python programming which is a remarkable statement to make about aprogramming language. If I had not seen others with the same view, I might haveseriously doubted my sanity. I became rather involved in the Numeric Python com-munity, adding the C-API chapter to the Numeric documentation (for which PaulDubois graciously made me a co-author). As I progressed with my thesis work, programming in Python was so enjoyablethat I felt inhibited when I worked with other programming frameworks. As a result,
13when a task I needed to perform was not available in the core language, or in theNumeric extension, I looked around and found C or Fortran code that performedthe needed task, wrapped it into Python (either by hand or using SWIG), and usedthe new functionality in my programs. Along the way, I learned a great deal about the underlying structure of Numericand grew to admire it’s simple but elegant structures that grew out of the mechanismby which Python allows itself to be extended.
NOTE Numeric was originally written in 1995 largely by Jim Hugunin while he was a graduate student at MIT. He received help from many people including Jim Fulton, David Ascher, Paul Dubois, and Konrad Hinsen. These individuals and many others added comments, criticisms, and code which helped the Numeric exten- sion reach stability. Jim Hugunin did not stay long as an active member of the community — moving on to write Jython and, later, Iron Python.
14code to SciPy including Ed Schofield, Robert Cimrman, David M. Cooke, Charles(Chuck) Harris, Prabhu Ramachandran, Gary Strangman, Jean-Sebastien Roy, andFernando Perez. Others such as Travis Vaught, David Morrill, Jeff Whitaker, andLouis Luangkesorn have contributed testing and build support. At the start of 2005, SciPy was at release 0.3 and relatively stable for an earlyversion number. Part of the reason it was difficult to stabilize SciPy was that thearray object upon which SciPy builds was undergoing a bit of an upheaval. At aboutthe same time as SciPy was being built, some Numeric users were hitting up againstthe limited capabilities of Numeric. In particular, the ability to deal with memorymapped files (and associated alignment and swapping issues), record arrays, andaltered error checking modes were important but limited or non-existent in Numeric.As a result, numarray was created by Perry Greenfield, Todd Miller, and Rick Whiteat the Space Science Telescope Institute as a replacement for Numeric. Numarrayused a very different implementation scheme as a mix of Python classes and Ccode (which led to slow downs in certain common uses). While improving somecapabilities, it was slow to pick up on the more advanced features of Numeric’suniversal functions (ufuncs) — never re-creating the C-API that SciPy dependedon. This made it difficult for SciPy to “convert” to numarray. Many newcomers to scientific computing with Python were told that numarraywas the future and started developing for it. Very useful tools were developedthat could not be used with Numeric (because of numarray’s change in C-API),and therefore could not be used easily in SciPy. This state of affairs was verydiscouraging for me personally as it left the community fragmented. Some developedfor numarray, others developed as part of SciPy. A few people even rejected adoptingPython for scientific computing entirely because of the split. In addition, I estimatethat quite a few Python users simply stayed away from both SciPy and numarray,leaving the community smaller than it could have been given the number of peoplethat use Python for science and engineering purposes. It should be recognized that the split was not intentional, but simply an out-growth of the different and exacting demands of scientific computing users. Mydescribing these events should not be construed as assigning blame to anyone. Ivery much admire and appreciate everyone I’ve met who is involved with scientificcomputing and Python. Using a stretched biological metaphor, it is only throughthe process of dividing and merging that better results are born. I think this conceptapplies to NumPy. In early 2005, I decided to begin an effort to help bring the diverging communitytogether under a common framework if it were possible. I first looked at numarray
15to see what could be done to add the missing features to make SciPy work withit as a core array object. After a couple of days of studying numarray, I was notenthusiastic about this approach. My familiarity with the Numeric code base nodoubt biased my opinion, but it seemed to me that the features of Numarray couldbe added back to Numeric with a few fundamental changes to the core object. Thiswould make the transition of SciPy to a more enhanced array object much easierin my mind. Therefore, I began to construct this hybrid array object complete with an en-hanced set of universal (broadcasting) functions that could deal with it. Along theway, quite a few new features and significant enhancements were added to the arrayobject and its surrounding infrastructure. This book describes the result of thatyear-and-a-half-long effort which culminated with the release of NumPy 0.9.2 inearly 2006 and NumPy 1.0 in late 2006. I first named the new package, SciPy Core,and used the scipy namespace. However, after a few months of testing under thatname, it became clear that a separate namespace was needed for the new package.As a result, a rapid search for a new name resulted in actually coming back to theNumPy name which was the unofficial name of Numerical Python but never theactual namespace. Because the new package builds on the code-base of and is asuccessor to Numeric, I think the NumPy name is fitting and hopefully not tooconfusing to new users. This book only briefly outlines some of the infrastructure that surrounds thebasic objects in NumPy to provide the additional functionality contained in the olderNumeric package (i.e. LinearAlgebra, RandomArray, FFT). This infrastructure inNumPy includes basic linear algebra routines, Fourier transform capabilities, andrandom number generators. In addition, the f2py module is described in its owndocumentation, and so is only briefly mentioned in the second part of the book.There are also extensions to the standard Python distutils and testing frameworksincluded with NumPy that are useful in constructing your own packages built on topof NumPy. The central purpose of this book, however, is to describe and documentthe basic NumPy system that is available under the numpy namespace.
NOTE The numpy namespace includes all names under the numpy.core and numpy.lib namespaces as well. Thus, import numpy will also import the names from numpy.core and numpy.lib. This is the recommended way to use numpy.
16 The following table gives a brief outline of the sub-packages contained in numpypackage.
17Chapter 2
Object Essentials
—Ron Jeffries
—Wayne Birmingham
18of memory in the array is interpreted in exactly the same way1 .
i TIP All arrays in NumPy are indexed starting at 0 and ending at M-1 following the Python convention.
>>> a = array([[1,2,3],[4,5,6]]) >>> a.shape (2, 3) >>> a.dtype dtype(’int32’)
NOTE for all code in this book it is assumed that you have first entered from numpy import *. In addition, any previously defined ar- rays are still defined for subsequent examples.
>>> a[1,1] 5
All code shown in the shaded-boxes in this book has been (automatically) exe-cuted on a particular version of NumPy. The output of the code shown below showswhich version of NumPy was used to create all of the output in your copy of thisbook.
1 By using OBJECT arrays, one can effectively have heterogeneous arrays, but the system still
sees each element of the array as exactly the same thing (a reference to a Python object).
19 head
data−type array scalar
header ... ndarray
Figure 2.1: Conceptual diagram showing the relationship between the three fun-damental objects used to describe the data in an array: 1) the ndarray itself, 2)the data-type object that describes the layout of a single fixed-size element of thearray, 3) the array-scalar Python object that is returned when a single element ofthe array is accessed.
20and complex data types. Associated with each data-type is a Python type objectwhose instances are array scalars. This type-object can be obtained using the typeattribute of the dtype object. Python typically defines only one data-type of aparticular data class (one integer type, one floating-point type, etc.). This can beconvenient for some applications that don’t need to be concerned with all the waysdata can be represented in a computer. For scientific applications, however, this isnot always true. As a result, in NumPy, their are 21 different fundamental Pythondata-type-descriptor objects built-in. These descriptors are mostly based on thetypes available in the C language that CPython is written in. However, there are afew types that are extremely flexible, such as str , unicode , and void. The fundamental data-types are shown in Table 2.1. Along with their (mostly)C-derived names, the integer, float, and complex data-types are also available usinga bit-width convention so that an array of the right size can always be ensured(e.g. int8, float64, complex128). The C-like names are also accessible using acharacter code which is also shown in the table (use of the character codes, however,is discouraged). Names for the data types that would clash with standard Pythonobject names are followed by a trailing underscore, ’ ’. These data types are sonamed because they use the same underlying precision as the corresponding Pythondata types. Most scientific users should be able to use the array-enhanced scalarobjects in place of the Python objects. The array-enhanced scalars inherit from thePython objects they can replace and should act like them under all circumstances(except for how errors are handled in math computations).
i TIP The array types bool , int , complex , float , object , uni- code , and str are enhanced-scalars. They are very similar to the standard Python types (without the trailing underscore) and inherit from them (except for bool and object ). They can be used in place of the standard Python types whenever desired. Whenever a data type is required, as an argument, the standard Python types are recognized as well.
Three of the data types are flexible in that they can have items that are of anarbitrary size: the str type, the unicode type, and the void type. While, youcan specify an arbitrary size for these types, every item in an array is still of thatspecified size. The void type, for example, allows for arbitrary records to be definedas elements of the array, and can be used to define exotic types built on top of the
21Table 2.1: Built-in array-scalar types corresponding to data-types for an ndarray.The bold-face types correspond to standard Python types. The object type isspecial because arrays with dtype=’O’ do not return an array scalar on item accessbut instead return the actual object referenced in the array.
basic ndarray.
NOTE The two types intp and uintp are not separate types. They are names bound to a specific integer type just large enough to hold a memory address (a pointer) on the platform.
22character conven- tion more consistent with other Python modules such as the struct module.
to indexing with a tuple is a feature added to Python at the request of the NumPy community.The Ellipsis object was also added to Python explicitly for the NumPy community. Extendedslicing (wherein a step can be provided) was also a feature added to Python because of Numeric.
23Figure 2.2: Hierarchy of type objects representing the array data types. Not shownare the two integer types intp and uintp which just point to the integer typethat holds a pointer for the platform. All the number types can be obtained usingbit-width names as well.
24third element of the 4th column can be selected as A[:: 3, 3]. Ellipses can be used toreplace zero or more “:” terms. In other words, an Ellipsis object expands to zeroor more full slice objects (“:”) so that the total number of dimensions in the slicingtuple matches the number of dimensions in the array. Thus, if A is 10 × 20 × 30 × 40,then A[3 :, ..., 4] is equivalent to A[3 :, :, :, 4] while A[..., 3] is equivalent to A[:, :, :, 3]. The following code illustrates some of these concepts:
[[20 21 22 23 24] [25 26 27 28 29] [30 31 32 33 34] [35 36 37 38 39]]
[[40 41 42 43 44] [45 46 47 48 49] [50 51 52 53 54] [55 56 57 58 59]]]
252.3 Memory Layout of ndarrayOn a fundamental level, an N -dimensional array object is just a one-dimensional se-quence of memory with fancy indexing code that maps an N -dimensional index intoa one-dimensional index. The one-dimensional index is necessary on some level be-cause that is how memory is addressed in a computer. The fancy indexing, however,can be very helpful for translating our ideas into computer code. This is becausemany concepts we wish to model on a computer have a natural representation asan N -dimensional array. While this is especially true in science and engineering,it is also applicable to many other arenas which can be appreciated by consideringthe popularity of the spreadsheet as well as “image processing” applications.
WARNING Some high-level languages give pre-eminence to a particular use of 2-dimensional arrays as Matrices. In NumPy, however, the core object is the more general N -dimensional array. NumPy defines a matrix object as a sub-class of the N-dimensional array.
In order to more fully understand the array object along with its attributesand methods it is important to learn more about how an N -dimensional array isrepresented in the computer’s memory. A complete understanding of this layout isonly essential for optimizing algorithms operating on general purpose arrays. But,even for the casual user, a general understanding of memory layout will help toexplain the use of certain array attributes that may otherwise be mysterious.
26 0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 0 3 6 9 (0,0) (0,1) (0,2) (0,0) (0,1) (0,2) (0,3) 3 4 5 1 4 7 10 (1,0) (1,1) (1,2) Fortran C (1,0) (1,1) (1,2) (1,3) 6 7 8 2 5 8 11 (2,0) (2,1) (2,2) (2,0) (2,1) (2,2) (2,3) 9 10 11 (3,0) (3,1) (3,2)
In the C-style of N -dimensional indexing shown on the left of Figure 2.3 thelast N -dimensional index “varies the fastest.” In other words, to move throughcomputer memory sequentially, the last index is incremented first, followed by thesecond-to-last index and so forth. Some of the algorithms in NumPy that deal withN -dimensional arrays work best with this kind of data. In the Fortran-style of N -dimensional indexing shown on the right of Figure 2.3,the first N -dimensional index “varies the fastest.” Thus, to move through computermemory sequentially, the first index is incremented first until it reaches the limit inthat dimension, then the second index is incremented and the first index is reset tozero. While NumPy can be compiled without the use of a Fortran compiler, severalmodules of SciPy (available separately) rely on underlying algorithms written inFortran. Algorithms that work on N -dimensional arrays that are written in Fortrantypically expect Fortran-style arrays. The two-styles of memory layout for arrays are connected through the transposeoperation. Thus, if A is a (contiguous) C-style array, then the same block of mem-ory can be used to represent AT as a (contiguous) Fortran-style array. This kindof understanding can be useful when trying to optimize the wrapping of Fortransubroutines, or if a more detailed understanding of how to write algorithms forgenerally-indexed arrays is desired. But, fortunately, the casual user who does notcare if an array is copied occasionally to get it into the right orientation needed fora particular algorithm can forget about how the array is stored in memory and justvisualize it as an N -dimensional array (that is, after all, the whole point of creatingthe ndarray object in the first place).
272.3.2 Non-contiguous memory layoutBoth of the examples presented above are single-segment arrays where the entirearray is visited by sequentially marching through memory one element at a time.When an algorithm in C or Fortran expects an N-dimensional array, this singlesegment (of a certain fundamental type) is usually what is expected along withthe shape N -tuple. With a single-segment of memory representing the array, theone-dimensional index into computer memory can always be computed from theN -dimensional index. This concept is explored further in the following paragraphs. Let ni be the value of the ith index into an array whose shape is represented bythe N integers di (i = 0 . . . N − 1). Then, the one-dimensional index into a C-stylecontiguous array is N X −1 N Y −1 nC = ni dj i=0 j=i+1
N X −1 i−1 Y nF = ni dj . i=0 j=0
so that if m < k, the product is 1. While perfectly general, these formulas may bea bit confusing at first glimpse. Let’s see how they expand out for determining theone-dimensional index corresponding to the element (1, 3, 2) of a 4 × 5 × 6 array. Ifthe array is stored as Fortran contiguous, then
nF = n0 · (1) + n1 · (4) + n2 · (4 · 5) = 1 + 3 · 4 + 2 · 20 = 53.
nC = n0 · (5 · 6) + n1 · (6) + n2 · (1) = 1 · 30 + 3 · 6 + 2 · 1 = 50.
28 The formulas for the one-dimensional index of the N-dimensional arrays revealwhat results in an important generalization for memory layout. Notice that eachformula can be written as N X −1 X n = n i sX i i=0
N Y −1 sC i = dj = di+1 di+2 · · · dN −1 , j=i+1 i−1 Y sF i = dj = d0 d1 · · · di−1 . j=0
NOTE Several algorithms in NumPy work on arbitrarily strided arrays. However, some algorithms require single-segment arrays. When an irregularly strided array is passed in to such algorithms, a copy is automatically made. 3 Our definition of stride here is an element-based stride, while the strides attribute returns a
byte-based stride. The byte-based stride is the element itemsize multiplied by the element-basedstride.
29 An important situation where irregularly strided arrays occur is array indexing.Consider again Figure 2.3. In that figure a high-lighted sub-array is shown. DefineC to be the 4 × 3 C contiguous array and F to be the 3 × 4 Fortran contiguousarray. The highlighted areas can be written respectively as C[1:3,1:3] and F [1:3,1:3].As evidenced by the corresponding highlighted region in the one-dimensional viewof the memory, these sub-arrays are neither C contiguous nor Fortran contiguous.However, they can still be represented by an ndarray object using the same stridingtuple as the original array used. Therefore, a regular indexing expression on anndarray can always produce an ndarray object without copying any data. Thisis sometimes referred to as the “view” feature of array indexing, and one can seethat it is enabled by the use of striding information in the underlying ndarrayobject. The greatest benefit of this feature is that it allows indexing to be donevery rapidly and without exploding memory usage (because no copies of the dataare made).
30arrays with a size of 1 along a particular dimension act as if they had the size of thearray with the largest shape along that dimension. The value of the array elementis assumed to be the same along that dimension for the “broadcasted” array. Afterapplication of the broadcasting rules, the sizes of all arrays must match. While a little tedious to explain, the broadcasting rules are easy to pick up bylooking at a couple of examples. Suppose there is a ufunc with two inputs, A andB. Now supposed that A has shape 4 × 6 × 5 while B has shape 4 × 6 × 1. Theufunc will proceed to compute the 4 × 6 × 5 output as if B had been 4 × 6 × 5 byassuming that B[..., k] = B[..., 0] for k = 1, 2, 3, 4. Another example illustrates the idea of adding 1’s to the beginning of the arrayshape-tuple. Suppose A is the same as above, but B is a length 5 array. Becauseof the first rule, B will be interpreted as a 1 × 1 × 5 array, and then because of thesecond rule B will be interpreted as a 4 × 6 × 5 array by repeating the elements ofB in the obvious way. The most common alteration needed is to route-around the automatic pre-pending of 1’s to the shape of the array. If it is desired, to add 1’s to the endof the array shape, then dimensions can always be added using the newaxis namein NumPy: B[..., newaxis, newaxis] returns an array with 2 additional 1’s appendedto the shape of B. One important aspect of broadcasting is the calculation of functions on regularlyspaced grids. For example, suppose it is desired to show a portion of the multipli-cation table by computing the function a ∗ b on a grid with a running from 6 to 9and b running from 12 to 16. The following code illustrates how this could be doneusing ufuncs and broadcasting.
312.5 Summary of new featuresMore information about using arrays in Python can be found in the old Numeric doc-umentation at. Quite abit of that documentation is still accurate, especially in the discussion of array ba-sics. There are significant differences, however, and this book seeks to explain themin detail. The following list tries to summarize the significant new features (overNumeric) available in the ndarray and ufunc objects of NumPy:
1. more data types (all standard C-data types plus complex floats, Boolean, string, unicode, and void *);
2. flexible data types where each array can have a different itemsize (but all elements of the same array still have the same itemsize);
3. there is a true Python scalar type (contained in a hierarchy of types) for every data-type an array can have;
4. data-type objects define the data-type with support for data-type objects with fields and subarrays which allow record arrays with nested records;
7. array scalars covering all data types which inherit from Python scalars when appropriate;
9. arrays can be more easily read from text files and created from buffers and iterators;
10. arrays can be quickly written to files in text and/or binary mode;
11. arrays support the removal of the 64-bit memory limitation as long as you have Python 2.5 or later;
12. fancy indexing can be done on arrays using integer sequences and Boolean masks;
3213. coercion rules are altered for mixed scalar / array operations so that scalars (anything that produces a 0-dimensional array internally) will not determine the output type in such cases.
15. errors are handled through the IEEE floating point status flags and there is flexibility on a per-thread level for handling these errors;
16. one can register an error callback function in Python to handle errors are set to ’call’ for their error handling;
17. ufunc reduce, accumulate, and reduceat can take place using a different type then the array type if desired (without copying the entire array);
18. ufunc output arrays passed in can be a different type than expected from the calculation;
19. ufuncs take keyword arguments which can specify 1) the error handling explic- itly and 2) the specific 1-d loop to use by-passing the type-coercion detection.
20. arbitrary classes can be passed through ufuncs ( array wrap and array priority expand previous array method);
22. ufuncs have attributes to detail their behavior, including a dynamic doc string that automatically generates the calling signature;
23. several new ufuncs (frexp, modf, ldexp, isnan, isfinite, isinf, signbit);
24. new types can be registered with the system so that specialized ufunc loops can be written over new type objects;
25. new types can also register casting functions and rules for fitting into the “can-cast” hierarchy;
26. C-API enhanced so that more of the functionality is available from compiled code;
27. C-API enhanced so array structure access can take place through macros;
28. new iterator objects created for easy handling in C of non-contiguous arrays;
33 29. new multi-iterator object created for easy handling in C of broadcasting;
30. types have more functions associated with them (no magic function lists in the C-code). Any function needed is part of the type structure.
34 (d) from Numeric import * –> from numpy.oldnumeric import * (e) Similar name changes need to be made for Matrix, MLab, UserAr- ray, LinearAlgebra, RandomArray RNG, RNG.Statistics, and FFT. The new names are numpy.oldnumeric.<pkg> where <pkg> is matrix, mlab, user array, linear algebra, random array, rng, rng stats, and fft. (f) multiarray and umath (if you used them directly) are now numpy.core.multiarray and numpy.core.umath, but it is more future proof to replace usages of these internal modules with numpy.oldnumeric.
2. Method name changes and methods converted to attributes. The alter code1 module handles all these changes.
35 (e) ’u’ –> ’I’
4. arr.flat now returns an indexable 1-D iterator. This behaves correctly when passed to a function, but if you expected methods or attributes on arr.flat — besides .copy() — then you will need to replace arr.flat with arr.ravel() (copies only when necessary) or arr.flatten() (always copies). The alter code1 module will change arr.flat to arr.ravel() unless you used the construct arr.flat = obj or arr.flat[ind].
5. If you used type-equality testing on the objects returned from arrays, then you need to change this to isinstance testing. Thus type(a[0]) is float or type(a[0]) == float should be changed to isinstance(a[0], float). This is because array scalar objects are now returned from arrays. These inherit from the Python scalars where they can, but define their own methods and attributes. This conversion is done by alter code1 for the types (float, int, complex, and Ar- rayType)
6. If your code should produce 0-d arrays. These no-longer have a length as they should be interpreted similarly to real scalars which don’t have a length.
7. Arrays cannot be tested for truth value unless they are empty (returns False) or have only one element. This means that if Z: where Z is an array will fail (unless Z is empty or has only one element). Also the ’and’ and ’or’ operations (which test for object truth value) will also fail on arrays of more than one element. Use the .any() and .all() methods to test for truth value of an array.
8. Masked arrays return a special nomask object instead of None when there is no mask on the array for the functions getmask and attribute access arr.mask
9. Masked array functions have a default axis of None (meaning ravel), make sure to specify an axis if your masked arrays are larger than 1-d.
10. If you used the construct arr.shape=<tuple>, this will not work for array scalars (which can be returned from array operations). You cannot set the shape of an array-scalar (you can read it though). As a result, for more general code you should use arr=arr.reshape(<tuple>) which works for both array-scalars and arrays.
The alter code1 script should handle the changes outlined in steps 1-5 above. Thefinal incompatibilities in 6-9 are less common and must be modified by hand ifnecessary.
362.6.2 Second-step changesDuring the second phase of migration (should it be necessary) the compatibilitylayer is dropped. This phase requires additional changes to your code. There isanother conversion module (alter code2) which can help but it is not complete.The changes required to drop dependency on the compatibility layer are
1. Importing
2. The typecode names are all lower-case and refer to type-objects corresponding to array scalars. The character codes are understood by array-creation func- tions but are not given names. All named type constants should be replaced with their lower-case equivalents. Also, the old character codes ’1’, ’s’, ’w’, and ’u’ are not understood as data-types. It is probably easiest to manually replace these with Int8, Int16, UInt16, and UInt32 and let the alter code2 script convert the names to lower-case typeobjects.
37 (a) All typecode= keywords must be changed to dtype=. (b) The savespace keyword argument has been removed from all functions where it was present (array, sarray, asarray, ones, and zeros). The sarray function is equivalent to asarray.
5. The nonzero function in NumPy returns a tuple of index arrays just like the corresponding method. There is a flatnonzero function that first ravels the array and then returns a single index array. This function should be interchangeable with the old use of nonzero.
6. The default axis is None (instead of 0) to match the methods for the func- tions take, repeat, sum, average, product, sometrue, alltrue, cumsum, and cumproduct (from Numeric) and also for the functions average, max, min, ptp, prod, std, and mean (from MLab).
7. The default axis is None (instead of -1) to match the methods for the functions argmin, argmax, compress
Convert the file with the given filename to use NumPy. If orig is True, then a backup is first made and given the name filename.orig. Then, the file is converted and the updated code written over the top of the old file.
38 Converts all the “.py” files in the given directory to use NumPy. Backups of all the files are first made if orig is True as explained for the convertfile function.
converttree (direc=os.path.curdir)
Walks the tree pointed to by direc and converts all “.py” modules in each sub- directory to use NumPy. No backups of the files are made. Also, con- verts all .h and .c files to replace ’’Numeric/arrayobject.h’’ with ’’numpy/oldnumeric.h’’ so that NumPy is used.
1. Switch from using typecode characters to bitwidth type names or c-type names
2. Convert use of uppercase type-names Int32, Float, etc., to lower case int32, float, etc.
4. The names for standard computations like Fourier transforms, linear algebra, and random-number generation have changed to conform to the standard of lower-case names possibly separated by an underscore.
5. Look for ways to take advantage of advanced slicing, but remember it always returns a copy and may be slower at times.
6. Remove any kludges you inserted to eliminate problems with Numeric that are now gone.
7. Look for ways to take advantage of new features like expanded data-types (record-arrays).
39 8. See if you can inherit from the ndarray directly, rather than using user array.container (UserArray). However, if you were using UserArray in a multiple-inheritance hierarchy this is going to be more difficult and you can continue to use the standard container class in user array (but notice the name change).
9. Watch your usage of scalars extracted from arrays. Treating Numeric arrays like lists and then doing math on the elements 1 by 1 was always about 2x slower than using real lists in Python. This can now be 3x-6x slower than using lists in NumPy because of the increased complexity of both the indexing of ndarrays and the math of array scalars. If you must select individual scalars from NumPy, you can get some speed increases by using the item method to get a standard Python scalar from an N-d array and by using the itemset method to place a scalar into a particular location in the N-d array. This complicates the appearance of the code, however. Also, when using these methods inside a loop, be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration.
Throughout this book, warnings are inserted when compatibility issues with oldNumeric are raised. While you may not need to make any changes to get code torun with the ndarray object, you will likely want to make changes to take advantageof the new features of NumPy. If you get into a jam during the conversion process,you should be aware that Numeric and NumPy can both be used together and theywill not interfere with each other. In addition, if you have Numeric 24.0 or newer,they can even share the same memory. This makes it easy to use NumPy as wellas third-party tools that have not made the switch from Numeric yet.
40compilation. On the Python-side the largest number of differences are in the methods andattributes of the array and the way array data-types are represented. In addition,arrays containing Python Objects, strings, and records are an integral part of thearray object and not handled using a separate class (although enhanced separateclasses do exist for the case of character arrays and record arrays). As is the case with Numeric, there is a two-step process available for migrat-ing code written for Numarray to work with NumPy. This process involves run-ning functions in the modules alter code1 and alter code2 located in the numar-ray sub-package of NumPy. These modules have interfaces identical to the onesthat convert Numeric code, but they work to convert code written for numarray.The first module will convert your code to use the numarray compatibility module(numpy.numarray), while the second will try and help convert code to move awayfrom dependency on the compatibility module. Because many users will proba-bly be content to only use the first step, the alter code2 module for second-stagemigration may not be as complete as it otherwise could be. Also, the alter code1 module is not guaranteed to convert every piece of workingnumarray code to use NumPy. If your code relied on the internal module structure ofnumarray or on how the class hierarchy was laid out, then it will need to be changedmanually to run with NumPy. Of course you can still use your code with Numarrayinstalled side-by-side and the two array objects should be able to exchange datawithout copying.
41 • from numarray import <names> –> from numpy.numarray import <names>
• .flat –> probably .ravel() (Many usages will still work correctly because you can index and assign to self.flat)
42 • .togglebyteorder() –> numarray.togglebyteorder(self)
43 • nd image –> scipy.ndimage
If you don’t want to install all of scipy, you can grab just these packages from SVNusing
On a Windows system, you can use the Tortoise SVN client which is integrated intothe Windows Explorer. It can be downloaded from on how to use it are also provided on that site. After downloadingthe packages from SVN, installation will still require a C-compiler (the mingw32compiler works fine even with MSVC-compiled Python as long as you specify –compiler=mingw32). Alternatively you can download binary releases of scipy from to get the needed functionality or use the Enthon edition ofPython.
44Chapter 3
Don’t worry about people stealing your ideas. If your ideas are any good, you’ll have to ram them down people’s throats.
—Ellen Glasgow
45 WARNING Numeric Compatibility: you should check your old use of the .flat attribute. This attribute now returns an iterator object which acts like a 1-d array in terms of indexing. while it does not share all the attributes or methods of an array, it will be interpreted as an array in functions that take objects and convert them to arrays. Furthermore, Any changes in an array converted from a 1-d iterator will be reflected back in the original array when the converted array is deleted.
Array flags provide information about how the memory area used for the array is to be interpreted. There are 6 Boolean flags in use which govern whether or not:
46 Table 3.1: Attributes of the ndarray. Attribute Settable Description flags No special array-connected dictionary-like object with attributes showing the state of flags in this ar- ray; only the flags WRITEABLE, ALIGNED, and UPDATEIFCOPY can be modified by setting at- tributes of this object shape Yes tuple showing the array shape; setting this at- tribute re-shapes the array strides Yes tuple showing how many bytes must be jumped in the data segment to get from one entry to the next ndim No number of dimensions in array data Yes buffer object loosely wrapping the array data (only works for single-segment arrays) size No total number of elements itemsize No size (in bytes) of each element nbytes No total number of bytes used base No object this array is using for its data buffer, or None if it owns its own memory dtype Yes data-type object for this array real Yes real part of the array; setting copies data to real part of current array imag Yes imaginary part, or read-only zero array if type is not complex; setting works only if type is complex flat Yes one-dimensional, indexable iterator object that acts somewhat like a 1-d array ctypes No object to simplify the interaction of this array with the ctypes modulearray interface No dictionary with keys (data, typestr, descr, shape, strides) for compliance with Python side of array protocol array struct No array interface on C-levelarray priority No always 0.0 for base type ndarray
47 Certain logical combinations of flags can also be read using named keys to the special flags dictionary. These combinations are
NOTE The array flags cannot be set arbitrarily. UPDATEIFCOPY can only be set False. the ALIGNED flag can only be set True if the data is truly aligned. The flag WRITEABLE can only be set True if the array owns its own memory or the ultimate owner of the memory exposes a writeable buffer interface (or is a string). The exception for string is made so that unpickling can be done without copying memory.
Flags can also be set and read using attribute access with the lower- case key equivalent (without first letter support). Thus, for example, self.flags.c contiguous returns whether or not the array is C-style contiguous, and self.flags.writeable=True changes the array to be writeable (if possible).
shape
The shape of the array is a tuple giving the number of elements in each dimension. The shape can be reset for single-segment arrays by setting this attribute to another tuple. The total number of elements cannot change. However, a -1 may be used in a dimension entry to indicate that the array length in that dimension should be computed so that the total number of elements does not change. a.shape=x is equivalent to a=a.reshape(x) except the latter can be used even if the array is not single-segment and even if a is an array scalar.
48 NOTE Setting the shape attribute to () for a 1-element array will turn self into a 0-dimensional array. This is one of the few ways to get a 0-dimensional array in Python. Most other operations will return an array scalar. Other ways to get a 0-dimensional array in Python include calling array with a scalar argument and calling the squeeze method of an array whose shape is all 1’s.
strides
The strides of an array is a tuple showing for each dimension how many bytes must be skipped to get to the next element in that dimension. Setting this attribute to another tuple will change the way the memory is viewed. This attribute can only be set to a tuple that will not cause the array to access unavailable memory. If an attempt is made to do so, ValueError is raised.
ndim
The number of dimensions of an array is sometimes called the rank of the array. Getting this attribute reveals the length of the shape tuple and the strides tuple.
data
A buffer object referencing the actual data for this array if this array is single- segment. If the array is not single-segment, then an AttributeError is raised. The buffer object is writeable depending on the status of self.flags.writeable.
size
itemsize
nbytes
base
49 If the array does not own its own memory, then this attribute returns the object whose memory this array is referencing. The returned object may not be the original allocator of the memory, but may be borrowing it from still another object. If this array does own its own memory, then None is returned unless the UPDATEIFCOPY flag is True in which case self.base is the array that will be updated when self is deleted. UPDATEIFCOPY gets set for an array that is created as a behaved copy of a general array. The intent is for the misaligned array to get any changes that occur to the copy.
dtype
A data-type object that fully describes (including any defined fields) each fixed- length item in the array. Whether or not the data is in machine byte-order is also determined by the data-type. The data-type attribute can be set to anything that can be interpreted as a data-type (see Chapter 7 for more information). Setting this attribute allows you to change the interpretation of the data in the array. The new data-type must be compatible with the array’s current data-type. The new data-type is compatible if it has the same itemsize as the current data-type descriptor, or (if the array is a single-segment array) if the the array with the new data-type fits in the memory already consumed by the array.
dtype.type
A Python type object gives the typeobject whose instances represent elements of the array. This type object can be used to instantiate a scalar of that type.
dtype.char
dtype.str
50 This string consists of a required first character giving the “endianness” of the data (“<” for little endian, “>” for big endian, and “|” for irrelevant), the second character is a code for the kind of data (’b’ for Boolean, ’i’ for signed integer, ’u’ for unsigned integer, ’f’ for floating-point, ’c’ for complex floating point, ’O’ for object, ’S’ for ASCII string, ’U’ for unicode, and ’V’ for void), the final characters give the number of bytes each element uses.
real
The real part of an array. For arrays that are not complex this attribute returns the array itself. Setting this attribute allows setting just the real part of an array. If the array is already real then setting this attribute is equivalent to self[...] = values.
imag
A view of the imaginary part of an array. For arrays that are not complex, this returns a read-only array of zeros. Setting this array allows in-place alteration of the complex part of an imaginary array. If the array is not complex, then trying to set this attribute raises an Error.
flat
Return. As an example, consider the following code:
51 >>> a = zeros((4,5)) >>> b = ones(6) >>> add(b,b,a[1:3,0:3].flat) array([[ 2., 2., 2.], [ 2., 2., 2.]]) >>> print a [[ 0. 0. 0. 0. 0.] [ 2. 2. 2. 0. 0.] [ 2. 2. 2. 0. 0.] [ 0. 0. 0. 0. 0.]]
The numpy.flatiter object has two methods: array () and copy() and one attribute: base. The base attribute returns a reference to the underlying array.
array priority
The array priority attribute is a floating point number useful in mixed operations involving two subtypes to decide which subtype is returned. The base ndarray object has priority 0.0 and 1.0 is the default subtype priority.
array interface
data A 2-tuple (dataptr, read-only flag). The dataptr is a string giving the address (in hexadecimal format) of the array data. The read-only flag is True if the array memory is read-only. strides The strides tuple. Same as strides attribute except None is returned if the array is C-style contiguous.
52 shape The shape tuple. Same as shape attribute. typestr A string giving the format of the data. Same as dtype.str attribute. descr A list of tuples providing the detailed description of this data type. This information is obtained from the arrdescr attribute of the dtypedescr object associated with each array. For arrays with fields, this will return a valid array-protocol descriptor list. For arrays without defined fields, this returns [(”,typestr)].
array struct
ctypes
This attribute creates an object that makes it easier to use arrays when calling out to shared libraries with the ctypes module. The returned object has data, shape, and strides attributes which return ctypes objects that can be used as arguments to a shared library. These attributes are:]. shape (c intp*self.ndim) A ctypes array of length self.ndim where the base- type is the C-integer corresponding to dtype(’p’) base- type is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array.
53 as parameter (c void p) Returns the data-pointer to the array as a ctypes object. Among other possible uses, this enables this ctypes object to be used directly in a ctypes-loaded call to an arbitrary function. Be sure to respect the flags on the array and the size and strides of the array so as not to use this memory in-appropriately (see the ndpointer function for how to return a class that can be used with the argtypes attribute of ctypes functions). be- fore the next Python statement. You can avoid this problem using either c=a+b or ct=(a+b).ctypes. In the latter case, ct will hold a reference to the array until ct is deleted or re-assigned.
The ctypes object also has several methods which can alter how the shape, strides, and data of the underlying object is returned.
data as (obj) Return the data pointer cast-to a particular c-types ob- ject..
543.2 ndarray MethodsIn NumPy, the ndarray object has many methods which operate on or with thearray in some fashion, typically returning an array result. In Numeric, many ofthese methods were only library calls. These methods are explained in this chapter.Whenever the array whose method is being called needs to be referenced it will bereferred to as this array, or self. Keyword arguments will be shown. Methods thatonly take one argument do not have keyword arguments. Default values for oneargument methods will be shown in braces {default}.
WARNING If you are converting code from Numeric, then you will need to make the following (search and re- place) conversions: .typecode() --> .dtype.char; .iscontiguous() --> .flags.contiguous; .byteswapped() --> .byteswap(); .toscalar() --> .item(); and .itemsize() --> .itemsize. The numpy.oldnumeric.alter code1 module can automate this for you.
item (*args)
If no arguments are passed in, then this method only works for arrays with one element (a.size == 1). In this case, it returns a standard Python scalar object (if possible) copied from the first element of self. When the data type of self is longdouble or clongdouble, this returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item() unless fields are defined in which case a tuple is returned.
55 >>> asc = a[0,0].item() >>> type(asc) <type ’int’> >>> asc 1 >>> type(a[0,0]) <type ’numpy.int32’>
If arguments are provided, then they indicate indices into the array (either a flat index or an nd-index). A standard Python scalar corresponding to the item at the given location is then returned. This is very similar to self[args] except instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.
itemset (*args)
There must be at least 1 argument and define the last argument as item. Then, this is equivalent to but faster than self[args] = item. The item should be a scalar value and args must select a single item in the array.
tostring (order=’C’)
A Python string showing a copy of the raw contents of data memory. The string can be produced in either ’C’ or ’Fortran’, or ’Any’ order (the default is ’C’- order). ’Any’ order means C-order unless the F CONTIGUOUS flag in the array is set, then ’Fortran’ order.
Write the contents of self to the open file object. If file is a string, then open a file of that name first. If sep is the empty string, then write the file in binary mode. If sep is any other string, write the array in simple text mode separating each element with the value of the sep string. When the file is written in text mode, the format string can be used to alter the appearance of each entry. If format is the empty string, then it is equivalent to ‘‘%s’’. Each element of the array will be converted to a Python scalar, o, and written to the file as ‘‘format’’ % o. Note that writing an array to a file does not store any information about the shape, type, or endianness of an array. When written in binary mode, tofile is functionally equivalent to fid.write(self.tostring()).
56 >>> a.tofile(’myfile.txt’,sep=’:’,format=’%03d’) Contents of myfile.txt 001:002:003:004:005:006
dump (file)
Pickle the contents of self to the file object represented by file. Equivalent to cPickle.dump(self, file, 2)
dumps ()
astype ({None})
Force conversion of this array to an array with the data type provided as the argument. If the argument is None, or equal to the data type of self, then return a copy of the array.
byteswap ({False})
Byteswap the elements of the array and return the byteswapped array. If the argu- ment is True, then byteswap in-place and return a reference to self. Otherwise, return a copy of the array with the elements byteswapped. The data-type de- scriptor is not changed so the array will have changed numbers.
copy ()
view ({None})
Return a new array using the same memory area as self. If the optional argument is given, it can be either a typeobject that is a sub-type of the ndarray or an object that can be converted to a data-type descriptor. If the argument is a typeobject then a new array of that Python type is returned that uses the information from self. If the argument is a data-type descriptor, then a new array of the same Python type as self is returned using the given data-type.
57 >>> print a.view(single) [[ 1.40129846e-45 2.80259693e-45 4.20389539e-45] [ 5.60519386e-45 7.00649232e-45 8.40779079e-45]] >>> a.view(ubyte) array([[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0], [4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0]], dtype=uint8)
Return a field of the given array as an array of the given data type. A field is a view of the array’s data at a certain byte offset interpreted as a given data type. The returned array is a reference into self, therefore changes made to the returned array will be reflected in self. This method is particularly useful for record arrays that use a void data type, but it can also be used to extract the low (high)-order bytes of other array types as well. For example, using getfield, you could extract fixed-length substrings from an array of strings.
>>> a = array([’Hello’,’World’,’NumPy’]) >>> a.getfield(’S2’,1) array([’el’, ’or’, ’um’], dtype=’|S2’)
fill (scalar)
Fill an array with the scalar value (appropriately converted to the type of self). If the scalar value is an array or a sequence, then only the first element is used. This method is usually faster than a[...]=scalar or self.flat=scalar, and always interprets its argument as a scalar.
58 Table 3.2: Array conversion methods
593.2.2 Array shape manipulationFor reshape, resize, and transpose, the single tuple argument may be replaced withn integers which will be interpreted as an n-tuple.
Return an array that uses the same data as this array but has a new shape given by the newshape tuple (or a scalar to reshape as 1-d). The new shape must define an array with the same total number of elements. If one of the elements of the new shape tuple is -1, then that dimension will be determined such that the overall number of items in the array stays constant. If possible, the new array will reference the data of the old one. If the data must be moved in order to accomplish the reshape, then then the new array will contain a copy of the data in self. The order argument specifies how the array data should be viewed during the reshape (either in ’C’ or ’FORTRAN’ order). This order argument specifies both how the intrinsic raveling to a 1-d array should occur as well as how that 1-d array should be used to fill-up the new output array.
Resize an array in-place. This changes self (in-place) to be an array with the new shape, reallocating space for the data area if necessary. If the data memory must be changed because the number of new elements is different than self.size, then an error will occur if this array does not own its data or if another object is referencing this one. Only a single-segment array can be resized. The method returns None. To bypass the reference count check, then set refcheck=0. The purpose of the reference count check is to make sure you don’t use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array to another Python object, then you may safely set refcheck=0.
transpose (<None>)
Return an array view with the shape transposed according to the argument. An argument of None is equivalent to range(self.ndim)[::-1]. The argument can either be a tuple or multiple integer arguments. This method returns a new array with permuted shape and strides attributes using the same data as self.
60 >>> a = arange(40).reshape((2,4,5)) >>> b = a.transpose(2,0,1) >>> print a.shape, b.shape (2, 4, 5) (5, 2, 4) >>> print a.strides, b.strides (80, 20, 4) (4, 80, 20) >>> print a [[[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]]
[[20 21 22 23 24] [25 26 27 28 29] [30 31 32 33 34] [35 36 37 38 39]]] >>> print b [[[ 0 5 10 15] [20 25 30 35]]
[[ 1 6 11 16] [21 26 31 36]]
[[ 2 7 12 17] [22 27 32 37]]
[[ 3 8 13 18] [23 28 33 38]]
[[ 4 9 14 19] [24 29 34 39]]]
Return an array view with axis1 and axis2 swapped. This is a special case of the transpose method with argument equal to arg=range(self.ndim); arg[axis1], arg[axis2] = arg[axis2], arg[axis1]. See the rollaxis function for a routine that transposes the array with the axes rolled instead of swapped.
61flatten (order=’C’)
Return a new 1-d array with data copied from self. Equivalent to but slightly faster then a.flat.copy().
ravel (order=’C’)
Return a 1-d version of self. If self is single-segment, then the new array references self, otherwise, a copy is made.
squeeze ()
The functionality of this method is available using the advanced indexing ability of the ndarray object. However, for doing selection along a single axis it is usually faster to use take. If axis is not None, this method is equivalent to self[indxobj] preceeded by indxobj=[slice(None)]*self.ndim; indxobj[axis] = indices. It returns the elements or sub-arrays from self indicated by the index numbers in indices. If axis is None, then this method is equivalent to self.flat[indices]. The out and mode arguments allow for specification of the output array and how out-of-bounds indices will be handled (’raise’: raise an error, ’wrap’: wrap around, ’clip’: clip to range)
for n in indices: self.flat[n] = values[n]
62 Copy elements (or sub-arrays selected along axis) of self repeats times. The repeats argument must be a sequence of length self.shape[axis] or a scalar. The repeats argument dictates how many times the element (or sub-array) will be repeated in the result array.
The array must be an integer (or bool) array with entries from 0 to n. Choices is a tuple of n choice arrays: b0, b1, . . . , bn. (Alternatively, choices can be replaced with n arguments where each argument is a choice array). The return array will be formed from the elements of the choice arrays according to the value of the elements of self. In other words, the output array will merge the choice arrays together by using the value of self at a particular position to select which choice array should be used for the output at a particular position. The out keyword allows specification of an output array and the clip keyword allows different behavior when self contains entries outside the number of choices. The acceptable arguments to mode are ’raise’ (RAISE), ’wrap’ (WRAP), and ’clip’ (CLIP) (’raise’ produces an error, ’wrap’ converts the number into range by periodic wrapping so that numbers <0 have n repeatedly added and numbers >= n have n repeatedly subtracted, and ’clip’ will clip all entries to be within the range [0,n).
>>> a = array([0,3,2,1]) >>> a.choose([0,1,2,3],[10,11,12,13], ... [20,21,22,23],[30,31,32,33]) array([ 0, 31, 22, 13])
Sort the array in-place and return None. The sort takes place over the given axis using an underlying sort algorithm specified by kind. The sorting algorithms available are ’quick’, ’heap’, and ’merge’. For flexible types only the quicksort algorithm is available..
63 >>> a=array([[0.2,1.3,2.5],[1.5,0.1,1.4]]); >>> b=a.copy(); b.sort(0); print b [[ 0.2 0.1 1.4] [ 1.5 1.3 2.5]] >>> b=a.copy(); b.sort(1); print b [[ 0.2 1.3 2.5] [ 0.1 1.4 1.5]]
Return an index array of the same size as self showing which indices along the given axis should be selected to sort self along that axis. Uses an underlying sort algorithm specified by kind. The sorting algorithms available are ’quick’, ’heap’, and ’merge’..
i TIP Complex valued arrays sort lexicographically by comparing first the real parts and then the imaginary parts if the real parts are the same.
Return an index array (dtype=intp) of the same shape as values showing the index where the value would fit in self. The index is such that self[index-1]
64 < value ≤ self[index] when side is ’left’. In this formula self[self.size]=∞ and self[-1]=−∞. Therefore, if value is larger than all elements of self, then index is self.size. If value is smaller than all elements of self, then index is 0. Self must be a sorted 1-d array. If elements of self are repeated, the index of the first occurrence is used. If side is ’right’, then the search rule is switched so that the < sign is on the “right” instead of the left in the search rule. In other words, the index returned is such that self[index-1] ≤value < self[index].
nonzero ()
Return the n-dimensional indices for elements of the n-dimensional array self that are nonzero into an n-tuple of equal-length index arrays. In particular, notice that a 0-dimensional array always returns an empty tuple.
>>> x=array([0,1,2,3]) >>> x.compress(x > 2) array([3]) >>> x[x>2] array([3])
65diagonal (offset=0, axis1=0, axis2=1)
If self is 2-d, return the offset (from the main diagonal) diagonal of self. If self is larger than 2-d, then return an array constructed from all the diagonals created from all the 2-d sub-arrays formed using all of axis1 and axis2. The offset parameter is with respect to axis2. The shape of the returned array is found by removing the axis1 and axis2 entries from self.shape and then appending the length of the offset diagonal of each 2-d sub-array.
66Table 3.3: Array item selection and shape manipulation methods. If axis is anargument, then the calculation is performed along that axis. An axis value of Nonemeans the array is flattened before calculation proceeds.
67 Return the largest value in self. This is a better way to compute the maximum over an array, than using max(self). The latter uses the generic sequence in- terface to self. This will be slower, and will try to get an answer by comparing whole sub-arrays of self. This will be incorrect for arrays larger than 1-d.
Return the smallest value in self. This is a better way to compute the minimum over an array, than using min(self). The latter uses the generic sequence in- terface to self. This will be slower, and will try to get an answer by comparing whole sub-arrays of self. This will be incorrect for arrays larger than 1-d.
Return the difference of the largest to the smallest value in self. Equivalent to self.max(axis) - self.min(axis)
Return a new array where any element in self less than min is set to min and any element less than max is set to max. Equivalent to self[self<min]=min; self[self>max]=max.
conj (out=None)
conjugate (out=None)
Round the elements of the array to the nearest decimal. For decimals < 0, the rounding is done to the nearest tens, hundreds, etc. Rounding of exactly the half-interval is to the nearest even integer. This is the only difference with standard Python rounding.
68 Perform a summation along each diagonal specified by offset, axis1, and axis2. Equivalent to diagonal(offset,axis1,axis2).sum(axis=-1, dtype=dtype)
Return the cumulative sum. If ret is the return array of the same shape as self, then j X ret[:, . . . , :, j] = self[:, . . . , :, i]. | {z } | {z } i=0 axis axis
N −1 1 X self[:, . . . , :, i] N i=0 | {z } axis
where N is self.shape[axis] and axis ’:’ objects are placed before the i. The sum is done in the data-type of self unless self is an integer or Boolean data-type and then it is done over the float data-type.
69 as they may have larger mean-square error. The sum is done using a float data-type if self has integer or Boolean data-type, otherwise it is done using the same data-type as self.
N Y −1 self[:, . . . , :, i]. | {z } i=0 axis
Return the cumulative product so that the return array, ret, is the same shape as self and j Y ret[:, . . . , :, j] = self[:, . . . , :, i]. | {z } | {z } i=0 axis axis
Return True if all entries along axis evaluate True, otherwise return False.
Return True if any entries along axis evaluate True, otherwise return False.
70Table 3.4: Array object calculation methods. If axis is an argument, then thecalculation is performed along that axis. An axis value of None means the arrayis flattened before calculation proceeds. All of these methods can take an optionalout= argument which can specify the output array to write the results into.
713.3 Array Special MethodsMethods in this chapter are not generally meant to be called directly by the user.They are called by Python and are used to customize behavior of the ndarray objectas it interacts with the Python language and standard library.
deepcopy (memodict)
reduce ()
Pickling support for arrays is provided by these two methods. When an array needs to be pickled, the reduce () method is called to provide a 3-tuple of already-pickleable objects. To construct a new object from the pickle, the first two elements of the 3-tuple are used to construct a new (0-length) array of the correct type and the last element of the 3-tuple, which is itself a 4-tuple of (shape, typestr, isfortran, data) is passed to the setstate method of the newly created array to restore its contents.
The reduce method returns a 3-tuple consisting of (callable, args, state) where callable is a simple constructor function that handles subclasses of the ndar- ray. Also, args is a 3-tuple of arguments to pass to this constructor function (type(self), (0,), self.dtypechar), and state is a 4-tuple of information giving the object’s state (self.shape, self.dtypedescr, isfortran, string or list). In this tuple, isfortran is a Bool stating whether the following flattened data is in Fortran order or not, and string or list is a string formed by self.tostring() if the data type is not object. If the data type of self is an object array, then string or list is a flat list equivalent to self.ravel().tolist().
72 On load from a pickle, the pickling code uses the first two elements from the tuple returned by reduce to construct an empty 0-dimensional subclass of the correct type. The last element is then passed to the setstate method of the newly created array to restore its contents.
NOTE When data is a string, the setstate method will directly use the string memory as the array memory (new.base will point to the string). The typestr contains enough information to decode how the memory should be interpreted.
This method creates a new ndarray. It is typically only used in the new method of a subclass. This method is called to construct a new array whenever the object name is called, a=ndarray(...). It supports two basic modes of array creation:
1. a single-segment array of the specified shape and data-type from newly allo- cated memory;
(a) uses shape, dtype, strides, and order arguments; others are ignored; (b) The order argument allows specification of a Fortran-style contiguous memory segment (order=’Fortran’); (c) If strides is given, then it specifies the new strides of the array (and the order keyword is ignored). The strides will be checked for consistency with the dimension size so that steps outside of the memory won’t occur.
2. an array of the given shape and data type using the provided object, buffer, which must export the buffer interface.
73 (c) order indicates whether the data buffer should be interpreted as Fortran- style contiguous (order=’Fortran’) or not; (d) offset can be used to start the array data at some offset in the buffer.
NOTE The ndarray uses the default no-op init function because the array is completely initialized after new is called.
This is a special method that should always return an object of type ndarray. Useful for subclasses that need to get to the ndarray object.
This is a special method that always returns an object of the same Python type as self using the array passed as an argument. This is mainly useful for subclasses as it is an easy way to get the subclass back from an ndarray.
lt (other)
le (other)
gt (other)
ge (other)
eq (other)
ne (other)
Defined to support rich comparisons (<, <=, >, >=, ==, !=) on ndarrays using universal functions.
str ()
repr ()
These functions print the array when called by str(self) and repr(self) respectively. Array printing can be changed using set string function(..). Default array printing has been borrowed from numarray whose printing code was written by Perry Greenfield and J. Todd Miller. By default, arrays print such that
74 1. The last axis is always printed left to right.
3. Remaining axes are printed top to bottom with increasing numbers of sepa- rators.
Five parameters of the printing can be set using keyword arguments with set printoptions(...). The parameters can all be retrieved using get printoptions(). These printing options are
precision the number of digits of precision for floating point output (default 8); threshold total number of array elements which triggers summarization rather than full representation (default 1000); edgeitems number of array items in summary at beginning an end of each dimension (default 3); linewidth the number of characters per line for the purpose of inserting line breaks (default 71); suppress Boolean indicating whether or not to suppress printing of small floating point values using scientific notation (default False).
nonzero ()
Truth-value testing for the array as a whole. It is called whenever the truth value of the ndarray as a whole object is required. This raises an error if the number of elements in the the array is larger than 1 because the truth value of such arrays is ambiguous. Use .any() and .all() instead to be clear about what is meant in such cases. If the number of elements is 0 then False is returned. If there is one element in the array, then the truth-value of this element is returned.
75 Notice that the default Python iterator for sequences is used when arrays are used in places that expect an iterator. This iterator returns successively self[0], self[1], ..., self[self. len ()]. Use self.flat to get an iterator that walks through the entire array one element at a time.
getitem (key)
Called when evaluating self[key] construct. Items from the array can be selected using this customization. This construct has both standard and extended indexing abilities which are explained in Section 3.4. A named field can be retrieved if key is a string and fields are defined in the dtypedescr object associated with this array.
Called when evaluating self[key]=value. Items in the array can be set using this construct. This construct is explained in Section 3.4. A named field can be set if key is a string and fields are defined in the dtypedescr object associated with this array.
getslice (i, j)
Equivalent to self. getitem (slice(i,j)) but defined mainly so that C code can use the sequence interface. Called to evaluate self[i:j]
Equivalent to self. setitem (slice(i,j), value) but defined mainly so C code can use the sequence interface. Called to evaluate self[i:j] = value.
contains (item)
Called to determine truth value of the item in self construct. Returns the equivalent of (self==item).any()
add (other)
sub (other)
76div (other)
truediv (other)
floordiv (other)
mod (other)
divmod (other)
pow (other[,modulo])
lshift (other)
rshift (other)
and (other)
or (other)
xor (other)
These methods are defined for ndarrays to implement the operations (+, -, *, /, /, //, %, divmod(), ** or pow(), <<, >>, &, ˆ, |). This is done using calls to the corresponding universal function object (add, subtract, multiply, divide, true divide, floor divide, remainder, divide and remainder, power, left shift, right shift, bitwise and, bitwise xor, bitwise or). These implement element- by-element operations for arrays that are broadcastable to the same shape.
• the three division operators are all defined, div is active by default, truediv is active when future .division is in effect.
NOTE Because it is a built-in type (written in C), the r<op> special methods are not directly defined for the ndarray.
773.3.4.2 In-place
iadd (other)
isub (other)
imul (other)
idiv (other)
itruediv (other)
ifloordiv (other)
imod (other)
ipow (other)
ilshift (other)
irshift (other)
iand (other)
ixor (other)
ior (other)
These methods are implemented to handle the inplace operatiors (+=, -=, *=, /=, /=, //=, %=, **=, <<=, >>=, &=, ˆ=, |=). The inplace operators are implemented using the corresponding ufunc and its ability to take an output argument (which is set as self). Using inplace operations can save space and time and is therefore encouraged whenever appropriate.j casts the result to fit back in a, while a=a+3j re-binds the name a to the result.
783.3.4.3 Unary operations
neg (self)
pos (self)
abs (self)
invert (self)
These functions are called in response to the unary operations (-, +, abs(), ˜). With the exception of pos , these are implemented using ufuncs (negative, absolute, invert). The unary + operator, however simply calls self.copy(), and can therefore be used to get a copy of an array.
complex (self)
int (self)
long (self)
float (self)
oct (self)
hex (self)
These functions are also defined for the ndarray object to handle the operations complex(), int(), long(), float(), oct(), and hex(). They work only on arrays that have one element in them and return the appropriate scalar.
i TIP The function called to implement many arithmetic special meth- ods for arrays can be modified using the function set numeric ops. This function is called with keyword arguments indicating which operation(s) to replace. A dictionary is returned containing show- ing the old functions. By default, these functions are set to the corresponding ufunc.
793.4 Array indexingMore powerful array indexing was an important extension introduced by numarray,and was therefore an important part of the development of NumPy. In particular,the desire to select arbitrary elements based on their position in the array, andaccording to a mask was desirable. There are two kinds of indexing available using the X[obj] syntax: basic slicing,and advanced indexing. For the description of this syntax given below, X is the arrayto-be-sliced and obj is the selection object. Furthermore, define N ≡X.ndim. Thesetwo methods of slicing have different behavior and are triggered depending on obj.Adding additional functionality yet remaining compatible with old uses of slicingcomplicated the rules a little. Hopefully, after studying this section, you will havea firm grasp of what kind of selection will be initiated depending on the selectionobject.
i TIP in Python X[(exp1, exp2, ..., expN)] is equivalent to X[exp1, exp2, ..., expN] as the latter is just syntactic sugar for the former.
80 defaults to n for k > 0 and −1 for k < 0. If k is not given it defaults to 1. Note that ’::’ is the same as ’:’ and means select all indices along this axis.
• If the number of objects in the selection tuple is less than N , then ’:’ is assumed for any remaining dimensions.
• Ellipsis expand to the number of ’:’ objects needed to make a selection tuple of the same length as X.ndim. Only one ellipsis is expanded, any others are interpreted as more ’:’
• Each newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension. The added dimension is the position of the newaxis object in the selection tuple.
• If the selection tuple has all entries ’:’ except the pth entry which is a slice object i : j : k, then the returned array has dimension N formed by con- catenating the sub-arrays returned by integer indexing of elements i, i + k, i + (m − 1)k < j,
•. Note this is NOT true for advanced slicing.
• You may use slicing to set values in the array, but (unlike lists) you can never grow the array. The size of the value to be set in X[obj] = value must be (broadcastable) to the same shape as X[obj].
Basic slicing always returns another view of the array. In other words, the returnedarray from a basic slicing operation uses the same data as the original array. Thiscan be confusing at first, but it is faster and can save memory. A copy can alwaysbe obtained if needed using the unary + operator (which has lower precedence thanslicing) or the .copy() method.
81 i TIP.
3.4.2.1 Integer
Integer indexing allows selection of arbitrary items in the array based on theirN -dimensional index. This kind of selection occurs when advanced selection is trig-gered and the selection object is not an array of data type bool. For the discussionbelow, when the selection object is not a tuple, it will be referred to as if it hadbeen promoted to a 1-tuple, which will be called the selection tuple. The rules ofadvanced integer-style indexing are:
• all sequences and scalars in the selection tuple are converted to intp indexing arrays.
• all selection tuple objects must be convertible to intp arrays, or slice objects, or the Ellipsis (...) object.
• Exactly one Ellipsis object will be expanded, any other Ellipsis objects will be treated as full slice (’:’) objects. The Ellipsis object is replaced with as many full slice (’:’) objects as needed to make the length of the selection tuple N .
82• If the selection tuple is smaller than N , then as many ’:’ objects as needed are added to the end of the selection tuple so that the modified selection tuple has length N .
• The shape of all the integer indexing arrays must be broadcastable to the same shape. Arrays are broadcastable if any of the following are satisfied
• The shape of the output (or the needed shape of the object to be used for setting) is the broadcasted shape.
• After expanding any ellipses and filling out any missing (’:’) objects in the selection tuple, then let Nt be the number of indexing arrays, and let Ns = N − Nt be the number of slice objects. Note that Nt > 0 (or we wouldn’t be doing advanced integer indexing).
83 • If Ns > 0, then partial indexing is done. This can be somewhat mind-boggling to understand, but if you think in terms of the shapes of the arrays involved, it can be easier to grasp what happens. In simple cases (i.e. one indexing array and N −.
3.4.2.2 Boolean
This advanced selection occurs when obj is an array object of Boolean type (such asmay be returned from comparison operators). It is always equivalent to (but fasterthan) X[obj.nonzero()] where as described above obj.nonzero() returns a tuple (oflength obj.ndim) of integer index arrays showing the True elements of obj. The special case when obj.ndim == X.ndim is worth mentioning. In this caseX[obj] returns a 1-dimensional array filled with the elements of X corresponding tothe True values of obj. It The search order will be C-style (last index varies thefastest). If obj has True values at entries that are outside of the bounds of X, thenan index error will be raised.
84 You can also use Boolean arrays as element of the selection tuple. In suchinstances, they will always be interpreted as nonzero(obj) and the equivalent integerindexing will be done. In general you can think of indexing with Boolean arrays asindexing with nonzero(<Boolean>).
WARNING the definition of advanced selection means that X[(1,2,3),] is fun- damentally different than X[(1,2,3)]. The latter is equivalent to X[1,2,3] which will trigger basic selection while the former will trig- ger advanced selection. Be sure to understand why this is True. You should also recognize that x[[1,2,3]] will trigger advanced se- lection, but X[[1,2,slice(None)]] will trigger basic selection.
85Chapter 4
Basic Routines
Do not pray for tasks equal to your powers; pray for powers equal to your tasks. Then the doing of your work shall be no miracle, but you shall be the miracle.
—Phillips Brooks
Education isn’t how much you have committed to memory, or even how much you know. It’s being able to differentiate between what you do know and what you don’t.
—Anatole France
Create a new ndarray of data type, dtype (or determined from object if dtype is None). The shape of the new array will be determined from object. If copy is True, then ensure a copy of the object is made. If copy is False, then the returned object is a copy of the array only if dtype is not equivalent to the data type of object. If order is ’Fortran’ then the resulting array will be in Fortran order, otherwise it is in C order. If subok (subclasses are O.K.) is True then pass through subclasses of the array object if possible. If subok is False
86 then only ndarray objects may be returned. The ndmin parameter specifies that the returned array must have at least the given number of dimensions.
Exactly the same as array(...) except the default copy argument is False, and subok is always False. Using this function always returns the base class ndar- ray.
Thin wrapper around array(...) with subok=1. You should use this routine if you are only making use of the array attributes, and believe the calculations that will follow would work with any subclass of the array. Use of this routine increases the chance that array subclasses will interact seamlessly with your function — returning the same subclasses.
87 with element i equal to start + i · step. If stop is None, then the first argument is interpreted as stop and start is 0.
NOTE By definition of the ceiling function (denoted by ⌈x⌉), we know that x ≤ ⌈x⌉ < x + 1, therefore this definition of the length of arange guarantees that start+n·step ≥ stop as well as start+(n−1)·step < stop.
isfortran (arr)
Return an uninitialized array of data type, dtype, and given shape. The memory layout defaults to C-style contiguous, but can be made Fortran-style contigu- ous with a ’Fortran’ order keyword.
Return an array of data type dtype and given shape filled with zeros. The memory layout may be altered from the default C-style contiguous with the order keyword.
If sep is ”, then return a new 1-d array with data-type descriptor given by dtype and with memory initialized (copied) from the raw binary data in string. If count is non-negative, the new array will have count elements (with a
88 ValueError raised if count requires more data than the string offers), other- wise the size of the string must be a multiple of the itemsize implied by dtype, and count will be the length of the string divided by the itemsize.
If sep is not ”, then interpret the string in ASCII mode with the provided separator and convert the string to an array of numbers. Any additional white-space will be ignored.
Return a 1-d array of data type, dtype, from a file (open file object or string with the name of a file to read). The file will be read in binary mode if sep is the empty string. Otherwise, the file will be read in text mode with sep providing the separator string between the entries. If count is -1, then the size will be determined from the file, otherwise, up to count items will be read from the file. If fewer than count items are read, then a RunTimeWarning is issued indicating the number of items read.
load (file)
Load a pickled array from an open file. If file is a string, then open a file with that name first. Except for the automatic file opening equivalent to cPickle.load(file)
loads (str)
89 Return an array of dtype representing n(=len(dimensions)) grids of indices each with variation in a single direction. The returned array has shape (n,)+dimensions. Compare with mgrid.
>>> indices((2,3)) array([[[0, 0, 0], [1, 1, 1]],
[[0, 1, 2], [0, 1, 2]]])
Construct an array from a function called on a tuple of index grids. The function should be able to take array arguments and process them like ufuncs (use vectorize if it doesn’t). The function should accept as many arguments as there are dimensions which is a sequence of numbers indicating the length of the desired output for each axis. Keyword arguments to function may also be passed in as keywords to fromfunction.
Return a 2-d array of shape (n,n) and data type, dtype with ones along the main diagonal.
Returns an array shaped like condition, that has the elements of x and y respec- tively where condition is respectively true or false. If x and y are not given, then it is equivalent to nonzero(condition).
flatnonzero (arr)
90putmask (arr=, mask=, values=)
The values array is repeated if it is too short. In particular, this means that indexing on the values array is modular it’s length, which might be surprising you are expecting putmask to work the same as arr[mask]=values.
Return an array of indices similar to argsort except sorting is done using all of the provided keys. First a sort is computed using key[0], then the indices are further altered by sorting on key[1]. This is repeated until sorting has been performed on all of the keys. This is a useful function for multiple-field sorting.
Notice the order the keys had to be used in order to get a lexicographical sorting order. To clarify, suppose three equal-length sequences are fields of an un- derlying data-type: (f1,f2,f3). If we want to sort first on f1 and then on f2 and then on f3, the indices that would accomplish that sort are obtained as lexsort((f3,f2,f1)).
Construct a new array from elements of the sequence object seq concatenated along the given axis. The elements of the sequence object must have compat- ible types and be the same shape. If axis is None, then flatten each element of seq before concatenating together to construct a 1-d array.
91correlate (x, y, mode=’valid’)
Compute the 1-d cross correlation of x and y keeping portions determined by mode which may be ’valid’ (0), ’same’ (1), or ’full’ (2). The ’full’ cross-correlation between two 1-d arrays is computed as
min(n,K) X z [n] = x [i] y [n + i] , i=max(n−M,0)
If mode is ’same’ then only the K middle values are returned starting at n = M−1 2 . If the flag has a value of ’valid’ then only the middle K − M + 1 = (K + 1) − (M + 1) + 1 output values are returned starting at n = M.
The mode keyword has the same effect as it does for correlation. Convolution (’full’) between two 1-d arrays implements polynomial multiplication where the array entries are viewed as coefficients for polynomials. Example: Consider that (x3 + 4x2 + 2) x4 + 3x + 1 =x7 + 4x6 + 5x4 + 13x3 + 4x2 + 6x + 2. This can be determined by using the code convolve([1,4,0,2], [1,0,0,3,1]) which returns [1,4,0,5,13,4,6,2]. Notice the one-to-one alignment between the elements of the arrays and the coefficients on powers of x in the polyno- mial.
outer (a, b)
92 >>> print outer([1,2,3],[10,100,1000]) [[ 10 100 1000] [ 20 200 2000] [ 30 300 3000]]
inner (a, b)
Computes the inner product between two arrays. This is an array that has shape a.shape[:-1] + b.shape[:-1] with elements computed as the sum of the product of the elements from the last dimensions of a and b. In particular, let I and J be the super1 indices selecting the 1-dimensional arrays a[I, :] and b[J, :], then the resulting array, r, is X r[I, J] = a[I, k]b[J, k]. k
dot (a, b)
Computes the dot (matrix) product between two arrays. The product-sum is over the last dimension of a and the second-to-last dimension of b. Specifically, if I and J are super indices for a[I, :] and b[J, :, j] so that j is the index of the last dimension of b. Then, the shape of the resulting array is a.shape[:-1] + b.shape[:-2] + (b.shape[-1],) with elements. X r[I, J, j] = a[I, k]b[J, k, j], k
vdot (a, b)
Computes the dot product between two arrays (flattened into one-dimensional vectors) after conjugating the first vector. This is an inner-product following the physicists convention of conjugating the first argument. X r= a.flat[k]b.flat[k]. k
93 Computes a dot-product between two arrays where the sum is taken over the axes specified by the 2-sequence which can have either scalar or sequence entries. The axes specified are summed over and the remaining axes are used to construct the result. So, for example, if a is 3 × 4 × 5 and b is 4 × 3 × 2 then if axes=([1,0],[0,1]) (or axes=([0,1],[1,0])) the result will be 5 × 2. Let I represent the indices of the un-summed axes in a, let J represent the indices of the un-summed axes in b and let K represent the the indices of the axes summed over in both a and b. Also, let at represent a transposed version of a where the axes to be summed over are pushed to the end, and let bt represent a transposed version of b where the axes to be summed over are pushed to P the front. Then, using K to represent a multi-index sum, the result can be written as X r[I, J] = at [I, K]bt [K, J] K
Returns the cross product of two (arrays of) vectors. The cross product is per- formed over the axes of the input arrays indicated by the axisa, and axisb arguments. For both arrays, the axis used must have dimension either 2 or 3. If both axes used have dimension 2, then only the z-component of the equiv- alent 3-d cross product is returned. Otherwise, the entire vector is returned. The axisc argument gives the axis of the vectors in the returned cross-product result. If axis is not None, then it is assumed that axisa=axisb=axisc=axis (regardless of what else is specified).
Returns true if all components of a and b are equal subject to the given relative and absolute tolerances. This returns true if every element of a and b satisfy
The default printing mechanism uses this function to produce a string from an array.
94set printoptions (precision=None, theshold=None, edgeitems=None, linewidth=None, suppress=None)
precision the default number of digits of precision for floating point output (default 8); threshold total number of array elements which triggers printing only the “ends” of the array rather than a full representation (default 1000); edgeitems number of array elements in summary at beginning and end of each dimension (default 3); linewidth the number of characters per line (default 75); suppress Boolean value indicating whether or not to suppress printing of small floating point values using scientific notation (default False).
get printoptions ()
95shape, compress, clip, std, var, mean, sum, cumsum, product, cumprod-uct, sometrue (method is .any), alltrue (method is .all), around (method is.round), rank (attribute is .ndim), shape, size (.size or .shape[axis]), and copy.
Return a data-type object from any object. See Chapter 7 for a more detailed explanation of what can be interpreted as a data-type object and the meaning of the align keyword.
Returns the array-scalar type of highest precision of the same general kind as arg which can be any recognized form for describing a data-type.
issctype (obj)
Returns True if obj is an array data type (or a recognized alias for one)
Returns the array type object corresponding to obj which can be an array type already, a python type object, an actual array, or any recognized alias for an array type object. If no suitable data type object can be determined, return default.
sctype2char (sctype)
Return the typecode character associated with an array-scalar type dtype. The first argument is first converted to a dtype if it needs to be.
96 i TIP the type attribute of data-type objects are actual Python type ob- jects subclassed in a hierarchy of types. This can often be useful to check data types generically. For example, issubclass(dtype.type, integer) can check to see if the data type is one of the 10 different integer types. The issubclass function, however, raises an error if ei- ther argument is not an actual type object. NumPy defines (arg1, arg2) that will return false instead of raise an error. Alternatively, dtype.kind is a character describing the class of the data-type so dtype.kind in ’iu’ would also check to see if the data-type is an integer type.
Return Boolean value indicating whether or not data type d1 can be cast to data type d2 safely (without losing precision or information).
97Chapter 5
Additional ConvenienceRoutines
—John F. Kennedy
Your mind can only hold one thought at a time. Make it a positive and constructive one.
atleast 2d (a1,a2,...,an)
Force a sequence of arrays (including array scalars) to each be at least 2-d. Di- mensions of length 1 are pre-pended to reach a two-dimensional array.
atleast 3d (a1,a2,...,an)
Force a sequence of arrays (including array scalars) to each be at least 3-d. Di- mensions of length 1 are pre-pended to reach a two-dimensional array.
98roll .
Stack a sequence of arrays as columns into a 2-d array. 1-d arrays are converted to 2-d arrays and transposed. All arrays must have shapes so that the resulting array is well defined. Compare with hstack.
Stack a sequence of 1-d arrays as rows into a 2-d array (alias for vstack).
dstack (seq)
Stack a sequence of arrays along the third axis (depth wise). Arrays in seq must have the same shape along all dimensions but the third. Rebuilds array di- vided by vsplit.
99array split (ary, i or s, axis=0)
Divide ary into a list of sub-arrays along the specified axis. The i or s argument stands for indices or sections. If i or s is an integer, ary is divided into that many equally-sized arrays. If it is impossible to make an even split, each of the leading arrays in the returned list have one additional member. If i or s is a list of sorted integer, its entries define the indexes where ary is split. An empty list for i or s results in a single sub-array equal to the original array.
hsplit (ary, i or s)
Split a single array into multiple columns of sub-arrays (along the first axis if 1-d or along the second second if >1-d). Only works on arrays of 1 or more dimension.
vsplit ()
Split a single array into multiple rows of sub-arrays (along the first axis). Only works on arrays of 2 or more dimensions.
dsplit ()
Split a single array into multiple sub-arrays along the third axis (depth). Only works on arrays of 3 or more dimensions.
Execute func1d(arr[sel i], *args) where func1d takes 1-d arrays and arr is an N-d array, where sel i is a selection object sufficient to select a 1-d sub-array along the given axis. The function is executed for all 1-d arrays along axis in arr.
For each axis in the axes sequence, call func as res=func(a, axis). If res is the same shape as a then set a=res and continue. if res.ndim = a.ndim -1, then insert a dimension before axis and continue.
100 Expand the shape of array a by including newaxis before the given axis.
Returns a new array with the specified shape which can be any size. The new array is filled with repeated copies of a. This function is similar in spirit to a.resize(new shape) except that it fills in the new array with repeated copies and returns a new array.
kron (a, b)
Return a composite array with blocks from b scaled by elements of a. The number of dimensions of a and b should be the same. If not, then the input with fewer dimensions is pre-pended with ones (broadcast) to the same shape as the input with more dimensions. The return array has this same number of dimensions with shape given by the product of the shape of a and the shape of b. If either a or b is a scalar then this function is equivalent to multiply(a,b).
Example:
>>> kron([1,10,100],[5,6,7]) array([ 5, 6, 7, 50, 60, 70, 500, 600, 700]) >>> kron([[1,10],[100,1000]],[[2,3],[4,5]]) array([[ 2, 3, 20, 30], [ 4, 5, 40, 50], [ 200, 300, 2000, 3000], [ 400, 500, 4000, 5000]])
101 Tile an N -dimensional array using the shape information in reps to create a larger N -dimensional array. This is equivalent to kron(ones(reps, a.dtype), a). The number of dimensions of a and the length of shape should be the same or else 1’s will be pre-pended to make them the same.
>>> tile([5,6,7],(1,2,3)) array([[[5, 6, 7, 5, 6, 7, 5, 6, 7], [5, 6, 7, 5, 6, 7, 5, 6, 7]]])
Computes the average along the indicated axis. If axis is None, average over the entire array. Inputs can be integer or floating types; result is type float. If weights are given, the result is sum(a*weights)/sum(weights). Therefore, weights must have shape equal to a.shape or be 1-d with length a.shape[axis]. Integer weights are converted to float. If returned is True, then return a tuple showing both the result and the sum of the weights (or count of the values). The shape of these two results will be the same.
102 It can be approximated as
N −1 1 X H C≈ (xi − x̄) (xi − x̄) P i=0
msort (a)
Return a new array, sorted along the first axis. Equivalent to b=a.copy(); b.sort(0)
median (m)
The list argument is a 1-d integer array. Let r be the returned 1-d array whose length is (list.max()+1). If weights is None, then r[i] is the number of occur- rences of i in list. If weight is present, then the ith element is X r[i] = weights[j]. j:list[j]=i
103digitize (x=,bins=)
Return an array of integers the same length as x with values i such that bins [i − 1] ≤ x < bins [i] if bins is monotonically increasing, or bins[i] ≤ x < bins[i − 1] if bins is monotonically decreasing. When x is beyond the bounds of bins, return either i = 0 or i =len(bins) as appropriate.
Compute the two-dimensional histogram for a dataset (x,y) given the bins. Re- turns (histogram, xedges, yedges). The bins argument can be either the num- ber of bins or a sequence of the bin edges if the x and y directions should have the same bins. If the bins argument is a sequence of length 2, then separate bin edges will be computed. The first element can be either the number of bins or the bin edges for the x-direction. The second element is interpreted as the number of bins or the bin edges for the y-direction. The returned histogram array, H, is a count of the number of samples in each bin. The array is ori- ented such that H[i,j] is the number of samples falling into binx[j] and biny[i] (notice the association x<->j and y<->i). Setting normed to True returns a density rather than a bin-count. The range argument allows specifying lower and upper bin edges (in a sequence of length 2 with 2-length sequences in each entry). The default is [[x.min(), x.max()],[y.min(), y.max()]].
104 that a point in the sample data fell into the volume bin specified. The edges sequence has D-entries to specify the edge boundaries for each dimension. The bins argument is a sequence of edge arrays or a sequence of the number of bins. If a scalar is given, it is assumed to be the number of bins for all dimensions. The range is a length-D sequence containing lower and upper bin edges which default to the min and maximum of the respective datasets. If normed is True, then a density rather than a bin-count is returned.
Evenly spaced samples on a logarithmic scale. Returns num evenly spaced (in logspace) samples from base**start to base**stop. If endpoint is True, then the last sample is base**stop.
Evenly spaced samples. Returns num evenly spaced samples from start to stop. If endpoint is True, then the last sample is stop. If retstep is True, then return the computed step size.
meshgrid (x, y)
For 1-d arrays x, y with lengths Nx=len(x) and Ny = len(y), return X, Y where X and Y are (Ny, Nx) shaped arrays with the elements of x and y repeated to fill the array.
105 The choicelist argument is a list of choice arrays (of the same size as the arrays in condlist). The result has the same size as the arrays in choicelist. If condlist is [c0 , . . . , cN −1 ], then choicelist must be of length N . The elements of choicelist can then be represented as [v0 , . . . , vN −1 ]. The default choice if none of the conditions are met is given as the default argument. The conditions are tested in order and the first one satisfied is used to select the choice. In other words, the elements of the output array are found from the following tree (evaluated on an element-by-element basis)
if c0 : v0 elif c1 : v1 ... elif cN −1 : vN −1 else: default
where S1 are sets. Thus, the function is defined differently over different sub- domains of the input. Such a function can be computed using select but such an implementation means calling each fi over the entire region of x. The piecewise call guarantees that each function fi will only be called over those values of x in Si .
Arguments: x is the array of values over which to call the function; condlist is a sequence of Boolean (indicator) arrays (or a single Boolean array) of the same shape as x that defines the sets (True indicates that element of x is in the set). If needed, to match the length of funclist, an “otherwise” set will be added to S condlist. This otherwise set is defined as Sn = Si . The argument funclist is a list of functions to be called (or items to be inserted) corresponding to the conditions. Each of these functions can take extra arguments and key-word arguments which are passed in as *args, and **kw using standard Python syntax. Each of these functions should return vector output for vector input.
106 If the function is a scalar, then it will simply be inserted where appropriate into the output. It is the equivalent of a constant function. Example: Suppose we want to compute f (x) = x2 Π x3 + u (x − 5) where Π (x) = 1 only when |x| ≤ 1 and u (x) = 1 only when x ≥ 0. This could be done using the code:
Trim the leading (’f’ in trim) and trailing (’b’ in trim) zeros from a sequence according to the trim keyword.
Calculates the nth order, discrete difference along the given axis.
107angle (z, deg=0)
Unwraps radian phase p by changing absolute jumps greater than discont to their 2π complement along the given axis.
unique (seq)
Return a new array with the sub-arrays indicated by indices along axis removed. If axis is None, then first ravel the array and set axis to -1. The indices argument describes which sub-arrays along the given axis should be removed. It can be an integer, a slice object, or a sequence of integers. A new array is created with the corresponding sub-arrays are removed.
108insert (arr, indices, values, axis=None)
Create a new array with values inserted into arr before indices. If axis is None, then first ravel the array and set axis to -1. The indices argument describes which indices along the provided axis the values should be inserted before. It can be an integer, a slice object, or a sequence of integers. The values argument must be broadcastable to the shape implied by where they will be inserted.
Return a new array with values appended to the end of the array along axis.
These functions perform their respective operations over the given axis (or the entire array if axis is None), after replacing any nans with appropriate values so as not to affect the calculation.
This creates a class whose instances have a call method that invokes a ufunc that has been dynamically built to call the python function pyfunc internally. The output types can be controlled by the otypes argument. If it is None, then the output types will be determined upon first call to the function using the provided inputs. This can be reset, by re-setting the otypes attribute to “”. The normal rules of array broadcasting are followed by the returned object.
109asarray chkfinite (x)
Like asarray(x) except an error is raised if any of the values in x are not finite.
Return an array with all the elements of x rounded to decimals places. Returns x if array is not floating point and rounds both the real and imaginary parts separately if array is complex. Rounds in the same way as standard python except for half-way values are rounded to the nearest even number.
Adds a docstring to a built-in object, obj, that does not have a docstring defined already. The obj can be a built-in function-or-method, a typeobject, a method descriptor, a getset descriptor, or a member descriptor. This is useful for improving the documentation of objects defined in C-compiled code without re-compiling. If the object already has a docstring, a RuntimeError is raised. If the object is not a supported type the code can add a docstring to, a TypeError is raised.
Adds a docstring to the obj imported from place using exec ’from %s import %s’ % (place, obj). Thus, both place and obj should be strings. If doc is a string, then a single docstring is added to obj from place. If doc is a 2-tuple, then obj must be an object with attributes that need to be commented. The first element of the doc tuple is the attribute to be commented on and the second element is the actual docstring. If doc is a list, then it must be composed of elements that are 2-tuples indicating that obj has several attributes that need to be documented.
110Most of the functions below operate on and return a simple sequence of coeffi-cients representing a polynomial. There is, however, a simple polynomial class thatprovides some utility for doing simple algebra on polynomials.
poly1d (c or r, r=0)
>>> p=poly1d([2,5,7]) >>> print p 2 2 x + 5 x + 7 >>> print p*[1,3,1] 4 3 2 2 x + 11 x + 24 x + 26 x + 7 >>> print p([0.5,0.6,3]) [ 10. 10.72 40. ] >>> print p.r [-1.25+1.3919j -1.25-1.3919j]
roots (poly)
111 Return the roots of the polynomial represented by coefficients in poly
Example:
p (x) = x2 + 3x + 4 Z Z 1 4 1 3 p (x) = x + x + 2x2 + k0 x + k1 12 2
polyder (poly, m)
Return an exact mth -order derivative of the polynomial represented in poly. Also available as .deriv(m=1) method of poly1d objects.
p (x) = x3 + 2x2 + 4x + 3 dp (x) = 3x2 + 4x + 4 dx
>>> polyder([1,2,4,3]) array([3, 4, 4])
Return coefficients for the polynomial found by subtracting the two polynomials represented by p1 and p2 : p1 (x) − p2 (x)
112polymul (p1, p2)
Return the quotient, q (x), and remainder, r (x), so that p1 (x) = q (x) p2 (x) + r (x) , with the order of r (x) less than the order of p2 (x) .
polyval (p, y)
polyfit (x,y,N)
Return the unique elements of arr as a 1-d array. If retindx is True, then also return the indices, ind, such that arr.flat[ind] is the set of unique values.
113 Return the (sorted) intersection of a1 and a2 but allow a1 and a2 to be N-d arrays with non-unique elements. Equivalent to intersect1d(unique1d(a1), unique1d(a2)).
Return the (sorted) union of a1 and a2 which is an array containing elements that are in either a1 or a2.
Return the (sorted) set containing the exclusive-or of the arrays a1 and a2. The exclusive-or contains elements that are in a1 or in a2 as long as the element is not in both a1 and a2.
Return a Boolean 1-d array of the length of tocheck which is True whenever that element is contained in set and false when it is not. Equivalent to array([x in set for x in tocheck]).
ix (*args)
This indexing cross function is useful for forming indexing arrays necessary to select out the cross-product of N 1-dimensional arrays. Note that the default indexing does not do a cross-product (which might be unexpected for someone coming from other programming environments). The default indexing is more general purpose. Using the ix constructor can produce the indexing arrays necessary to select a cross-product.
114ogrid [index expression]
This is similar to mgrid except it returns an open grid, so as to save space and time. The broadcasting rules will ensure that any universal function operating on the grid will act as if the ogrid had been the result of mgrid.
r [index expression]
This is a simple way to build up arrays quickly. There are two use cases. 1) If the index expression contains comma separated arrays, then stack them along their first axis. 2) If the index expression contains slice notation or scalars then create a 1-d array with a range indicated by the slice notation. In other- words the slice syntax start:stop:step is equivalent to arange(start, stop, step) inside of the brackets. However, if step is an imaginary number (i.e. 100j) then its integer portion is interpreted as a number-of-points desired and the start and stop are inclusive. In other words start:stop:stepj is interpreted as linspace(start, stop, step, endpoint=1) inside of the brackets. After expansion of slice notation, all comma separated sequences are concatenated together.
Optional character strings placed as the first element of the index expression can be used to change the output. The strings ’r’ or ’c’ result in matrix output. If the result is 1-d and ’r’ is specified a 1 × N (row) matrix is produced. If the result is 1-d and ’c’ is specified, then a N × 1 (column) matrix is produced. If the result is 2-d then both provide the same matrix result.
A string integer specifies which axis to stack multiple comma separated arrays along.
115>>> a=arange(6).reshape(2,3)>>> r [a,a]array([[0, 1, 2],[3, 4, 5],[0, 1, 2],[3, 4, 5]])>>> r [’-1’,a,a]array([[0, 1, 2, 0, 1, 2],[3, 4, 5, 3, 4, 5]])
>>> r [’0,2’,[1,2,3],[4,5,6]]array([[1, 2, 3],[4, 5, 6]])>>> r [’1,2’,[1,2,3],[4,5,6]]array([[1, 2, 3, 4, 5, 6]])
116 >>> r [’0,2,0’, [1,2,3], [4,5,6]] array([[1], [2], [3], [4], [5], [6]]) >>> r [’1,2,0’, [1,2,3], [4,5,6]] array([[1, 4], [2, 5], [3, 6]])
c [index expression]
This is short-hand for r [’-1,2,0’, index expression] useful because of its common occurence. In particular, arrays will be stacked along their last axis after being upgraded to at least 2-d with 1’s post-pended to the shape (column vectors made out of 1-d arrays).
Return a tuple of Python objects that implements the index expression and can be modified and placed in any other index expression.
s [index expression]
Translate index expressions into the equivalent Python objects. This is similar to index expression except a tuple is not always returned. For example:
>>> s [1:10] slice(1, 10, None) >>> s [1:10,-3:4:0.5] (slice(1, 10, None), slice(-3, 4, 0.5))
117 This provides a standard way to construct index expressions to pass to functions and methods because Python does not allow slice expressions anywhere except for inside brackets.
ndindex (*seq)
Convert a flat index, indx, into an index tuple for an array of the given shape. Keep in mind that it may be more convenient to use indx with a.flat, then to unravel the index.
Return an N × M array of the given type with ones down the k th diagonal. If M is None, it defaults to N . Alternatively, if M is a valid data type, then it becomes the data-type used.
The Vandermonde matrix of vector, x. The ith column of the return matrix is the mth i power of x where mi = N − i − 1. If N is None, it defaults to the length of x.
>>> vander([1,2,3,4,5],3) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [16, 4, 1], [25, 5, 1]])
118diag (v, k=0)
>>> diag(arange(12).reshape(4,3),k=1) array([1, 5]) >>> diag([1,4,5,7],k=-1) array([[0, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 4, 0, 0, 0], [0, 0, 5, 0, 0], [0, 0, 0, 7, 0]])
Return a 2-d array (of the same class as v) by placing a flattened version of v along the k th diagonal. This differs from diag in that it only creates 2-d arrays and will work with any object that can be converted to an array (returning that object if it also defines an array wrap method).
fliplr (m)
Return the array, m, with rows preserved and columns reversed in the left-right direction. For m.ndim > 2, this works on the first two dimensions (equivalent to m[:,::-1])
flipud (m)
Return the array, m, with columns preserved and rows reversed in the up-down direction. For m.ndim > 1, this works on the first dimension (equivalent to m[::-1])
Rotate the first two dimensions of an array, m, by k*90 degrees in the counter- clockwise direction. Must have m.ndim >=2.
Construct an N × M array where all the diagonals starting from the lower left corner up to the kth diagonal are all ones.
119triu (m, k=0)
Return a upper-triangular 2-d array from m with all the elements below the kth diagonal set to 0.
Return a lower-triangular 2-d array from m with all the elements above the kth diagonal set to 0.
Construct a matrix from data. Alias for numpy.asmatrix. The calling syntax is the same as that function. Note that data can be a string in which case the routine uses spaces and semi-colons to construct the matrix:
Build a matrix from sub-blocks. This is similar to mat, except the items in the nested-sequence, or string, should be appropriately shaped 2-d arrays. If obj is a string, then ldict and gdict can be used to alter where the names represented in the string are found (default is current local and global namespace).
120 Returns True if arg1 is a sub-class of arg2, otherwise returns False. Similar to the built-in issubclass except it does not raise an error if arg1 or arg2 are not types.
Returns True if the type-object of the data-type represented by arg1 is a sub class of the type-object of the data-type represented by arg2.
iscomplexobj (obj)
Return a single True or False value depending on whether or not obj would be interpreted as an array with complex-valued data type.
isrealobj (obj)
Return a single True or False value depending on whether or not obj would be interpreted as an array with real-valued data type.
isscalar (obj)
True if obj is a scalar (an instance of an array data type, or a standard Python scalar type). There is also a sequence of called ScalarType defined in NumPy, so that this can also be tested as type(obj) in numpy.ScalarType.
Returns an array with non-finite numbers changed to finite numbers. The map- ping converts nan to 0, inf to the maximum value for the data type and -inf to the minimum value for the data type.
Return a real arr if arr is complex with imaginary parts less than some tolerance. If tol > 1, then it represents a multiplicative factor on the value of epsilon for the data type of arr.
121 >>> cast[bool]([1,2,0,4,0]).astype(int) array([1, 1, 0, 1, 0])
Return a minimum data type character from typeset that handles all given type- chars. The returned type character must correspond to the data type of the smallest size such that an array of the returned type can handle the data from an array of type t for each t in typechars. If the typechars does not intersect with the typeset, then default is returned. If an element of typechars is not a string, then t=asarray(t).dtypechar is applied.
finfo (dtype)
This class allows exploration of the details of how a floating point number is represented in the computer. It can be instantiated by an inexact data type object (or an alias for one). Complex-valued data types are acceptable and are equivalent to their real-valued counterparts. The attributes of the class are
122 maxexp Smallest (positive) power of 2 that causes overflow. max The largest usable floating value: (1-epsneg)* (2**maxep) min The most negative usable floating value: -max
The most useful attributes are probably eps, max, min, and tiny.
sinc (x)
Compute the sinc function for x which can be a scalar or array. The sinc is defined as y = sinc (x) = sin(πx) πx with the caveat that the limiting value (1.0) of the ratio is taken for x = 0.
123i0 (x)
Modified Bessel function of the first kind of order 0. Needed to compute the kaiser window. The modified Bessel function is defined as Z π ∞ 1 X x2k I0 (x) = ex cos θ dθ = . π 0 k=0 4k (k!)2
blackman (M )
bartlett (M )
hanning (M )
hamming (M )
All of the windowing functions are smoothing windows that attempt to balance the inherent trade off between side-lobe height (ringing) and main-lobe width (resolution) in the frequency domain. A rectangular window has the smallest main-lobe width but the largest side-lobe height. A windowing (tapering) function tries to can help trade off main-lobe width By sacrificing a little in resolution using a windowing function These windows can be used to smooth
124 Smoothing window in time-domain Smoothing window in frequency-domain 1.0 40 Blackman Bartlett 0.8 20 Hanning Hamming 0
Magnitude (dB) 0.6 -20
0.4 -40
Blackman -60 0.2 Bartlett Hanning -80 Hamming 0.0 -100 0 10 20 30 40 50 0.0 0.1 0.2 0.3 0.4 0.5 n Normalized Frequency
Figure 5.1: Blackman, Bartlett, Hanning, and Hamming windows in the time andfrequency domain showing the trade-off between main-lobe width and side-lobeheight (Figures made with matplotlib).
data using the convolve function. Figure 5.1 shows the windowing functions described so far and their time- and frequency-domain behavior.
The trade-off between main-lobe and side-lobe has been studied extensively. So- lutions that maximize energy in the main-lobe compared to energy in the side-lobes can be found by finding an eigenvector which can be expensive to compute for large window sizes. A good approximation to these prolate- spheroidal windows is the Kaiser window.
kaiser (M , β)
125 The length M of the window determines the transition width. To obtain a transition width of ∆ωrad/s the window-length must be at least:
α−8 M= + 1. 2.285∆ω
This function can be used to alter the operations used for internal array calcu- lations and array special methods. Replaceable operations (and possible en- tries for <opN>) are add, subtract, multiply, divide, remainder, power, sqrt, negative, absolute, invert, left shift, right shift, bitwise and, bitwise or, less, less equal, equal, not equal, greater, greater equal, floor divide, true divide, logical or, logical and, floor, ceil, maximum, and minimum. The example code below changes, then restores, the old Numeric behavior of remainder (which was changed because it was not consistent with Python).
>>> a = array([-3.,-2,-1,0,1,2,3]) >>> print a % -2.1 [-0.9 -2. -1. 0. -1.1 -0.1 -1.2] >>> oldops = set numeric ops(remainder=fmod) >>> print a % -2.1 [-0.9 -2. -1. 0. 1. 2. 0.9] >>> newops = set numeric ops(**oldops) >>> print a % -2.1 [-0.9 -2. -1. 0. -1.1 -0.1 -1.2] >>> print 3 % -2.1 # comparison -1.2
get include ()
Return the directory that contains the numpy include files. The numpy.distutils automatically includes this directory in building extensions.
Return the directory that contains the numarray compatible C-API include files. If type is not None, then return a list containing both the numarray compatible
126 C-API include files and the numpy include files. The latter form is only needed when building an extension without the use of numpy.distutils.
Return a deprecated function named ’oldname’ that has been replaced by ’new- name’. This new deprecated function issues a warning before calling the old function. The name and docs of the function are also updated to be oldname instead of the name that func has. Example usage. If you want to deprecate the function named ’old’ in favor of a new function named ’new’ which has the same calling conention then this could be done with the assignment
127Chapter 6
Scalar objects
Never worry about numbers. Help one person at a time, and always start with the person nearest you.
—Mother Teresa
A great many people think they are thinking when they are merely rearranging their prejudices.
—William James
One important new feature of NumPy is the addition of a new scalar objectfor each of the 21 different data types that an array can have. Do not confusethese scalar objects with the data-type objects. There is one data-type object. Itcontains a .type attribute which points to the Python type that each element of thearray will be returned as1 . The built-in data-types point have .type attributes thatpoint to these scalar objects. Five (or six) of these new scalar objects are essentiallyequivalent to fundamental Python types and therefore inherit from them as well asfrom the generic array scalar type. The bool data type is very similar to the PythonBooleanType but does not inherit from it because Python’s BooleanType does notallow itself to be inherited from, and on the C-level the size of the actual bool datais not the same as a Python Boolean scalar. Table 6.1 shows which array scalarsinherit from basic Python types. 1 with the exception of object data-types which return the underlying object and not a “scalar”
type.
128Table 6.1: Array scalar types that inherit from basic Python types. The intc arraydata type might also inherit from the IntType if it has the same number of bits asthe int array data type on your platform.
The array scalars have the same attributes and methods as arrays and live ina hierarchy of scalar types so they can be easily classified based on their type ob-jects. However, because array scalars are immutable, and attributes change intrinsicproperties of the object, the array scalar attributes are not settable. Array scalars can be detected using the hierarchy of data types. For exam-ple, isinstance(val, generic) will return True if val is an array scalar ob-ject. Alternatively, what kind of array scalar is present can be determined usingother members of the data type hierarchy. Thus, for example isinstance(val,complexfloating) will return True if val is a complex valued type, whileisinstance(val, flexible) will return true if val is one of the flexible item-size array types (string, unicode, void).
WARNING The bool type is not a subclass of the int type (the bool type is not even a number type). This is different than Python’s default implementation of bool as a sub-class of int.
flags
129shape
Returns ().
Returns 0.
Return 1.
Returns None.
130 array interface
new (obj)
The default behavior is to return a new array or array scalar by calling array(obj) with the corresponding data type. There are two situations when this default behavior is delayed until another approach is tried. First, when the array scalar type inherits from a Python type, then the Python types new method is called first and the default method is called only if that approach fails. The second situation is for the void data type where a single integer-like argument will cause a void scalar of that size to be created and initialized to 0.
Notice that because array(obj) is called for new, if obj is a nested sequence, then the return object could actually be an ndarray. Thus, arrays of the correct type can also be created by calling the array data type name directly:
>>> uint32([[5,6,7,8],[1,2,3,4]]) array([[5, 6, 7, 8], [1, 2, 3, 4]], dtype=uint32)
131 array (<None>)
squeeze ()
Returns self.
byteswap (<False>)
Trying to set the first (inplace) argument to True raises a ValueError. Otherwise, this returns a new array scalar with the data byteswapped.
reduce ()
setstate ()
setflags ()
132Chapter 7
We cannot expect that all nations will adopt like systems, for con- formity is the jailer of freedom and the enemy of growth.
—John F. Kennedy
—Herbert Simon
133data-type object which is the actual object an ndarray looks to in order to interpreteach element of its data region. Whenever a data-type is required in a NumPyfunction or method, supplying a dtype object is always fastest. If the object suppliedis not a dtype object, then it will be converted to one using dtype(obj). Therefore,understanding data-type objects is the key to understanding how data types arereally represented and understood in NumPy.
7.1 Attributestype The type object used to instantiate a scalar of this data-type.
kind A character code (one of ’biufcSUV’) identifying the general kind of data.
char A unique character code for each of the 21 different built-in types.
num A unique number for each of the 21 different built-in types roughly ordered from least-to-most precision.
name A bit-width name for this data-type (un-sized flexible data-type objects are missing the width).
itemsize The element size of this data-type object. For 18 of the 21 types this number is fixed by the data-type. For the flexible data-types, this number can be anything.
alignment The required alignment (in bytes) of this data-type according to the compiler. More information is available in the C-API section.
fields A dictionary showing any named fields that have been defined for this data- type (or None if there are no named fields). Fields can be assigned to any built- in data-type (e.g. using the tuple input to the dtype constructor). However, fields are most useful for (subtypes of) void data-types which can be any size. Fields are a convenient way to keep track of fixed-size sub-parts of the total fixed-size array-element, or record. A field is defined in terms of another dtype object and an offset (in bytes) into the current record.
134). Notice also, that the first two elements of the tuple can be passed directly as arguments to the getfield and setfield attributes of an ndarray. If field names are not specified in a constructor, they default to ’f0’, ’f2’, ..., ’f<n-1>’.
names An ordered list of field names. This can be used to walk through all of the named fields in offset order. Notice that the defined fields do not have to “cover” the record, but the itemsize of the container data-type object must always be at least as large as the itemsizes of the data-type objects in the defined fields. This attribute is None if there are no fields.
isnative True if this data-type object has a byteorder that is native to the platform; otherwise False.
hasobject True if self contains reference-counted objects in any of it’s fields or sub data-types..
135flags Bit-flags for the data-type describing how the data-type will be in- terpreted. Bit-masks are in numpy.core.multiarray as the constants ITEM HASOBJECT, LIST PICKLE, ITEM IS POINTER, NEEDS INIT, NEEDS PYAPI, USE GETITEM, USE SETITEM. A full explanation of these flags is in the second part of this book. These flags are largely use- ful for user-defined data-types.
7.2 Constructiondtype (obj, align=0, copy=0)
Return a new data-type object from obj. The keyword argument, align, can only be nonzero if obj is a dictionary, or a comma-separated string. If it is non-zero in those cases it is used to add padding as needed to the fields to match what the compiler that compiled NumPy would do to a similar C-struct. The copy argument guarantees a new copy of the data-type object, otherwise, the result may just be a reference to a built-in data-type object.
Objects that can be converted to a data-type object are described in the following list. Because every object in this list can be converted to a data-type object it can also be used whenever a dtype is requested by a function or method in NumPy.
136 3. Builtin types: Several python types are equivalent to a corresponding array scalar when used to generate a dtype object: int –> int ; bool –> bool ; float –> float ; complex –> cfloat; str –> string; unicode –> unicode ; buffer –> void; (all others) –> object . Examples: object, str, float, int 4. Any type object with the dtype attribute: The attribute will be accessed and used directly. The attribute must return something that is convertible into a dtype object.string Several kinds of strings can be converted. Recognized strings can be pre-pended with ’>’, or ’<’, to specify the byteorder. 1. One-character strings: Each built-in data-type has a character code (the updated Numeric typecodes), that uniquely identifies it. Examples: ’b’, ’H’, ’f’, ’d’, ’F’, ’D’, Float64, Int32, UInt16 2. Array-protocol type strings: The first character specifies the kind of data and the remaining characters specify how many bytes of data. The supported kinds are ’b’ –> Boolean, ’i’ –> (signed) integer, ’u’ –> unsigned integer, ’f’ –> floating-point, ’c’ –> complex-floating point, ’S’, ’a’ –> string, ’U’ –> unicode, ’V’ –> anything (void). Examples: ’i4’, ’f8’, ’c16’, ’b1’, ’S10’, ’a25’ 3. Comma-separated field formats: is greater than 1-d. NumPy allows a modification on the format in that any string that can uniquely identify the type can be used to specify the data-type in a field. This data-type defines fields named ’f0’, ’f2’, ..., ’f<N-1>’ where N (>1) is the number of comma-separated basic formats in the string. If the optional shape specifier is provided, then the data-type for the corresponding field contains a subdtype attribute providing the shape. Examples: “i4, (2,3)f8, f4”; “a3, 3u8, (3,4)a10” 4. Any string in NumPy.sctypeDict.keys(): Examples: ’uint32’, ’Int16’, ’Uint64’, ’Float64’, ’Complex64’
137tuple Three kinds of tuples each of length 2 can be converted into a data-type object: 1. (flexible dtype, itemsize): The first argument must be an object that is converted to a flexible data-type object (one whose element size is 0), the second argument is an integer providing the desired itemsize. Examples: (void, 10); (str, 35), (’U’, 10) 2. (fixed dtype, shape): The first argument is any object that can be converted into a fixed-size data-type object. The second argument is the desired shape of this type. If the shape parameter is 1, then the data-type object is equivalent to fixed dtype. Examples: (int32, (2,5)); (’S10’, 1)==’S10’; (’i4, (2,3)f8, f4’, (2,3)) 3. (base dtype, new dtype): Both arguments must be convertible to data-type objects in this case. The base dtype is the data-type object that the new data-type builds on. This is how you could assign named fields to any built-in data-type object. Examples: (int32, {’real’:(int16,0), ’imag’:(int16,2)}); (int32, (int8, 4)); (’i4’, [(’r’,’u1’),(’g’,’u1’),(’b’,’u1’),(’a’,’u1’)])list (array description interface): This style is more fully described at this site. It consists of a list of fields where each field is described by a tuple of length 2 or 3. The first element of the tuple of the tuple can be anything that can be interpreted as a data-type. The optional third element of the tuple contains the shape if this field represents an array of the data- type in the second element. This style does not accept align=1 as it is assumed that all of the memory is accounted for by the array interface description. See the web-page for more examples. Note that a 3-tuple with a third argument equal to 1 is equivalent to a 2-tuple.Examples: [(’big’,’>i4’), (’little’,’<i4’)]; [(’R’,’u1’), (’G’,’u1’), (’B’,’u1’), (’A’,’u1’)]
138 dictionary There are two dictionary styles. The first is a standard dictionary format while the second accepted format allows the fields attribute of dtype objects to be interpreted as a data-type. 1. names and formats: This style has two required and two optional keys. The ’names’ and ’formats’ keys are required. Their respective values are equal-length lists with the field names and the field for- mats. The field names must be strings and the field formats can be any object accepted by dtypedescr constructor. The optional keys in the dictionary are ’offsets’ and ’titles’ and their values must each be lists of the same length as the ’names’ and ’formats’ lists. The ’offsets’ value is a list of integer offsets. Examples: {’names’: [’r’,’g’,’b’,’a’], ’formats’: [uint8, uint8, uint8, uint8]}; {’names’:[’r’,’b’], ’formats’: [’u1’, ’u1’], ’offsets’: [0, 2], ’titles’: [’Red pixel’, ’Blue pixel’]} 2. data-type object fields: This style is patterned after the format of the fields dictionary in a data-type object. It contains string or unicode keys that refer to (data-type, offset) or (data-type, offset, title) tuples. Examples: {’col1’: (’S10’, 0), ’col2’: (float32, 10), ’col3’: (int, 14)}
7.3 Methodsnewbyteorder (<’swap’>)
Construct a new copy of self with its byteorder changed according to the optional argument. All changes are also propagated to the data-type objects of all fields and sub-arrays. If a byteorder of ’|’ (meaning ignore) is encountered it is left unchanged. The default behavior is to swap the byteorder. Other possible arguments are ’big’ (’>’), ’little’ (’<’), and ’native’ (’=’) which recursively forces the byteorder of self (and it’s field data-type objects and any sub-arrays) to the corresponding byteorder.
139reduce ()
setstate (state)
Data-type objects can be pickled because of these two methods. The reduce () method returns a 3-tuple consisting of (callable object, args, state), where the callable object is numpy.core.multiarray.dtype and args is (typestring, 0, 1) unless the data-type inherits from void (or is user-defined) in which case args is (typeobj, 0, 1). The state is an 8-tuple with (version, endian, self.subdtype, self.names, self.fields, self.itemsize, self.alignment, self.flags). The self.itemsize and self.alignment entries are both -1 if the data-type object is built-in and not flexible (because they are fixed on creation). The setstate method takes the saved state and updates the date-type object.
140Chapter 8
Standard Classes
To generalize is to be an idiot.
—William Blake
Not everything that can be counted counts, and not everything that counts can be counted.
—Albert Einstein
141subclasses of the arrayobject will not redefine certain aspects of the array object suchas the buffer interface, or the attributes of the array. One of important example,however, of why your subroutine may not be able to handle an arbitrary subclassof an array is that matrices redefine the ’*’ operator to be matrix-multiplication,rather than element-by-element multiplication.
This method is called whenever the system internally allocates a new array from obj, where obj is a subclass (subtype) of the (big)ndarray. It can be used to change attributes of self after construction (so as to ensure a 2-d matrix for example), or to update meta-information from the “parent.” Subclasses inherit a default implementation of this method that does nothing.
This method should return an instance of the class from the ndarray object passed in. For example, this is called after every ufunc for the object with the highest array priority . The ufunc-computed array object is passed in and whatever is returned is passed to the user. Subclasses inherit a default implementation of this method.
This method is called to obtain an ndarray object when needed. You should always guarantee this returns an actual ndarray object. Subclasses inherit a default implementation of this method.
array priority
The value of this attribute is used to determine what type of object to return in situations where there is more than one possibility for the Python type of the returned object. Subclasses inherit a default value of 1.0 for this attribute.
1428.2 Matrix ObjectsMatrix objects inherit from the ndarray and therefore, they have the same attributesand methods of ndarrays. There are six important differences of matrix objects,however that may lead to unexpected results when you use matrices but expectthem to act like arrays:
5. The default array priority of matrix objects is 10.0, and therefore mixed operations with ndarrays always produce matrices.
6. Matrices have special attributes which make calculations easier. These are
WARNING Matrix objects over-ride multiplication, ’*’, and power, ’**’,.
143 The matrix class is a Python subclass of the ndarray and can be used as areference for how to construct your own subclass of the ndarray. Matrices can becreated from other matrices, strings, and anything else that can be converted to anndarray. The name “mat” is an alias for “matrix” in NumPy.
>>> mat([[1,5,10],[1.0,3,4j]]) matrix([[ 1.+0.j, 5.+0.j, 10.+0.j], [ 1.+0.j, 3.+0.j, 0.+4.j]])
>>> mat(random.rand(3,3)).T matrix([[ 0.7699, 0.7922, 0.3294], [ 0.2792, 0.0101, 0.9219], [ 0.3398, 0.7571, 0.8197]])
mat
144asmatrix (data, dtype=None)
Build a matrix object from a string, nested sequence or an array. This command lets you build up matrices from other other objects. The ldict and gdict parameters are local and module (global) dictionaries that are only used when obj is a string. If they are not provided, then the local and module dictionaries present when bmat is called are used.
NOTE Memory-mapped arrays use the the Python memory-map object which (prior to Python 2.5) does not allow files to be larger than a certain size depending on the platform. This size is always < 2GB even on 64-bit systems.
The class is called memmap and is available in the NumPy namespace. The new method of the class has been re-written to have the following syntax:
145 new (cls, filename, dtype=uint8, mode=’r+’, offset=0, shape=None, order=0)
Memory-mapped-file arrays have one additional method (besides those they inheritfrom the ndarray): self.sync() which must be called manually by the user to ensurethat any changes to the array actually get written to disk.
Example:
146(broadcasting) element-by-element basis. These operations are not available onthe standard ndarray of character type. In addition, the chararray has all of thestandard string (and unicode) methods, executing them on an element-by-elementbasis. Perhaps the easiest way to create a chararray is to use self.view(chararray)where self is an ndarray of string or unicode data-type. However, a chararray canalso be created using the numpy.chararray. new method.
Create a new character array of string or unicode type and itemsize characters. Create the array using buffer (with offset and strides) if it is not None. If buffer is None, then construct a new array with strides in Fortran order if len(shape) >=2 and order is ’Fortran’ (otherwise the strides will be in ’C’ order).
Create a chararray from the nested sequence obj. If obj is an ndarray of data- type unicode or string, then its data is wrapped by the chararray object and converted to the desired type (string or unicode).
Another difference with the standard ndarray of string data-type is that the charar-ray inherits the feature introduced by Numarray that white-space at the end of anyelement in the array will be ignored on item retrieval and comparison operations.
147 >>> desc = dtype({’names’: [’name’, ’age’, ’weight’], ’formats’: [’S30’ >>> a = array([(’Bill’,31,260.0),(’Fred’, 15, 145.0)],dtype=desc) >>> print a[0] (’Bill’, 31, 260.0) >>> print a[’name’] [’Bill’ ’Fred’] >>> print a[’age’] [31 15] >>> print a[’weight’] [ 260. 145.] >>> print a[0][’name’], a[0][’age’], a[0][’weight’] Bill 31 260.0 >>> print len(a[0]) 3
This example shows how a general array can be assigned named fields and howthese fields can be accessed. In this case the a[0] object is an array-scalar of typevoid. The void array-scalars are unique in that they contain references to (ratherthan copies of) the underlying data whenever fields are defined. Therefore, therecord data can be modified in place:
The recarray subclass and its accompanying record item add the ability to accessnamed fields through attribute lookup. A quick way to get a record array is to usethe view method of the ndarray.
>>> r = a.view(recarray) >>> print r.name [’George’ ’Fred’]
148formats= is required as the data-type can be inferred from the object passed in asthe first argument. The five argument method for specifying a data-type constructs a data-typeobject internally. The comma-separated formats string is used to specify the fields.The names (and optional titles) of the fields can be specified by a comma-separatedstring of names (or titles). The aligned flag determines whether the fields are packed(False) or padded (True) according to the platform compiler rules. The byteorderargument allows specification of the byte-order for all of the fields at once (theycan also be specified individually in the formats string). The default byte-order isnative to the platform.
Create a record array from a (flat) list of ndarrays. The data from the arrays will be copied into the fields. If formats is None and dtype is None, then the formats will be determined from the arrays. The names and titles arguments can be a list, tuple or a (comma-separated) string specifying the names and/or titles to use for the fields. If aligned is True, then the structure will be padded according to the rules of the compiler that NumPy was compiled with.
149 >>> x1 = array([21,32,14]) >>> x2 = array([’my’,’first’,’name’]) >>> x3 = array([3.1, 4.5, 6.2]) >>> r = rec.fromarrays([x1,x2,x3], names=’id, word, number’) >>> print r[1] (32, ’first’, 4.5) >>> r.number array([ 3.1, 4.5, 6.2]) >>> r.word chararray([’my’, ’first’, ’name’], dtype=’|S5’)
Construct a record array from a (nested) sequence of tuples that define the records. If formats are not given, they are deduced from the records, but this is slower. The field names and field titles can be specified. If aligned is non-zero, then the record array is padded so that fields are aligned as the platform compiler would do if the fields represented a C-struct.
Construct a record array using the provided datastring (at the given offset) as the memory. The record array will be read-only. The byteorder argument may be used to specify the byteorder of all of the fields at the same time. A True aligned argument causes padding fields to be added as needed so that
150 the fields are aligned on boundaries determined by the compiler. The shape of the returned array can also be specified.
Construct a record array from the (binary) data in the given file object, fd. This object may be an open file or a string to indicate a file to read from. If offset is non-zero, then data is read from the file at offset bytes from the current position.
The following classes are also available in the numpy.core (and therefore the numpy)namespace
record A subclass of the void array scalar type that allows field access using at- tributes.
recarray A subclass of the ndarray that allows field access using attributes
format parser A class useful for creating a data-type descriptor from formats, names, titles, and aligned arguments. This is used by several of the record array constructors for consistency in behavior.
151Dubois (the original author of MA for Numeric) adapted and modified the codefor use by NumPy. Alexander Belopolsky (Sasha) added additional functions andimprovements Masked arrays are created using the masked array creation function.
Masked arrays have the same methods and attributes as arrays with the additionof the mask attribute as well as the “hidden” attributes . data and . mask.
152 for val in myiter: ... some code involving val ...
for i in arr.shape[0]: val = arr[i]
This default iterator selects a sub-array of dimension N − 1 from the array. Thiscan be a useful construct for defining recursive algorithms. To loop over the entirearray requires N for-loops.
>>> a = arange(24).reshape(3,2,4)+10 >>> for val in a: ... print ’item:’, val item: [[10 11 12 13] [14 15 16 17]] item: [[18 19 20 21] [22 23 24 25]] item: [[26 27 28 29] [30 31 32 33]]
153 >>> for i, val in enumerate(a.flat): ... if i%5 == 0: print i, val 0 10 5 15 10 20 15 25 20 30
Here, I’ve used the built-in enumerate iterator to return the iterator index aswell as the value.
154nd the number of dimensions in the broadcasted result.shape the shape of the broadcasted result.size the total size of the broadcasted result.index the current (flat) index into the broadcasted arrayiters a tuple of (broadcasted) NumPy.flatiter objects, one for each array.reset () Reset the multiter object to the beginning.next () Get the next tuple of objects from the (broadcasted) arrays
155Chapter 9
Universal Functions
—Andy Rooney
—Adam Osborne
9.1 DescriptionUniversal functions are wrappers that provide a common interface to mathematicalfunctions that operate on scalars, and can be made to operate on arrays in anelement-by-element fashion. All universal functions (ufuncs) wrap some corefunction that takes ni (scalar) inputs and produces no (scalar) outputs. Typically,this core function is implemented in compiled code but a Python function can alsobe wrapped into a universal function using the basic method frompyfunc in theumath module.
156 works using Object arrays for both input and output. The vectorize class makes use of frompyfunc internally. You can view the source code using numpy.source(numpy.vectorize).
9.1.1 BroadcastingEach universal function takes array inputs and produces array outputs by perform-ing the core function element-wise on the inputs. The standard broadcasting rulesare applied so that inputs without exactly the same shapes can still be usefullyoperated on. Broadcasting can be understood by four rules:
1. All input arrays with ndim smaller than the input array of largest ndim have 1’s pre-pended to their shapes.
2. The size in each dimension of the output shape is the maximum of all the input shapes in that dimension.
4. If an input has a dimension size of 1 in its shape, the first data entry in that dimension will be used for all calculations along that dimension. In other words, the stepping machinery of the ufunc will simply not step along that dimension when otherwise needed (the stride will be 0 for that dimension).
While perhaps a bit difficult to explain, broadcasting can be quite useful and be-comes second nature rather quickly. Broadcasting is used throughout NumPy todecide how to handle non equally-shaped arrays.
157the class also has an array wrap method, the returned ndarray result will bepassed to that method just before passing control back to the caller.
setbufsize (size)
Set the buffer size to the given number of elements in the current thread. Return the old buffer size (so that it can be reset later if desired).
This will set the current thread so that errors can be handled if desired. If one of the errors is set to ’call’, then a function must be provided using the seterrcall() routine. If any of the arguments are None, then that error mask will be unchanged. The return value of this function is a dictionary with the old error conditions. Thus, you can restore the old condition after you are finished with your function by calling seterr(**old). If all is set, then all errors will be set to the specified value.
158seterrcall (callable)
This sets the function to call when an error is triggered for an error condition configured with the “call” handler. This function should take two arguments: a string showing the type of error that triggered the call, and an integer showing the state of the floating point status registers. Any return value of the call function will be ignored, but errors can be raised by the function. Only one error function handler can be specified for all the errors. The status argument shows which errors were raised. The return value of this routine is the old callable. The argument passed in to this function must be any callable object with the right signature or None.
NOTE FPE DIVIDEBYZERO, FPE OVERFLOW, FPE UNDERFLOW, and FPE INVALID, are all defined con- stants in NumPy. The status flag returned for a ’call’ error handling type shows which errors were raised by adding these constants together.
159 be useful as an optimization for calculations requiring lots of ufuncs on small arrays in a loop.
9.2 AttributesThere are some informational attributes that universal functions possess. None ofthe attributes can be set.
doc
A docstring for each ufunc. The first part of the docstring is dynamically gener- ated from the number of outputs, the name, and the number of inputs. The second part of the doc string is provided at creation time and stored with the ufunc.
name
nin
nout
nargs
ntypes
The total number of different types for which this ufunc is defined.
types
A list of length ntypes containing strings showing the types for which this ufunc is defined. Other types may still be used as inputs (and as output arrays), they will just need casting. For inputs, standard casting rules will be used to determine which of the supplied internal functions that will be used (and therefore the default type of the output). Results will always be force-cast to any array provided to hold the output.
160 Table 9.1: Universal function (ufunc) attributes.
Name Description doc Dynamic docstring. name Name of ufunc nin Number of input arguments nout Number of output arguments nargs Total number of arguments ntypes Number of defined inner loops. types List showing types for which inner loop is defined. identity Identity for this ufunc.
identity
A 1, 0, or None to show the identity for this universal function. This identity is used for reduction on zero-sized arrays (arrays with a shape that includes a 0).
161question of when a data type can be cast “safely” to another data type. Theanswer to this question can be determined in Python with a function call: can cast(fromtype, totype). Figure shows the results of this call for my 32-bit system onthe 21 internally supported types. You can generate this table for your system withcode shown in that Figure. You should note that, while included in the table for completeness, the ’S’, ’U’,and ’V’ types cannot be operated on by ufuncs. Also, note that on a 64-bit systemthe integer types may have different sizes resulting in a slightly altered table. Mixed scalar-array operations use a different set of casting rules that ensure thata scalar cannot upcast an array unless the scalar is of a fundamentally different kindof data (i.e. under a different hierachy in the data type hierarchy) then the array.This rule enables you to use scalar constants in your code (which as Python typesare interpreted accordingly in ufuncs) without worrying about whether the precisionof the scalar constant will cause upcasting on your large (small precision) array.
9.4 MethodsAll ufuncs have 4 methods. However, these methods only make sense on ufuncs thattake two input arguments and return one output argument. Attempting to call thesemethods on other ufuncs will cause a ValueError. The reduce-like methods alltake an axis keyword and a dtype keyword, and the arrays must all have dimension>= 1. The axis keyword specifies which axis of the array the reduction will takeplace over and may be negative, but must be an integer. The dtype keyword allowsyou to manage a very common problem that arises when naively using <op>.reduce.Sometimes you may have an array of a certain data type and wish to add up allof its elements, but the result does not fit into the data type of the array. Thiscommonly happens if you have an array of single-byte integers. The dtype keywordallows you to alter the data type that the reduction takes place over (and thereforethe type of the output). Thus, you can ensure that the output is a data type with
162>>> def print table(ntypes):... print ’X’,... for char in ntypes: print char,... print... for row in ntypes:... print row,... for col in ntypes:... print int(can cast(row, col)),... print>>> print table(typecodes[’All’])X ? b h i l q p B H I L Q P f d g F D G S U V O? 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1b 0 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1h 0 0 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1i 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1l 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1q 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1p 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1B 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1H 0 0 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1I 0 0 0 0 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 1 1 1 1L 0 0 0 0 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 1 1 1 1Q 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 1 1 1 1 1P 0 0 0 0 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 1 1 1 1f 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1d 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1g 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 1 1 1F 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1D 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1G 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1U 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1V 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1O 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
Figure 9.1: Code segment showing the can cast safely table for a 32-bit system.
163large-enough precision to handle your output. The responsibility of altering thereduce type is mostly up to you. There is one exception: if no dtype is given for areduction on the “add” or “multiply” operations, then if the input type is an integer(or boolean) data-type and smaller than the size of the int data type, it will beinternally upcast to the int (or uint) data type.
WARNING A reduce-like operation on an array with a data type that has range “too small” to handle the result will silently wrap. You should use dtype to increase the data type over which reduction takes place.
9.4.1 Reduce<op>.reduce (array=, axis=0, dtype=None)
For each one-dimensional sequence along the axis dimension of the array, return a single number resulting from recursively applying the operation to succesive elements along that dimension. If the input array has N dimensions, then the returned array has N − 1 dimensions. This produces the equivalent of the following Python code :
Studying the above code can also help you gain an appreciation for how to do generic indexing in Python using index exp. For example, if <op> is add, then <op>.reduce produces a summation along the given axis. If <op> is prod, then a repeated multiply is performed.
9.4.2 Accumulate<op>.accumulate (array=, axis=0, dtype=None)
This method is similar to reduce, except it returns an array of the same shape as the input, and keeps intermediate calculations. The operation is still per- formed along the access. This method underlies the operations of the cumsum
164 and cumprod methods of arrays. The following Python code implements an equivalent of the accumulate method.
9.4.3 Reduceat<op>.reduceat (array=, indices=, axis=0, dtype=None)
165 ... Ikp1 = indices[k+1] ... except IndexError: ... Ikp1 = N ... if (Ikp1 > Ik): ... i2[axis] = index exp[Ik:Ikp1] ... result[i1] = <op>.reduce(array[i2],axis=axis,dtype=dtype ... else: ... result[i1] = array[Ik].astype(dtype)
The returned array has as many dimensions as the input array, and is the same shape except for the axis dimension which has shape equal to the length of indices (the number of reduce operations that were performed). If you ever have a need to compute multiple reductions over portions of an array, then (if you can get your mind around what it is doing) reduceat may be just what you were looking for.
9.4.4 Outer<op>.outer (a, b)
Among many other uses, arithmetic tables can be conveniently built using outer:
>>> multiply.outer([1,7,9,12],arange(5,12)) array([[ 5, 6, 7, 8, 9, 10, 11], [ 35, 42, 49, 56, 63, 70, 77], [ 45, 54, 63, 72, 81, 90, 99], [ 60, 72, 84, 96, 108, 120, 132]])
1669.5 Available ufuncsThere are currently more than 60 universal functions defined on one or more types,covering a wide variety of operations. Some of these ufuncs are called automaticallyon arrays when the relevant infix notation is used (i.e. add(a,b) is called internallywhen a + b is written and a or b is an ndarray). Nonetheless, you may still wantto use the ufunc call in order to use the optional output argument(s) to place theoutput(s) in an object (or in objects) of your choice. Recall that each ufunc operates element-by-element. Therefore, each ufunc willbe described as if acting on a set of scalar inputs to return a set of scalar outputs.
NOTE The ufunc still returns its output(s) even if you use the optional output argument(s).
This version of division always returns an inexact number so that integer division returns floating point. Called with future .division is active to implement x1/x2 for arrays.
167 This version of division always results in truncation of an fractional part remain- ing. Called to implement x1//x2 for arrays.
negative (x [, y])
absolute (x [, y])
Round x to the nearest integer. Rounds half-way cases to the nearest even integer.
sign (x [, y])
Sets y according to 1 x :> 0, sign (x) = 0 x = 0, −1 x < 0.
conj (x [, y])
conjugate (x [, y])
168exp (x [, y])
y = ex .
log (x [, y])
y = log (1 + x) but accurate for small |x| . Returns the number y such that ey −1 = x
log10 (x [, y])
sqrt (x [, y]) √ y = x.
square (x [,y])
y =x∗x
reciprocal (x [, y])
y = 1/x
i TIP The optional output arguments can be used to help you save mem- ory.
1699.5.2 Trigonometric functionsAll trigonometric functions use radians when an angle is called for. The ratio ofdegrees to radians is 180◦ /π.
sin (x [, y])
cos (x [, y])
tan (x [, y])
The standard trignometric functions. y = sin (x) , y = cos (x) , and y = tan (x) .
arcsin (x [, y])
arccos (x [, y])
arctan (x [, y])
The inverse trigonometric functions: y = sin−1 (x) , y = cos−1 (x), y = tan−1 (x) . These return the value of y (in radians) such that sin (y) = x with y ∈ − π2 , π2 ; cos (y) = x with y ∈ [0, π]; and tan (y) = x with y ∈ − π2 , π2 , respectively.
x1 x2 y = arctan2 (x1 , x2 ) 0 1 0 π 1 0 2 0 -1 π -1 0 − π2
sinh (x [, y]) 1 Computes y = sinh (x) which is defined as 2 (ex − e−x ) .
170cosh (x [, y]) 1 Computes y = cosh (x) which is defined as 2 (ex + e−x ) .
tanh (x [, y])
arcsinh (x [, y])
arccosh (x [, y])
arctanh (x [, y])
These compute the inverse hyperpolic functions. y = arcf unc (x) is the (principal) value of y such that f unc (y) = x.
Each bit in y is the result of a bit-wise ’and’ operation on the corresponding bits in x1 and x2 . Called to implement x1&x2 for arrays.
Each bit in y is the result of a bit-wise ’or’ operation on the corresponding bits in x1 and x2 . Called to implement x1|x2 for arrays.
Each bit in y is the result of a bit-wise ’xor’ operation on the corresponding bits in x1 and x2 . An xor operation sets the output to 1 if one and only one of the input bits is 1. Called to implement x1ˆx2 for arrays. Using the bitwise xor operation and the optional output argument you can swap the values of two integer arrays of equivalent types without using temporary arrays.
171 >>> a=arange(10) >>> b=arange(10,20) >>> bitwise xor(a,b,a); bitwise xor(a,b,b); >>> bitwise xor(a,b,a) array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) >>> print a; print b [10 11 12 13 14 15 16 17 18 19] [0 1 2 3 4 5 6 7 8 9]
Shifts the bits of x1 to the left by x2 . Called to implement x1<<x2 for arrays. Provided there is no overflow, the result is equal to y = x1 2x2 .
Shifts the bits of x1 to the right by x2 . Called to implement x1>>x2 for arrays. Absent overflow, the result is equal to y = x1 2−x2 .
172 The fact that these functions return Boolean arrays make them very useful in combination with advanced array indexing. Thus, for example, arr[arr>10] = 10 clips large values to 10. Used in conjunction with bitwise operators quite complicated expressions are possible. For example, arr[˜((arr<10)&(arr>5))] = 0 clips all values outside of the range (5, 10) to 0.
WARNING Do not use the Python keywords and and or to combine logical array expressions. These keywords will test the truth value of the entire array (not element-by-element as you might expect). Use the bitwise operators: & and | instead.
The output is the truth value of x1 and x2 . Numbers equal to 0 are considered False. Nonzero numbers are True.
The output, y, is the truth value of x1 xor x2 , which is the same as (x1 and not x2 ) or (not x1 and x2 )..
173 >>> maximum([1,0,5,10],[3,2,4,5]) array([ 3, 2, 5, 10]) >>> max([1,0,5,10],[3,2,4,5]) [3, 2, 4, 5]
i TIP The Python function max() will find the maximum over a one- dimensional array, but it will do so using a slower sequence inter- face. The reduce method of the maximum ufunc is much faster. Also, the max() method will not give answers you might expect for arrays with greater than one dimension. The reduce method of minimum also allows you to compute a total minimum over an array.
>>> minimum([1,0,5,10],[3,2,4,5]) array([1, 0, 4, 5]) >>> min([1,0,5,10],[3,2,4,5]) [1, 0, 5, 10]
WARNING the behavior of maximum(a,b) is).
174isreal (x)
iscomplex (x)
isfinite (x)
isinf (x)
True if x is ±∞.
isnan (x)
signbit (x)
True where the sign bit of the floating point number is set. This should correspond to x > 0 when x is a finite number. When, x is NaN or infinite, then this tests the actual signbit.
modf (x [, y1 , y2 ])
Breaks up the floating point value x into its fractional, y1 , and integral, y2 , parts. Thus, x = y1 + y2 with floor(y2)==y2.
frexp (x [, y, n])
Breaks up the floating point value x into a normalized fraction, y and an exponent, n which corresponds to how the value is represented in the computer. The results are such that x = y2n . Effectively, the inverse of ldexp.
175 Computes the remainder of dividing x1 by x2 . The result, y, is x1 − nx2 where n is the quotient (rounded towards zero to an integer) of x1 /x2 .
floor (x [,y ])
ceil (x [,y ])
176Chapter 10
Basic Modules
—Aristotle
inv (A)
177 Table 10.1: Functions in numpy.dual (both in NumPy and SciPy)
Family Functions Fourier Transforms fft, ifft, fft2, ifft2, fftn, ifftn norm, det, inv, pinv, solve, eig, eigh, eigvals, Linear Algebra eigvalsh, lstsq, cholesky, svd Special Functions i0
Return the (matrix) inverse of the 2-d array A. The result, X, is such that dot(A,X) is equal to eye(*A.shape) (to within machine precision).
solve (A,b)
Find the solution to the linear equation Ax = b, where A is a 2-d array and b is a 1-d or 2-d array.
Find the tensor inverse of A, defined to be the tensor such that tensordot (Ainv, A) is an identity operator.
cholesky (A)
eigvals (A)
178eig (A)
Return all solutions (λ, x) to the equation Ax = λx. The first element of the return tuple contains all the eigenvalues. The second element of the return tuple contains the eigenvectors in the columns (x[:,i] is the ith eigenvector).
eigvalsh (U)
eigh (U)
These functions are identical to eigvals and eig except they only work with Her- mitian matrices where UH = U (only the lower-triangular part of the array is used).
svd (A)
Compute the singular value decomposition of the 2-d array A. Every m×n matrix can be decomposed into a pair of unitary matrices, U = UH (m × m) and V = VH (n × n) and an m × n “diagonal” matrix Σ, such that A = UΣVH . The only non-zero portion of Σ is the upper r × r block where r = min (m, n). The svd function returns three arrays as a tuple: (U, σ, VH ). The singular values are returned in the 1-d array σ. If needed, the array Σ can be found (if really needed) using the command diag(σ) which creates the r × r diagonal block and then inserting this into a zeros matrix:
>>> A = random.rand(3,5) >>> from numpy.dual import svd; U,s,Vh = svd(A) >>> r=min(*A.shape); Sig = zeros like(A); >>> Sig[:r,:r] = diag(s); print Sig [[ 2.1634 0. 0. 0. 0. ] [ 0. 0.7076 0. 0. 0. ] [ 0. 0. 0.2098 0. 0. ]]
Return the generalized, pseudo inverse, of A. For invertible matrices, this is the same as the inverse.
det (A)
179 Return the determinant of the array. The determinant of an array is the product of its singular values.
Return (x, resids, rank, s) where x minimizes resids=kAx − bk2 . The output rank is the rank of A and s is the singular values of a in descending order. Singular values less than s[0]*rcond are treated as 0. If the rank of A is less than the number of columns of A or greater than the number of rows, resids will be returned as an empty array.
Return, X, the N-point Discrete Fourier Transform (DFT) of x along the given axis using a fast algorithm. If N is larger than x.shape[axis], then x will be zero-padded. If N is smaller than x.shape[axis], then the first N items will be used. The result is computed for k = 0 . . . n − 1 from the formula: n−1 X 2πkm X [k] = x[m] exp −j . m=0 n
i TIP The fft returns values for k = 0 . . . N − 1. Because X [N − k] = X[−k] in the FFT formula, larger values of k correspond also to negative frequencies.
Return the inverse of the fft so that (ifft(fft(a)) == a within numerical precision. The order of frequencies must be the same as returned by fft. The result is computed (using a fast algorithm) for m = 0 . . . n − 1 from the formula: n−1 X 2πkm x [m] = X [k] exp j . n k=0
180 Sometimes having the “negative” frequencies at the end of the output returnedby fft can be a little confusing. There are two ways to deal with this confusion. Inmy opinion, the most useful way is to get a collection of DFT sample frequencies anduse them to keep track of where each frequency is. The function fftfreq providesthese sample frequencies. Making an x-y plot, where the sample frequencies arealong the “x”-axis and the result of the DFT is along the “y”-axis provides a usefulvisualization with the zero-frequency at the center of the plot. The advantage ofthis approach is that your data is still in proper order for using the ifft function.Some people, however, prefer to simply swap one-half of the output with the other.This is exactly what the function fftshift does. Of course, now the data is notin the proper order for the ifft function, but to each his own. The reason that the “negative” frequencies are in the upper part of the returnsignal was given in the description of the DFT. The reason is that the output ofthe DFT is just one period of a periodic function (with period n). The traditionaloutput of the FFT algorithm is to provide the portion of the function from fromk = 0 to k = n − 1.
Reverse the effect of the fftshift operation. Thus, it takes zero-centered data and shifts it into the correct order for the ifft operation.
Provide the DFT sample frequencies. The returned float array contains the fre- quency bins in the order returned from the fft function. If given, d represents the sample-spacing. The units on the frequency bins are cycles / unit. For example, the following example computes the output frequencies (in Hz) of the fft of 256 samples of a voice signal sampled at 20000Hz.
181fft2 (x, s=None, axes=(-2,-1))
Return the two-dimensional fft of the array x for each 2-d array formed by axes. The 2-d fft is computed as
s[0]−1 s[1]−1 X X 2πk0 m0 2πk1 m1 X [k0 , k1 ] = x [m0 , m1 ] exp −j exp −j m0 =0 m1 =0 s[0] s [1]
and can be realized by repeated application of the 1-d fft (first over the axes[0] and then over axes[1]). In other-words fft2(x,s,axes) is equivalent to fft(fft(x, s[0], axes[0]), s[1], axes[1]). The 2-d fft is returned for k0 = 0 . . . s[0] − 1 and k1 = 0 . . . s[1] − 1. Symmetry (X [s[0] − k0 , s[1] − k1 ] = X[−k0 , −k1 ]) ensures that higher values of ki correspond to negative frequencies.
Return the N -dimensional fft of x. If s is not given, then if axes is given, then N =len(axes), otherwise N =x.ndim. If s is given, then N =len(s). Results are computed using a similar formula as for the 1- and 2-d FFT with N summations.
The Discrete Fourier transform returns complex-valued data (even for real-valuedinput). If the data was originally real-valued, then much of the output of the fullDFT is redundant. Notice that if x [m] is real, then
n−1 X 2π (n − k) m X [n − k] = x[m] exp −j m=0 n " n−1 #∗ X 2πkm = x [m] exp −j m=0 n = X ∗ [k] ,
182where a∗ denotes the complex-conjugate of a. So, the upper half of the fft output(the negative frequencies) is determined exactly by the lower half of the output whenthe input is purely real. This kind of symmetry is called Hermitian symmetry.The real-valued Fourier transforms described next take advantage of Hermitiansymmetry to compute only the unique outputs more quickly. The symmetry in higher dimensions is always about the origin. If N is thenumber of dimensions, then:
X[n1 − k1 , n2 − k2 , . . . nN − kN ] = X ∗ [k1 , k2 , . . . , kN ] .
Thus, the data-savings remains constant at about 1/2 for higher dimensions as well.
Compute the first n//2+1 points of the n-point discrete Fourier transform of the real valued data along the given axis. The returned array will be just the first half of the fft, corresponding to positive frequencies: rfft(x) == fft(x)[:n//2+1]
Compute the inverse n-point discrete Fourier transform along the given axis using the first n//2+1 points. To within numerical precision, irfft(rfft(x))==x.
Compute only the first half-plane of the two-dimensional discrete Fourier trans- form corresponding to unique values. s[0] and s[1]-point DFTs will be com- puted along axes[0] and axes[1] dimensions, respectively. Requires a real array. If s is None it defaults to the shape of x. The real fft will be computed along the last axis specified in axes while a full fft will be computed in the other dimension.
Compute the inverse of the 2-d DFT using only the first quadrant. Returns a real array such that to within numerical precision irfft2(rfft2(x))==x.
Compute only the unique part of the N -dimensional DFT from a real-valued array. If s is None it defaults to the shape of x. If axes is not given it defaults to
183 all the axes (-n,. . ., -1). The length of axes provides the dimensionality of the DFT. The unique part of the real N -dimensional DFT is obtained by slicing the full fft along the last axis specified and taking n//2+1 slices. rfftn(x) == fft(x)[sliceobj] where sliceobj[axes[-1]] = slice(None,s[-1]//2+1,None).
Compute the inverse DFT from the unique portions of the N-dimensional DFT provided by rfftn.
Occasionally, the situation may arise where you have complex-valued data withHermitian symmetry (or real-valued symmetric data). This ensures that the Fouriertransform will be real. The two functions below can calculate it without wastingextra space for the zero-valued imaginary entries of the Discrete Fourier transform,or the entire signal.
Calculate the n-point real-valued Fourier transform from (the first half of Hermitian-symmetric data, x.
Return (the first half-of) Hermitian-symmetric data from the real-valued Fourier transform, X.
184 Each of the discrete and continuous random number generators take a size key-word. If this is None (default), then the size is determined from the additionalinputs (using ufunc-like broadcasting). If no additional inputs are needed, or ifthese additional inputs are scalars, then a single number is generated from the se-lected distribution. If size is an integer, then a 1-d array of that size is generatedfilled with random numbers from the selected distribution. Finally, if size is a tuple,then an array of that shape is returned filled with random numbers. Many distributions take additional inputs as parameters. These additional in-puts must be broadcastable to each other (and to the size parameter if it is notNone). The broadcasting behavior of the additional inputs is ufunc-like.
It will be useful to define the discrete indicator function, IS (k) , where S is a setof integers (often represented by an interval). IS (k) = 1 if k ∈ S, otherwise IS (k) =0. This convenient notation isolates the relevance of a particular functional form toa certain range. Also, the formulas below make use of the following definition: ! n n! = k k! (n − k)!
where k! = k · (k − 1) · · · · · 2 · 1.
185 This random number models the number of (independent) attempts required to obtain a success where the probability of success on each attempt is p. k−1 pm (k; p) = (1 − p) p I[1,∞) (k) .
Imagine a probability theorists favorite urn filled with ng “good” objects and nb “bad” objects. In other words there are two types of objects in a jar. The hypergeometric random number models how many “good” objects will be present when N items are taken out of the urn without replacement. ! ! ng nb k N −k p (k; ng , nb , N ) = ! I[N −nb ,min(n,N )] (k) . ng + nb N
A random number whose pmf with terms proportional to the Taylor series expan- sion of log (1 − p). It has been used in biological studies to model the species abundance distribution.
pk pm (k; p) = − I[1,∞) (k) . k log (1 − p)
This generator produces random vectors of length N where N = len (pvals). The shape of the returned array is always the shape indicated by size + (N,). The multinomial distribution is a generalization of the binomial distribution. This time, n trials of an experiment are independently repeated but each trial PN results in N possible integers k1 , k2 , . . . , kN with i=1 ki = n.
186 Models the number of extra independent trials (beyond n) required to accumulate a total of n successes where the probability of success on each trial is p. Equivalently, this random number models the number of failures encountered while accumulating n successes during independent trials of the experiment that succeeds with probability, p. ! k+n−1 k pm (k; n, p) = pn (1 − p) I[0,∞) (k) . n−1
λk p (k; λ) = e−λ I[0,∞) (k) . k!zipf (a, size=None)
The probability mass function of this random number (also called the zeta distri- bution) is 1 pm (k; a) = I[1,∞) (k) , ζ (a) k a where ∞ X 1 ζ (a) = a n=1 n
is the Riemann zeta function. Zipf distributions have been shown to char- acterize use of words in a natural language (like English), the popularity of library books, and even the use of the web. The Zipf distribution describes collections that have a few items whose probability of selection is very high, a medium number of items whose probability of selection is medium, and a huge number of items whose probability of selection is very low.
187is an uncountable number of possibilities for the random number1 , a continuousdistribution is modeled by a probability density function, f (x; ·) . To obtain theprobability that the random number generated by X (·) is in a certain interval, weintegrate this density function: Z b f (x) dx = Probability {X (·) ≤ b} . −∞
Thus, from the standard from provided, the pdf of the actual random numbersgenerated by fixing the location and scale parameters can be quickly found. In this section, the indicator function IA (x) will be used where A is a set definedover all the real numbers. For clarity, ( 1 x ∈ A, IA (x) = 0 x 6∈ A.
there are only a finite set of numbers that can be represented by a computer. However, forcontinuous random number generators, the resulting random numbers usually approximate thecontinuous distribution well enough to ignore the subtlety.
188 1 b−1 f (x; a, b) = xa−1 (1 − x) I(0,1) (x) . B (a, b)
1 x ν/2−1 f (x; ν) = ν e−x/2 I[0,∞) (x) . 2Γ 2 2
f (ν1 , ν2 , size=None) X1 /ν1 The distribution of X2 /ν2 where Xi is chi-squared with νi degrees of freedom.
ν /2 ν /2 ν2 2 ν1 1 xν1 /2−1 f (x; ν1 , ν2 ) = (ν1 +ν2 )/2 I[0,∞) (x) . ν1 ν2 (ν2 + ν1 x) B 2 , 2
The parameters, µ and σ are not the mean and variance of this distribution, butthe parameters of the underlying normal distribution. Random numbers from thisdistribution are generated as eσZ+µ where Z is a standard normal random number.
189logistic (loc=0.0, scale=1.0, size=None)
e−x f (x) = 2 I[0,∞) (x) [1 + e−x ]
Returns a vector of random numbers which are jointly drawn from a multivariate normal distribution. The last-dimension of the output array contains the sample vector, which is of length N = len (mean) . The covariance matrix must be N × N . If µ ≡ mean and C = cov, then the joint-pdf representing the returned random vector(s) is 1 1 T −1 f (x) = q exp − (x − µ) C (x − µ) . N 2 (2π) |C|
1 x (ν−2)/4 √ f (x; ν, λ) = e−(λ+x)/2 I(ν−2)/2 λx I(0,∞) (x) , 2 λ where Iν (z) (a real-number in the subscript, not an interval) is the modified Bessel Function of the first kind.
190 of the celebrated central limit theorem). The normal distribution is also the distribution of maximum entropy when the mean and variance alone are fixed. These two facts account for its name as well as the wide variety of situations that can be usefully modelled using the normal distribution. Because it is so widely used, the full pdf with the location (µ) and scale (σ) parameters is provided: " # 2 1 (x − µ) f (x) = √ exp − . σ 2π 2σ 2
Equally probably random integers in the range low ≤ x < high. If high is None, then the range is 0 ≤ x < low. Similar to random integers, but check the difference on the bounds.
191random integers (low, high=None, size=None)
Equally probably random integers in the range low ≤ x ≤ high. If high is None, then the range is 1 ≤ x ≤ low. Similar to randint, but check the difference on the bounds.
A standard exponetial random number with scale=1.0. The pdf was given under the description of random.exponential.
A standard gamma random number with scale=1.0. The pdf was given under the description of random.gamma.
192 the sample-size is small. The first parameter, ν, is the number of degrees of freedom of the distribution. ν+1 Γ 2 f (x; ν) √ ν+1 . ν x2 2 πνΓ 2 1+ ν
Returns random numbers that are equally probable over the range [low, high) .
A continuous distribution that is well suited for circular attributes such as angles, time of day, day of the year, etc. The mean direction is µ and concentration (or dispersion) parameter is κ. For small κ the distribution tends towards a uniform distribution over [−π, π] . For large κ, the distribution tends towards a normal distribution with mean µ and variance 1/κ.
eκ cos(x−µ) f (x) = I[−π,π] (x) . 2πI0 (κ)
This distribution is also called the inverse Gaussian distribution (and the Wald distribution considered as a special case when µ = λ). It can be generated 2 by noticing that if X is a wald random number then λ(X−µ) µ2 X is the square of a standard normal random number (i.e. it is chi-square with one degree of freedom). The pdf is r 2 λ − λ(x−µ) f (x) = e 2µ2 x . 2πx3
An extreme-value distribution:
19310.3.3 Miscellaneous utilitiesbytes (length)
get state ()
Return an object that holds the state of the random number generator (allows you to restart simulations where you left off).
Set the state of the random number generator. The argument should be the returned object of a previous get state command.
shuffle (sequence)
permutation (n)
Load a shared library named “name” (use the full name including any prefix but excluding the extension) located in the directory indicated by path and return a ctypes library object whose attributes are the functions in the library. If
194 ctypes is not available, this function will raise an ImportError. If there is an error loading the library, ctypes raises an OSError. The extension is appended to the library name (on a platform-dependent basis) unless the name includes the “.” character in which case name is assumed to be the “full-name” of the library.
Create a class object that can be used in the argtypes list of a ctypes function that will do basic type, number-of-dimensions, shape, and flags checking on input array objects. Setting an argtypes entry with the result of this function allows passing arrays directly to ctypes-wrapped functions. The returned class object will contain a from param method as required by ctypes. This from param method takes the array object, does data-type, number-of-dimensions, shape, and flags checking on the object and if all tests pass returns an object that ctypes can use as the data area of the array. Checking is not performed for any entries which are None in this class creation function.
195Chapter 11
Research is what I’m doing when I don’t know what I’m doing.
The most likely way for the world to be destroyed, most experts agree, is by accident. That’s where we come in; we’re computer profes- sionals. We cause accidents.
—Nathaniel Borenstein
There are two additional sub-packages distributed with NumPy that simplify theprocess of distributing and testing code based on NumPy. The numpy.distutils sub-package extends the standard distutils package to handle Fortran code along withproviding support for the auto-generated code in NumPy. The numpy.testing sub-package defines a few functions and classes for standardizing unit-tests in NumPy.These facilities can be used in your own packages that build on top of NumPy.
11.1 TestingIn this sub-package are two classes and some useful utilities for writing unit-tests
196NumpyTest the test manager for NumPy which was extracted originally from the SciPy code base. This test manager makes it easy to add unit- tests to a package simply by creating a tests sub-directory with files named test <module>.py. These test files should then define sub-classes of NumpyTestCase (or unittest.TestCase) named “test*”. These classes should then define functions named “test*” or “bench*” or “check*” that contain the actual unit-tests. The first keyword argument should specify the level above which this test should be run.
prepend local directory (+ reldir) to sys.path. The caller is responsible for re- moving this path using restore path().
prepend package directory to sys.path. This should be called from a test file.py that satisfies the tree structure: <somepath>/<somedir>/test file.py. The, the first existing path name from the list <somepath>/build/lib.<platform>- <version>, <somepath>/.. is pre-pended to sys.path. The caller is responsi- ble for removing this path using restore path().
restore path ()
Raise an assertion error if the two items are not equal. Automatically calls as- sert array equal if actual or desired is an ndarray.
Raise an assertion error if the two items are not equal within decimal places. Au- tomatically calls assert array almost equal if actual or desired is an ndarray.
197assert approx equal (actual, desired, significant=7, err msg=”, verbose=1)
Raise an assertion error if the two items are not equal to within the given signif- icant digits. Does not work on arrays.
Raise an error if the two arrays x and y are not equal at every element.
Raise an error if the two arrays x and y have different shapes or if x is not less than y at every element.
Raise an error if x and y are not equal to decimal places at every element.
jiffies ()
Return a number of 1/100ths of a second that this process has been scheduled in user mode. Implemented using time.time() unless on Linux where the special /proc directory filesystem is used.
memusage ()
Return the virtual memory size in bytes of the running python. If the operation is not supported on the platform, then return None. This works only on linux for now.
rand (*args)
Return an array of random numbers with the given shape using only the standard library random number generator.
Run the given string in the dictionary provided. Functional form for (exec astr in dict) that is useful for the failUnlessRaises method of unittest.TestCase class.
19811.2 NumPy DistutilsNumPy provides enhanced distutils functionality to make it easier to build andinstall sub-packages, auto-generate code, and extension modules that use Fortran-compiled libraries. To use features of numpy distutils use the setup com-mand from numpy.distutils.core. A useful Configuration class is also provided innumpy.distutils.misc util that can make it easier to construct keyword argumentsto pass to the setup function (by passing the dictionary obtained from the todict()method of the class). More information is available in the NumPy Distutils UsersGuide in <site-packages>/numpy/doc/DISTUTILS.txt..
self.todict () Return a dictionary compatible with the keyword arguments of dis- tutils setup function. Thus, this method may be used as setup(**config.todict()). self.get distribution () Return the distutils distribution object for self. self.get subpackage (subpackage name, subpackage path=None) Return a Configuration instance for the sub-package given. If subpack- age path is None then the path is assumed to be the local path plus the subpackage name. If a setup.py file is not found in the subpackage path, then a default configuration is used. self.add subpackage (subpackage name, subpackage path=None) Add a sub-package to the current Configuration instance. This is useful in a setup.py script for adding sub-packages to a package. The sub-package
199.self.add data files (*files) Add files to the list of data files to be included with the package.. An example may clarify: self.add data files(’foo.dat’, (’fun’, [’gun.dat’, ’nun/pun.dat’, ’/tmp/sun.dat’]), ’bar/cat.dat’, ’/full/path/to/can.dat’) will install these data files to: <package install directory>/ foo.dat fun/
200 gun.dat nun/ pun.dat sun.dat bar/ car.dat can.dat where <package install directory> is the package (or sub-package) directory such as ’/usr/lib/python2.4/site-packages/mypackage’ (’C:\\Python2.4\\Lib\\site-packages\\mypackage’) or ’/usr/lib/python2.4/site-packages/mypackage/mysubpackage’ (’C:\\Python2.4\\Lib\\site-packages\\mypackage\\mysubpackage’).
201 bar/ car.dat gun/ foo.dat car.dat
202 Add a library to the list of libraries. Allowed keyword arguments are de- pends, macros, include dirs, extra compiler args, and f2py options. The name is the name of the library to be built and sources is a list of sources (or source generating functions) to add to the library.self.add scripts (*files) Add the sequence of files to the beginning of the scripts list. Scripts will be installed under the <prefix>/bin/ directory.self.paths (*paths).self.get config cmd () Returns the numpy.distutils config command instance.self.get build temp dir () Return a path to a temporary directory where temporary files should be placed.self.have f77c () True if a Fortran 77 compiler is available (because a simple Fortran 77 code was able to be compiled successfully).self.have f90c () True if a Fortran 90 compiler is available (because a simple Fortran 90 code was able to be compiled successfully)self.get version () Return a version string of the current package or None if the version informa- tion could not be detected. This method scans files named version .py, <packagename> version.py, version.py, and svn version .py for string variables version, version , and <packagename> version, until a ver- sion number is found.self.make svn version py () Appends a data function to the data files list that will generate svn version .py file to the current package directory. This file will
203 be removed from the source directory when Python exits (so that it can be re-generated next time the package is built). This is intended for working with source directories that are in an SVN repository. self.make config py () Generate a package config .py file containing system information used during the building of the package. This file is installed to the package installation directory. self.get info (*names) Return information (from system info.get info) for all of the names in the argument list in a single dictionary.
Return the include directory where the numpy/libnumarray.h file is found. This should be added to the include dirs of any extension module that relies on the Numarray-compatible C-API.
Add the keyword arguments given as entries in the dictionary provided as the first argument. If the entry is already present, then assume it is a list and extend the list with the keyword value.
allpath (name)
Convert a ’/’ separated pathname to one using the platform’s path separator.
204 Converts a sequence of string arguments to a string joined by ’.’ (removing any empty strings).
A suitable function that can be used in a source list. This constructs a python file that contains system info information used during building the package. Gen- erally easier to use a Configuration instance and the config.make config py() method.
Tries to determine if the stdout terminal can be written to using ANSI colors. Returns 1 if it can be determined that ANSI colors are acceptable or 0 if not.
If terminal has colors() is true, then these commands return a string with the necessary codes prepended to display the given string argument in the spec- ified color on an ANSI terminal. If terminal has colors() is false, then these functions simply return the input argument.
cyg2win32 (path)
Convert a cygwin path beginning with /cygdrive to a standard win32 path name.
Return True if all items in the input list are string objects otherwise return False.
205 Return True if any of the source files listed in the input argument are Fortran files because its name matches against the compiled regular expression for- tran ext match.
Return True if any of the source files listed in the input argument are C++ files because its name matches against the compiled regular expression cxx ext match.
From the provided list of sources, return four lists of filenames containing C, C++, Fortran, and Fortran 90 module sources respectively. The com- piled regular expressions used in this search (which are also available in the misc util module) are cxx ext match, fortran ext match, f90 ext match, and f90 module name match.
Return True if the provided directory is the local current working directory.
Get sources and any include files in the same directory from an Extension instance.
For the given string representing a particular resource, return a dictionary that is compatible with the distutils.setup keyword arguments. If this is an empty dictionary, then the requested resource is not available. Some of the names that can be checked are ’lapack opt’, ’blas opt’, ’fft opt’, ’fftw’, ’fftw3’, ’fftw2’, ’djbfft’, ’numpy’, ’numarray’, ’boost python’, ’agg2’, ’wx’, ’gdk’, ’xft’, ’freetype2’.
206system info.get standard file (filename)
Return a list of length 0 to 3 containing the full-path filenames for the filename provided. The filename is searched for in three places in the following order 1) the system-wide location which is the directory that the system info file is located in; 2) the directory specified by the environment variable HOME; and 3) the current local directory.
cpuinfo.cpu an instance of a cpuinfo class that defines methods for checking var- ious aspects of the cpu. The info attribute is a list of length (# of CPUs). Each entry is a dictionary providing technical information about that CPU.
Set the distutils logging threshold and return the previously stored value. The level is an integer that corresponds to distutils.log thresholds: -1 <–> ER- ROR, 0 <–> WARN, 1 <–> INFO, and 2 <–> DEBUG.
exec command
20711.3 Conversion of .src filesNumPy distutils supports automatic conversion of source files named <some-file>.src. This facility can be used to maintain very similar code blocks requiringonly simple changes between blocks. During the build phase of setup, if a tem-plate file named <somefile>.src is encountered, a new file named <somefile> isconstructed from the template and placed in the build directory to be used instead.Two forms of template conversion are supported. The first form occurs for filesnamed named <file>.ext.src where ext is a recognized Fortran extension (f, f90,f95, f77, for, ftn, pyf). The second form is used for all other cases.
A named repeat rule is useful when the same set of repeats must be used severaltimes in a block. It is specified using <rule1=item1, item2, item3,..., itemN>, whereN is the number of times the block should be repeated. On each repeat of the block,the entire expression, ’<...>’ will be replaced first with item1, and then with item2,and so forth until N repeats are accomplished. Once a named repeat specificationhas been introduced, the same repeat rule may be used in the current block byreferring only to the name (i.e. <rule1>.
A short repeat rule looks like <item1, item2, item3, ..., itemN>. The rule specifiesthat the entire expression, ’<...>’ should be replaced first with item1, and thenwith item2, and so forth until N repeats are accomplished.
20811.3.1.3 Pre-defined names
• <prefix=s,d,c,z>
• < c=s,d,c,z>
3. In specifying the repeat rule for a named variable, item*N is short-hand for item, item, ..., item repeated N times. In addition, parenthesis in combi- nation with *N can be used for grouping several items that should be re- peated.@.
2096. “/**end repeat**/” on a line by itself marks the previous line as the last line of the block to be repeated.
210Part II
C-API
211Chapter 12
NumPy provides a C-API to enable users to extend the system and get accessto the array object for use in other routines. The best way to truly understandthe C-API is to read the source code. If you are unfamiliar with (C) source code,however, this can be a daunting experience at first. Be assured that the taskbecomes easier with practice, and you may be surprised at how simple the C-codecan be to understand. Even if you don’t think you can write C-code from scratch,it is much easier to understand and modify already-written source code then createit de novo. Python extensions are especially straightforward to understand because they allhave a very similar structure. Admittedly, NumPy is not a trivial extension toPython, and may take a little more snooping to grasp. This is especially true be-cause of the code-generation techniques, which simplify maintenance of very similarcode, but can make the code a little less readable to beginners. Still, with a littlepersistence, the code can be opened to your understanding. It is my hope, that
212this guide to the C-API can assist in the process of becoming familiar with thecompiled-level work that can be done with NumPy in order to squeeze that last bitof necessary speed out of your code. Several new types are defined in the C-code. Most of these are accessiblefrom Python, but a few are not exposed due to their limited use. Every newPython type has an associated PyObject * with an internal structure that includesa pointer to a “method table” that defines how the new object behaves in Python.When you receive a Python object into C code, you always get a pointer to aPyObject structure. Because a PyObject structure is very generic and definesonly PyObject HEAD, by itself it is not very interesting. However, different objectscontain more details after the PyObject HEAD (but you have to cast to the correcttype to access them — or use accessor functions or macros).
Instead of special method names which define behavior for Python classes, thereare “function tables” which point to functions that implement the desired results.Since Python 2.2, the PyTypeObject itself has become dynamic which allows Ctypes supportiverole: the PyArrayIter Type, the PyArrayMultiIter Type, and thePyArrayDescr Type. The PyArrayIter Type is the type for a flat iteratorfor an ndarray (the object that is returned when getting the flat attribute).
213The PyArrayMultiIter Type is the type of the object returned when callingbroadcast(). It handles iteration and broadcasting over a collection of nestedsequences. Also, the PyArrayDescr Type is the data-type-descriptor type whoseinstances describe the data. Finally, there are 21 new scalar-array types which arenew Python scalars corresponding to each of the fundamental data types availablefor arrays. An additional 10 other types are place holders that allow the arrayscalars to fit into a hierarchy of actual Python types.
PyObject HEAD This is needed by all Python objects. It consists of (at least) a reference count member (ob refcnt) and a pointer to the typeobject (ob type). (Other elements may also be present if Python was compiled with special options see Include/object.h in the Python source tree for more information). The ob type member points to a Python type object.
data A pointer to the first element of the array. This pointer can (and normally should) be recast to the data type of the array.
214nd An integer providing the number of dimensions for this array. When nd is 0, the array is sometimes called a rank-0 array. Such arrays have undefined dimensions and strides and cannot be accessed. NPY MAXDIMS is the largest number of dimensions for any array.
strides An array of integers providing for each dimension the number of bytes that must be skipped to get to the next element in that dimension.
base UPDATEIFCOPY flag set, then this array is a working copy of a “misbehaved” array. As soon as this array is deleted, the array pointed to by base will be updated with the contents of this array.
descr A pointer to a data-type descriptor object (see below). The data-type de- scriptor.
weakreflist This member allows array objects to have weak references (using the weakref module).
215zero. There is also a dynamic table of user-defined PyArray Descr objects thatis also maintained. Once a data-type-descriptor object is “registered” it shouldnever be deallocated either. The function PyArray DescrFromType(...) can beused to retrieve a PyArray Descr object from an enumerated type-number (eitherbuilt-in or user-defined). The format of the structure that lies at the heart of thePyArrayDescr Type is.
typedef struct { PyObject HEAD PyTypeObject *typeobj; char kind; char type; char byteorder; char hasobject; int type num; int elsize; int alignment; PyArray ArrayDescr *subarray; PyObject *fields; PyArray ArrFuncs *f; } PyArray Descr;
typeobj Pointer to a typeobject that is the corresponding Python type for the elements of this array. For the builtin types, this points to the correspond- ing hasobject flag.
kind A character code indicating the kind of array (using the array interface type- string notation). A ’b’ represents Boolean, a ’i’ represents signed integer, a ’u’ represents unsigned integer, ’f’ represents floating point, ’c’ represents complex floating point, ’S’ represents 8-bit character string, ’U’ represents 32-bit/character unicode string, and ’V’ repesents arbitrary.
216hasobject A data-type bit-flag that determines if the data-type exhibits object- array like behavior. Each bit in this member is a flag which are named as:
type num A number that uniquely identifies the data type. For new data-types, this number is assigned when the data-type is registered.
217elsize For data types that are always the same size (such as long), this holds the size of the data type. For flexible data types where different arrays can have a different elementsize, this should be 0.
alignment A number providing alignment information for this data type. Specif- ically, it shows how far from the start of a 2-element structure (whose first element is a char), the compiler places an item of this type: offsetof(struct {char c; type v;}, v)
typedef struct { PyArray Descr *base; PyObject *shape; } PyArray ArrayDescr;
218 re- duced functionality for that data-type. (Also, the nonzero function will be filled in with a default function if it is NULL when you register a user-defined data-type).
typedef struct { PyArray VectorUnaryFunc *cast[PyArray[PyArray NSORTS]; PyArray ArgSortFunc *argsort[PyArray NSORTS]; PyObject *castdict; PyArray ScalarKindFunc *scalarkind; int **cancastscalarkindto; int *cancastto; int listpickle } PyArray ArrFuncs;
cast (void) (void* from, void* to, npy intp n, void* fromarr, void* toarr)
219 argu- ments fromarr and toarr are interpreted as PyArrayObjects for flexible arrays to get itemsize information.getitem (PyObject*) (void* data, void* arr) A pointer to a function that returns a standard Python object from a single element of the array object arr pointed to by data. This function must be able to deal with “misbehaved” (misaligned and/or swapped) arrays correctly.setitem (int) (PyObject* item, void* data, void* arr) A pointer to a function that sets the Python object item into the array, arr, at the position pointed to by data. This function deals with “mis- behaved” arrays. If successful, a zero is returned, otherwise, a negative one is returned (and a Python error set).copyswapn (void) (void* dest, npy intp dstride, void* src, npy intp sstride, npy intp n, int swap, void *arr)copyswap (void) (void* dest, void* src, int swap, void *arr) These members are both pointers to functions to copy data from src to dest and swap if indicated. The value of arr is only used for flexi- ble (NPY STRING, NPY UNICODE, and NPY VOID) arrays (and is ob- tained.compare (int) (const void* d1, const void* d2, void* arr) A pointer to a function that compares two elements of the array, arr, pointed to by d1 and d2. This function requires behaved arrays. The return value is 1 if *d1 > *d2, 0 if *d1 == *d2, and -1 if *d1 < *d2. The array object arr is used to retrieve itemsize and field information for flexible arrays.argmax (int) (void* data, npy intp n, npy intp* max ind, void* arr)
220.dotfunc (void) (void* ip1, npy intp is1, void* ip2, npy intp is2, void* op, npy intp n, void* arr).scanfunc (int) (FILE* fd, void* ip ,void* sep ,void* arr) A pointer to a function that scans (scanf style) one element of the corre- sponding.fromstr (int) (char* str, void* ip, char** endptr, void* arr).nonzero (Bool) (void* data, void* arr) A pointer to a function that returns TRUE if the item of arr pointed to by data is nonzero. This function can deal with misbehaved arrays.fill (void) (void* data, npy intp length, void* arr)
221.fillwithscalar (void).sort (int) (void* start, npy intp length, void* arr) An array of function pointers to a particular sorting algorithms. A particular sorting algorithm is obtained using a key (so far PyArray QUICKSORT, PyArray HEAPSORT, and PyArray MERGESORT are defined). These sorts are done in-place assuming contiguous and aligned data.argsort ).castdict Either NULL or a dictionary containing low-level casting functions for user- defined data-types. Each function is wrapped in a PyCObject* and keyed by the data-type number.scalarkind (PyArray PyArray SCALARKIND.cancastscalarkindto Either NULL or an array of PyArray NSCALARKINDS pointers. These pointers should each be either NULL or a pointer to an array of integers (terminated by PyArray NOTYPE) indicating data-types that a scalar
222 of this data-type of the specified kind can be cast to safely (this usually means without losing precision). cancastto Either NULL or an array of integers (terminated by PyArray NOTYPE) indicated data-types that this data-type can be cast to safely (this usually means without losing precision). listpickle Unused.
The PyArray Type typeobject implements many of the features of Python ob-jects including the tp as number, tp as sequence, tp as mapping, and tp as bufferinterfaces. The rich comparison (tp richcompare) is also used along with new-style attribute lookup for methods (tp methods) and properties (tp getset). ThePyArray Type can also be sub-typed.
i TIP The tp as number methods use a generic approach to call what- ever PyS- tring SetStringFunction(...).
223 The core of the ufunc is the PyUFuncObject which contains all the informationneeded to call the underlying C-code loops that perform the actual work. It hasthe following structure.
typedef struct { PyObject HEAD int nin; int nout; int nargs; int identity; PyUFuncGenericFunction *functions; void **data; int ntypes; int check return; char *name; char *types; char *doc; void *ptr; PyObject *obj; PyObject *userloops; } PyUFuncObject;
nargs The total number of arguments (nin+nout ). This must be less than NPY MAXARGS.
functions (void) (char** args, npy intp* dims, npy intp* steps, void* ex- tradata )
An array of function pointers — one for each data type supported by the ufunc. This is the vector loop that is called to implement the underlying function dims[0] times. The first argument, args, is an array of nargs pointers to
224.
data.
ntypes The number of supported data types for the ufunc. This number specifies how many different 1-d loops (of the builtin data types) are available.
check return Obsolete and unused. However, it is set by the corresponding entry in the main ufunc creation routine: PyUFunc FromFuncAndData(...).
name A string name for the ufunc. This is used dynamically to build the doc attribute of ufuncs.
types An array of nargs×ntypes 8-bit type numbers which contains the type sig- nature.
doc Documentation for the ufunc. Should not contain the function signature as this is generated dynamically when doc is retrieved.
ptr Any dynamically allocated memory. Currently, this is used for dynamic ufuncs created from a python function to store room for the types, data, and name members.
obj For ufuncs dynamically created from python functions, this member holds a reference to the underlying Python function.
225userloops;
226 } PyArrayIterObject;
strides The strides of the array. How many bytes needed to jump to the next element in each dimension.
backstrides How many bytes needed to jump from the end of a dimension back to its beginning. Note that backstrides[k]=strides[k]*dims m1 [k], but it is stored here as an optimization.
factors This array is used in computing an N-d index from a 1-d index. It contains needed products of the dimensions.
dataptr This member points to an element in the ndarray indicated by the index.
227by adjusting array iterators so that each iterator represents the broadcasted shapeand size, but has its strides adjusted so that the correct element from the array isused;
PyObject HEAD Needed at the start of every Python object (holds reference count and type identification).
numiter The number of arrays that need to be broadcast to the same shape.
dimensions The shape of the broadcasted result (only nd slots are used).
iters An array of iterator objects that holds the iterators for the arrays to be broadcast together. On return, the iterators are adjusted for broadcasting.
12.1.7 ScalarArrayTypesThere is a Python type for each of the different built-in data types that can bepresent in the array Most of these are simple wrappers around the corresponding
228data type in C. The C-names for these types are Py<TYPE>ArrType Typewhere <TYPE> can be
These type names are part of the C-API and can therefore be created in extensionC-code. There is also a PyIntpArrType Type and a PyUIntpArrType Typethat are simple substitutes for one of the integer types that can hold a pointeron the platform. The structure of these scalar objects is not exposed to C-code.The function PyArray ScalarAsCtype(..) can be used to extract the C-typevalue from the array scalar and the function PyArray Scalar(...) can be used toconstruct an array scalar from a C-value.
typedef struct { npy intp *ptr; int len; } PyArray Dims;
ptr A pointer to a list of (npy intp) integers which usually represent array shape or array strides.
len The length of the list of integers. It is assumed safe to access ptr [0] to ptr [len-1].
22912.2.2 PyArray ChunkThis is equivalent to the buffer object structure in Python up to the ptr member.On 32-bit platforms (i.e. if NPY SIZEOF INT==NPY SIZEOF INTP) or in Python2.5, the len member also matches an equivalent member of the buffer object. It isuseful to represent a generic single-segment chunk of memory.
typedef struct { PyObject HEAD PyObject *base; void *ptr; npy intp len; int flags; } PyArray Chunk;
PyObject HEAD Necessary for all Python objects. Included here so that the PyArray Chunk structure matches that of the buffer object (at least to the len member).
base The Python object this chunk of memory comes from. Needed so that memory can be accounted for properly.
flags Any data flags (e.g. NPY WRITEABLE) that should be used to interpret the memory.
12.2.3 PyArrayInterfaceThe PyArrayInterface structure is defined so that NumPy and other exten-sion modules can use the rapid array interface protocol. The array structmethod of an object that supports the rapid array interface protocol should returna PyCObject that contains a pointer to a PyArrayInterface structure with therelevant details of the array. After the new array is created, the attribute shouldbe DECREF’d which will free the PyArrayInterface structure. Remember toINCREF the object (whose array struct attribute was retrieved) and point thebase member of the new PyArrayObject to this same object. In this way thememory for the array will be managed correctly.
230 typedef struct { int two; int nd; char typekind; int itemsize; int flags; npy intp *shape; npy intp *strides; void *data; PyObject *descr; } PyArrayInterface;
flags deter- mined).
strides An array containing the number of bytes to jump to get to the next element in each dimension.
descr A Python object describing the data-type in more detail (currently an ar- ray description list of tuples). This can be NULL if typekind and itemsize provide enough information.
23112.2.4 Internally used structuresInternally, the code uses some additional Python objects primarily for memorymanagement. These types are not accessible directly from Python, and are notexposed to the C-API. They are included here only for completeness and assistancein understanding the code.
12.2.4.1 PyUFuncLoopObject
A loose wrapper for a C-structure that contains the information needed for loop-ing. This is useful if you are trying to understand the ufunc looping code.The PyUFuncLoopObject is the associated C-structure. It is defined in theufuncobject.h header.
12.2.4.2 PyUFuncReduceObject
A loose wrapper for the C-structure that contains the information needed for reduce-like methods of ufuncs. This is useful if you are trying to understand the reduce,accumulate, and reduce-at code. The PyUFuncReduceObject is the associatedC-structure. It is defined in the ufuncobject.h header.
Advanced indexing is handled with this Python type. It is simply a loose wrap-per around the C-structure containing the variables needed for advanced array in-dexing. The associated C-structure, PyArrayMapIterObject, is useful if youare trying to understand the advanced-index mapping code. It is defined in thearrayobject.h header. This type is not exposed to Python and could be re-placed with a C-structure. As a Python type it takes advantage of reference-countedmemory management.
232Chapter 13
Complete API
—Richard P. Feynman
CHAR BIT The number of bits of a char. The char is the unit of all sizeof definitions
233SIZEOF SHORT sizeof(short)
HAVE LONGDOUBLE FUNCS System has C99 long double math functions.
234HAVE EXPM1 System has the expm1 function: exp (x) − 1.
WARNING The names for the types in c code follows c naming conventions more closely. The Python names for these types follow Python conventions. Thus, NPY FLOAT picks up a 32-bit float in C, but “float ” in python corresponds to a 64-bit double. The bit-width names can be used in both Python and C for clarity.
The various character codes indicating certain types are also part of an enumeratedlist. References to type characters (should they be needed at all) should always usethese enumerations. The form of them is NPY <NAME>LTR where <NAME>can be
235 BOOL, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, LONGLONG, ULONGLONG, FLOAT, DOUBLE, LONGDOUBLE, CFLOAT, CDOUBLE, CLONG- DOUBLE, OBJECT, STRING, VOID INTP, UINTP GENBOOL, SIGNED, UNSIGNED, FLOATING, COMPLEX
The latter group of <NAME>s corresponds to letters used in the array interfacetypestring specification.
13.2.2 Defines13.2.2.1 Max and min values for integers
These are defined for <bits> = 8, 16, 32, 64, 128, and 256 and provide the max- imum (minimum) value of the corresponding (unsigned) integer type. Note: the actual integer type may not be available on all platforms (i.e. 128-bit and 256-bit integers are rare).
This is defined for all defined for <type> = BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, LONGLONG, ULONG- LONG, INTP, UINTP
236 BOOL, CHAR, SHORT, INT, LONG, LONGLONG, FLOAT, DOUBLE, LONGDOUBLE
All of the numeric data types (integer, floating point, and complex) have constantsthat are defined to be a specific enumerated type number. Exactly which enu-merated type a bit-width type refers to is platform dependent. In particular, theconstants available are PyArray <NAME><BITS> where <NAME> is INT,UINT, FLOAT, COMPLEX and <BITS> can be 8, 16, 32, 64, 80, 96, 128, 160,192, 256, and 512. Obviously not all bit-widths are available on all platforms forall the kinds of numeric types. Commonly 8-, 16-, 32-, 64-bit integers; 32-, 64-bitfloats; and 64-, 128-bit complex types are available.
13.2.3.1 Boolean
npy bool unsigned char; The constants NPY FALSE and NPY TRUE are also defined.
Unsigned versions of the integers can be defined by pre-pending a ’u’ to the frontof the integer name.
237npy (u)int (unsigned) int
npy (u)intp (unsigned) Py intptr t (an integer that is the size of a pointer on the platform).
complex types are structures with .real and .imag members (in that order).
There are also typedefs for signed integers, unsigned integers, floating point, andcomplex floating point types of specific bit-widths. The available type names are
where <bits> is the number of bits in the type and can be 8, 16, 32, 64, 128, and256 for integer types; 16, 32, 64, 80, 96, 128, and 256 for floating-point types; and32, 64, 128, 160, 192, and 512 for complex-valued types. Which bit-widths areavailable is platform dependent. The bolded bit-widths are usually available on allplatforms.
23813.3 Array API13.3.1 Array structure and data accessThese macros all access the PyArrayObject structure members. The inputargument, obj, can be any PyObject* that is directly interpretable as aPyArrayObject* (any instance of the PyArray Type and its sub-types)..
239.
These functions and macros provide easy access to elements of the ndarray from C.These work for all arrays. You may need to take care when accessing the data inthe array, however, if it is not in machine byte-order, misaligned, or not writeable.In other words, be sure to respect the state of the flags unless you know what youare doing, or have previously guaranteed an array that is writeable, aligned, andin machine byte-order using PyArray FromAny. If you wish to handle all typesof arrays, the copyswap function for each type is useful for handling misbehavedarrays. Some platforms (e.g. Solaris) do not like misaligned data and will crash ifyou de-reference a misaligned pointer. Other platforms (e.g. x86 Linux) will justwork.
240PyArray GETPTR3 (void*) (PyObject* obj, <npy intp> i, <npy intp> j, <npy intp> k) not &PyArray Type (e.g. a Python subclass of the ndarray), argu- ment is used as the new flags for the array (except the state of NPY OWNDATA and F CONTIGUOUS is nonzero non-NULL data). Any provided dims and strides are copied into newly allocated dimension and strides arrays for the new array object.
241 This is similar to PyArray DescrNew(...) except you specify the data-type de- scriptor accom- plished using Py INCREF on that object and setting the base mem- ber of the new array to point to that object. If strides are passed in they must be consistent with the dimensions, the itemsize, and the data of the array.
PyArray SimpleNew (PyObject*) (int nd, npy intp* dims, int typenum)
Create a new unitialized array of type, typenum, whose size in each of nd dimen- sions).
242PyArray Zeros PyArray OBJECT).
PyArray ZEROS (PyObject*) (int nd, npy intp* dims, int type num, int fortran)
PyArray Empty PyArray OBJECT in which case the array is filled with Py None.
PyArray EMPTY (PyObject*) (int nd, npy intp* dims, int typenum, int fortran)
24313.3.2.2 From other objects
This is the main function used to obtain an array from any nested sequence, or ob- ject that exposes the array interface, op. The parameters allow specification of the required type, the minimum (min depth) and maximum (max depth) number of dimensions acceptable, and other requirements for the array. The dtype argument needs to be a PyArray Descr structure indicating the de- sired data-type (including required byteorder). The dtype argument may be NULL, indicating that any data-type (and byteorder) is acceptable. se- quence protocol). The new array will have NPY DEFAULT as its flags member. The context argument is passed to the array method of op and is only used if the array is constructed that way.
244 NPY FORCECAST Force a cast to the output type even if it cannot be done safely. Without this flag, a data cast will occur only if it can be done safely, otherwise an error is reaised. NPY UPDATEIFCOPY If op is already an array, but does not satisfy the requirements, then a copy is made (which will satisfy the requirements). If this flag is present and a copy (of an object that is already an array) must be made, then the corresponding NPY BEHAVED NPY ALIGNED | NPY WRITEABLE NPY CARRAY NPY C CONTIGUOUS | NPY BEHAVED NPY CARRAY RO NPY C CONTIGUOUS | NPY ALIGNED NPY FARRAY NPY F CONTIGUOUS | NPY BEHAVED NPY FARRAY RO NPY F CONTIGUOUS | NPY ALIGNED NPY DEFAULT NPY CARRAY NPY IN ARRAY NPY CONTIGUOUS | NPY ALIGNED NPY IN FARRAY NPY F CONTIGUOUS | NPY ALIGNED NPY INOUT ARRAY NPY C CONTIGUOUS | NPY WRITEABLE | NPY ALIGNED NPY INOUT FARRAY NPY F CONTIGUOUS | NPY WRITEABLE | NPY ALIGNED NPY OUT ARRAY NPY C CONTIGUOUS | NPY WRITEABLE | NPY ALIGNED | NPY UPDATEIFCOPY NPY OUT FARRAY NPY F CONTIGUOUS | NPY WRITEABLE | NPY ALIGNED | UPDATEIFCOPY
245 NPY ELEMENTSTRIDES which indicates that the array should be aligned in the sense that the strides are multiples of the element size.
NPY NOTSWAPPED Make sure the returned array has a data-type descrip- tor that is in machine byte-order, over-riding any specification in the dtype argument. Normally, the byte-order requirement is determined by the dtype argument. If this flag is set and the dtype argument does not indicate a ma- chine byte-order descriptor (or is NULL and the object is already an array with a data-type descriptor that is not in machine byte-order), then a new data-type descriptor is created and used with its byte-order field set to native.
NPY ELEMENTSTRIDES Make sure the returned array has strides that are multiples of the element size.
Special case of PyArray FromAny for when op is already an array but it needs to be of a specific newtype (including byte-order) or has certain requirements.
Return an ndarray object from a Python object that exposes the array method. The array method can take 0, 1, or 2 arguments ([dtype, con- text]) where context is used to pass information about where the array method is being called from (currently only used in ufuncs).
246PyArray ContiguousFromAny (PyObject*) (PyObject* op, int typenum, int min depth, int max depth).
247, perform- ing a data-type conversion if necessary. If an error occurs return -1 (otherwise 0). The shape of src must be broadcastable to the shape of dest. The data areas of dest and src may overlap.
248PyArray FROM O (PyObject*) (PyObject* obj)Array FROM OTF (PyObject*) (PyObject* obj, int typenum, int re- quirements)
249PyArray CheckExact (op) a builtin Python “scalar” object (int, float, complex, str, unicode, long, bool).
25013.3.3.2 Data-type checking
251PyDataType ISNUMBER (descr)
Type represents any integer, floating point, or complex floating point number.
Type represents one of the flexible array types (NPY STRING, NPY UNICODE, or NPY VOID).
252PyTypeNum ISOBJECT (num).
253 Special case of PyArray EquivTypes(...) that does not accept flexible data types but may be easier to call. appropri- ate. The fortran member of the type structure will be respected in producing the strides of the output array..
254PyArray CanCastSafely (int) (int fromtype, int totype).
255’d or a memory-leak will occur. The example template-code below shows a typically usage.
A pointer to newly created memory of size arr ->itemsize that holds the repre- sentation of 0 for that type. The returned pointer, ret, must be freed using PyDataMem FREE(ret) when it is not needed anymore.
A pointer to newly created memory of size arr ->itemsize that holds the repre- sentation of 1 for that type. The returned pointer, ret, must be freed using PyDataMem FREE(ret) when it is not needed anymore.
Register a data-type as a new user-defined data type for arrays. The type must have most of its entries filled in. This is not always checked and errors can produce segfaults. In particular, the typeobj member of the dtype structure
256 refer- ence.
257PyArray XDECREF (int) (PyArrayObject* op) PyArray OBJECT and be single-segment and uninitialized (no previous objects in position). Use PyArray DECREF(arr ) if you need to decrement all the items in the object array prior to calling this inFortan-contiguous order. The array flags are used to indicate what can be saidabout data associated with an array.
NPY C CONTIGUOUS The data area is in C-style contiguous order (last index varies the fastest).
NPY ALIGNED The data area is aligned appropriately (for all strides).
258 Notice that the above 3 flags are are defined so that a new, well-behaved array has these flags defined as true.
These constants are used in PyArray FromAny (and its macro forms) to specifydesired properties of the new array.
NPY FORCECAST Cast to the desired type, even if it can’t be done without losing information.
NPY ENSURECOPY Make sure the resulting array is a copy of the original.
NPY ENSUREARRAY Make sure the resulting object is an actual ndarray (or bigndarray), and not a sub-class.
25913.3.4.4 Flag checking C CONTIGUOUS, NPY F CONTIGUOUS, NPY OWNDATA, NPY ALIGNED, NPY WRITEABLE, NPY UPDATEIFCOPY..
260PyArray ISCARRAY RO (arr) C CONTIGUOUS, NPY ALIGNED, and NPY.
261 array. But, it can also be used to select specific bytes or groups of bytes from any array type.
Equivalent to self.copy(fortran). Make a copy of the old array. The returned ar- ray is always aligned and writeable with data interpreted the same as the old array. If order is NPY CORDER, then a C-style contiguous array is returned. If order is NPY FORTRANORDER, then a Fortran-style contiguous array is re- turned. If order is NPY ANYORDER, then the array returned is Fortran-style contiguous only if the old one is; otherwise, it is C-style contiguous.
262 ob- ject)..
263 self.squeeze(). Return a new view of self with all of the dimensions of length 1 removed from the shape.
WARNING matrix objects are always 2-dimensional. Therefore, PyArray Squeeze has no effect on arrays of matrix sub-class.
264 has shape 10 × 20 × 30, and permute.ptr is (0,2,1) the shape of the result is 10 × 30 × 20. If permute is NULL, the shape of the result is 30 × 20 × 10.
Place the values in self wherever corresponding positions (using a flattened con- text) in mask are true. The mask and self arrays must have the same total number of elements. If values is too small, it will be repeated as necessary.
265PyArray Repeat (PyObject*) (PyArrayObject* self, PyObject* op, int axis)
Equivalent to self.sort(axis). Return an array with the items of self sorted along axis.
266 Given a sequence of arrays (sort keys) of the same shape, return an array of indices (similar to PyArray ArgSort(...)) that would sort the arrays lexi-.
26713.3.5.4 Calculation
i TIP Pass in NPY MAXDIMS for axis in order to achieve the same effect that is obtained by passing in axis = None in Python (treating the array as a 1-d array).
Equivalent to self.max(axis). Return the largest element of self along the given axis.
Equivalent to self.min(axis). Return the smallest element of self along the given axis.
NOTE The rtype argument specifies the data-type the reduction should take place over. This is important if the data-type of the array is not “large” enough to handle the output. By default, all inte- ger data-types are made at least as large as NPY LONG for the “add” and “multiply” ufuncs (which form the basis for mean, sum, cumsum, prod, and cumprod functions).
268PyArray Mean (PyObject*) (PyArrayObject* self, int axis, int rtype, PyArrayObject* out)
Equivalent to self.trace self.clip(min, max ). Clip an array, self, so that values larger than max are fixed to max and values less than min are fixed to min.
269PyArray Sum (PyObject*) (PyArrayObject* self, int axis, int rtype, PyArrayObject* out)
Equivalent to self.all(axis). Return an array with True elements for every 1-d sub-array of self defined by axis in which all the elements are True.
Equivalent to self.any(axis). Return an array with True elements for every 1-d sub-array of self defined by axis in which any of the elements are True.
13.3.6 Functions13.3.6.1 Array Functions
PyArray AsCArray (int) (PyObject** op, void* ptr, npy intp* dims, int nd, int typenum, int itemsize)
270. 0..
271PyArray MatrixProduct (PyObject*) (PyObject* obj1, PyObject* obj)
Compute a product-sum over the last dimension of obj1 and the second-to-last dimension of obj2. For 2-d arrays this is a matrix-product. Neither array is conjugated.).
PyArray CheckStrides (Bool) (int elsize, int nd, npy intp numbytes, npy intp* dims, npy intp* newstrides)
272 single-segment array. Return NPY TRUE if newstrides is acceptable, otherwise return NPY FALSE.
Both of these routines multiply an n-length array, seq, of integers and return the result. No overflow checking is performed.
PyArray CompareLists (int) (npy intp* l1, npy intp* l2, int n)
Given two n-length arrays of integers, l1, and l2, return 1 if the lists are identical; otherwise, return 0..
273 Evaluates true if op is an array iterator (or instance of a subclass of the array iterator type).
Incremement the index and the dataptr members of the iterator to point to the next element of the array. If the array is not (C-style) contiguous, also incre- ment the N-dimensional coordinates.
274 Advance each iterator in a multi-iterator object, multi, to its next (broadcasted) element.
This function encapsulates the broadcasting rules. The mit container should al- ready “broad- casted,” finds the dimension with the smallest “sum of strides” in the broad- casted result and adapts all the iterators so as not to iterate over that di- mension .
27513.3.9 Array ScalarsPyArray Return (PyObject*) (PyArrayObject* arr) the data (cast to the data type indicated by outcode) from the array- scalar, scalar, into the memory pointed to by ctypeptr (which must be large enough to handle the incoming memory).
276PyArray TypeObjectFromType (PyObject*) (int type).
Implements the rules for scalar coercion. Scalars are only silently co- erced.
27713.3.10 Data-type descriptors
WARNING Data-type objects must be reference counted so be aware of the action on the data-type reference of different C-API calls. The Rule is that when a data-type descriptor object is returned it is a new reference. Functions that take PyArray Descr* objects and return arrays steal references to their inputs unless otherwise noted. Unless you just created the data-type object you must usu- ally increase the reference count of an object passed in describing the data-type..
278PyArray DescrFromObject (PyArray Descr*) (PyObject* op, PyArray Descr* mintype)
Convert any compatible Python object, obj, to a data-type object in dtype. This version of the converter converts None objects so that the returned data- type is NULL. This function can also be used with the “O&” character in PyArg ParseTuple processing.
279Pyarray DescrAlignConverter2 (int) (PyObject* obj, PyArray Descr** dtype)not. The first argument to all of these function is a Python object. The secondargument is the address of the C-type to convert the Python object to.
WARNING Be sure to understand what steps you should take to manage the memory when using these conversion functions. These functions can require freeing memory, incrementing or decrementing refer- ence counts of specific objects based on your use.
280 If PyArray Check(obj ) is TRUE then it is returned in *address without incrementing its reference count.
Convert any Python sequence, obj, smaller than NPY MAXDIMS to an array of npy intp’s. The Python sequence a Python object, obj, representing an axis argument to the proper value for passing to the functions that take an integer axis. Specifically, if obj is None, set axis to NPY MAXDIMS which is interpreted by all these C-API functions correctly.
Convert any Python object, obj, to NPY TRUE or NPY FALSE, and place the result in value.
Convert Python strings into the corresponding byte-order character: ’>’, ’<’, ’s’, ’=’, or ’|’.
281PyArray SortkindConverter (int) (PyObject* obj, NPY SORTKIND* sort)
Convert Python strings into one of NPY QUICKSORT (starts with ’q’ or ’Q’) , NPY HEAPSORT (starts with ’h’ or ’H’), or NPY MERGESORT (starts with ’m’ or ’M’).
Convert Python strings into one of NPY SEARCHLEFT (starts with ’l’ or ’L’), or NPY SEARCHRIGHT (starts with ’r’ or ’R’).
Convert all kinds of Python objects (including arrays and array scalars) to a standard integer. On error, -1 is returned and an exception set. You may find useful the macro:.
28213.3.12 Miscellaneous13.3.12.1 Importing the API
In order to make use of the C-API from another extension module, theimport array() command must be used. If the extension module is self-containedin a single .c file, then that is all that needs to be done. If however, the extensionmodule involve multiple files where the C-API is needed then some additional stepsmust be taken.
This function must be called in the initialization section of a module that will make use of the C-API. It imports the module where the function-pointer table is stored and points the correct variable to it.
NO IMPORT ARRAY
Using these #defines you can use the C-API in multiple files for a single ex- tension:
283 This just returns the value NPY VERSION. Because it is in the C-API, however, comparing the output of this function from the value defined in the current header gives a way to test if the C-API has changed thus requiring a re- compilation of extension modules that use the C-API.
NumPy stores an internal table of Python callable objects that are used to im- plement (un- less you have designed the function to handle that), or an unchecked infinite recursion can result (possibly causing program crash). The key names that represent operations that can be replaced are:
284.
PyDimMem RENEW (npy intp*) (npy intp* ptr, npy intp newnd)
These macros are only meaningful if NPY ALLOW THREADS evaluates True duringcompilation of the extension module. Otherwise, these macros are equivalent towhitespace. Python uses a single Global Interpreter Lock (GIL) for each Pythonprocess so that only a single thread may excecute at a time (even on multi-cpumachines). When calling out to a compiled function that may take time to compute(and does not have side-effects for other threads like updated global variables),
285the GIL should be released so that other Python threads can run while the time-consuming calculations are performed. This can be accomplished using two groupsof macros. Typically, if one macro in a group is used in a code block, all of themmust be used in the same code block. Currently, NPY ALLOW THREADS is definedto the python-defined WITH THREADS constant unless the environment variableNPY NOSMP is set in which case NPY ALLOW THREADS is defined to be 0.
Group 1 This group is used to call code that may take some time but does not use any Python C-API calls. Thus, the GIL should be released during its calculation.
Group 2.
286 These macros accomplish essentially a reverse of the previous three (acquire the LOCK saving what state it had) and then re-release it with the saved state.
NPY ALLOW C API DEF).
i TIP Never use semicolons after the threading support macros.
13.3.12.5 Priority
NPY MAX BUFSIZE Largest size allowed for the user-settable buffers.
287NPY VERSION The current version of the ndarray object (check to see if this variable is defined to guarantee the numpy/arrayobject.h header is being used)..
Returns the maximum of a and b. If (a) or (b) are expressions they are evaluated twice.
Returns the minimum of a and b. If (a) or (b) are expressions they are evaluated twice.
DECREF’s an array object which may have the NPY UPDATEIFCOPY flag set without causing the contents to be copied back into the original array. Resets the NPY WRITEABLE flag on the base object. This is useful for recovering from an error condition when NPY UPDATEIFCOPY is used.
28813.3.12.9 Enumerated Types
NPY ORDER A variable type indicating the order that an array should be in- terpreted in. The value of a variable of this type can be NPY <ORDER> where <ORDER> is
NPY CLIPMODE A variable type indicating the kind of clipping that should be applied in certain functions. The value of a variable of this type can be NPY <MODE> where <MODE> is
PyUFunc <VALUE> <VALUE> can be One (1), Zero (0), or None (-1)
28913.4.2 MacrosNPY LOOP BEGIN THREADS.
13.4.3 FunctionsPyUFunc FromFuncAndData (PyObject*) (PyUFuncGenericFunction* func, void** data, char* types, int ntypes, int nin, int nout, int iden- tity, char* name, char* doc, int check return)
Create a new broadcasting universal function from required variables. Each ufunc builds around the notion of an element-by-element operation. Each ufunc object contains pointers to 1-d loops implementing the basic functionality for each supported type.
290nout The number of outputs
ntypes How many different data-type “signatures” the ufunc has implemented.
types Must be of length (nin+nout )*ntypes, and it contains the data-types (built- in only) that the corresponding function in the func array can deal with.
data Should be NULL or a pointer to an array of size ntypes. This array may contain arbitrary extra-data to be passed to the corresponding 1-d loop function in the func array.
doc Allows passing in a documentation string to be stored with the ufunc. The documentation string should not contain the name of the function or the calling signature as that will be dynamically determined from the object and available when accessing the doc attribute of the ufunc.
check return Unused and present for backwards compatibility of the C-API. A corresponding check return integer does exist in the ufunc structure and it does get set with this value when the ufunc object is created..
291. The mps argument is an array of.
A simple interface to the IEEE error-flag checking support. The errmask argu- ment func- tion)
292 looked-up buffer-size to use is passed into bufsize, and the value of the error mask is placed into errmask.
PyUFunc d d (void) (char** args, npy intp* dimensions, npy intp* steps, void* func)
PyUFunc f f (void) (char** args, npy intp* dimensions, npy intp* steps, void* func)
PyUFunc g g (void) (char** args, npy intp* dimensions, npy intp* steps, void* func)
PyUFunc F F (void)
293 the supported data types .
PyUFunc ff f (void) (char** args, npy intp* dimensions, npy intp* steps, void* func).
294PyUFunc OO O (void) (char** args, npy intp* dimensions, npy intp* steps, void* func)
One-input, one-output, and two-input, one-output core 1-d functions for the NPY OBJECT data type. These functions handle reference count issues and return early on error. The actual function to call is func and it must ac- cept {int nin; int nout; PyObject* callable}. At each iteration of the loop, the nin input objects are exctracted from their object arrays and placed into an argument tuple, the Python callable is called with the input arguments, and the nout outputs are placed into their object arrays.
295NO IMPORT UFUNC
These are the constants and functions for accessing the ufunc C-API from exten- sion.
296Chapter 14
—John A. Locke
—Alan Turing
297defined and compiled in C code. The basic steps for doing this in Python are well-documented and you can find more information in the documentation for Pythonitself available online at. In addition to the Python C-API, there is a full and rich C-API for NumPyallowing sophisticated manipulations on a C-level. However, for most applications,only a few API calls will typically be used. If all you need to do is extract a pointer tomemory along with some shape information to pass to another calculation routine,then you will use very different calls, then if you are trying to create a new array-liketype or add a new data type for ndarrays. This chapter documents the API callsand macros that are most commonly used.
PyMODINIT FUNC init<name>(void) { (void)Py InitModule(’’<name>’’, mymethods); import array(); }
298general way to add itmes to the module is to get the module dictionary using Py-Module GetDict(module). With the module dictionary, you can add whatever youlike to the module manually. An easier way to add objects to the module is to useone of three additional Python C-API calls that do not require a separate extractionof the module dictionary. These are documented in the Python documentation, butrepeated here for convenience:
All three of these functions require the module object (the return value of Py InitModule). The name is a string that labels the value in the mod- ule. Depending on which function is called, the value argument is either a general object (PyModule AddObject steals a reference to it), an integer constant, or a string constant.
299Each entry in the mymethods array is a PyMethodDef structure containing 1) thePython name, 2) the C-function that implements the function, 3) flags indicatingwhether or not keywords are accepted for this function, and 4) The docstring for thefunction. Any number of functions may be defined for a single module by addingmore entries to this table. The last entry must be all NULL as shown to act asa sentinel. Python looks for this entry to know that all of the functions for themodule have been defined. The last thing that must be done to finish the extension module is to actuallywrite the code that performs the desired functions. There are two kinds of functions:those that don’t accept keyword arguments, and those that do.
static PyObject* nokeyword cfunc (PyObject *dummy, PyObject *args) { /* convert Python arguments */ /* do function */ /* return something */ }
The dummy argument is not used in this context and can be safely ignored. Theargs argument contains all of the arguments passed in to the function as a tu-ple. You can do anything you want at this point, but usually the easiest way tomanage the input arguments is to call PyArg ParseTuple (args, format string,addresses to C variables...) or PyArg UnpackTuple (tuple, “name”, min, max,...). A good description of how to use the first function is contained in the PythonC-API reference manual under section 5.5 (Parsing arguments and building values).You should pay particular attention to the “O&” format which uses converter func-tions to go between the Python object and the C object. All of the other formatfunctions can be (mostly) thought of as special cases of this general rule. There areseveral converter functions defined in the NumPy C-API that may be of use. Inparticular, the PyArray DescrConverter function is very useful to support arbi-trary data-type specification. This function transforms any valid data-type Pythonobject into a PyArray Descr* object. Remember to pass in the address of theC-variables that should be filled in.
300 There are lots of examples of how to use PyArg ParseTuple throughout theNusing the “O” format string. However, the converter functions usually require someform of memory handling. In this example, if the conversion is successful, dtype willhold a new reference to a PyArray Descr* object, while input will hold a borrowedreference. Therefore, if this conversion were mixed with another conversion (say toan integer) and the data-type conversion was successful but the integer conversionfailed, then you would need to release the reference count to the data-type objectbefore returning. A typical way to do this is to set dtype to NULL before callingPyArg ParseTuple and then use Py XDECREF on dtype before returning. After the input arguments are processed, the code that actually does the workis written (likely calling other functions as needed). The final step of the C-functionis to return something. If an error is encountered then NULL should be returned(making sure an error has actually been set). If nothing should be returned thenincrement Py None and return it. If a single object should be returned then it isreturned (ensuring that you own a reference to it first). If multiple objects shouldbe returned then you need to return a tuple. The Py BuildValue (format string,c variables...) function makes it easy to build tuples of Python objects from Cvariables. Pay special attention to the difference between ’N’ and ’O’ in the formatstring or you can easily create memory leaks. The ’O’ format string incrementsthe reference count of the PyObject* C-variable it corresponds to, while the ’N’format string steals a reference to the corresponding PyObject* C-variable. Youshould use ’N’ if you ave already created a reference for the object and just wantto give that reference to the tuple. You should use ’O’ if you only have a borrowedreference to an object and need to create one to provide for the tuple.
301 static PyObject* keyword cfunc (PyObject *dummy, PyObject *args, PyObject *kwds) { ... }
The kwds argument holds a Python dictionary whose keys are the names of thekeyword arguments and whose values are the corresponding keyword-argument val-ues. This dictionary can be processed however you see fit. The easiest way tohandle it, however, is to replace the PyArg ParseTuple (args, format string, ad-dresses...) function with a call to PyArg ParseTupleAndKeywords (args, kwds,format string, char *kwlist[], addresses...). The kwlist parameter to this functionis a NULL-terminated array of strings providing the expected keyword arguments.There should be one string for each entry in the format string. Using this functionwill raise a TypeError if invalid keyword arguments are passed in. For more help on this function please see section 1.8 (Keyword Paramters forExtension Functions) of the Extending and Embedding tutorial in the Python doc-umentation.
302are responsible to make sure that Py DECREF(var) is called when the variable is nolonger necessary (and no other function has “stolen” its reference). Also, if you arepassing a Python object to a function that will “steal” the reference, then you needto make sure you own it (or use Py INCREF to get your own reference). You will alsoencounter the notion of borrowing a reference. A function that borrows a referencedoes not alter the reference count of the object and does not expect to “hold on”to the reference. It’s just going to use the object temporarily. When you usePyArg ParseTuple or PyArg UnpackTuple you receive a borrowed referenceto the objects in the tuple and should not alter their reference count inside yourfunction. With practice, you can learn to get reference counting right, but it canbe frustrating at first. One common source of reference-count errors is the Py BuildValue function.Pay careful attention to the difference between the ’N’ format character and the ’O’format character. If you create a new object in your subroutine (such as an outputarray), and you are passing it back in a tuple of return values, then you shouldmost-likely use the ’N’ format character in Py BuildValue. The ’O’ character willincrease the reference count by one. This will leave the caller with two referencecounts for a brand-new array. When the variable is deleted and the reference countdecremented by one, there will still be that extra reference count, and the arraywill never be deallocated. You will have a reference-counting induced memory leak.Using the ’N’ character will avoid this situation as it will return to the caller anobject (inside the tuple) with a single reference count.
1. Ensure you are dealing with a well-behaved array (aligned, in machine byte- order and single-segment) of the correct type and number of dimensions.
2. Get the shape of the array and a pointer to its actual data.
303 3. Pass the data and shape information on to a subroutine or other section of code that actually performs the computation.
4..
PyArray FROM OTF (PyObject*) (PyObject* obj, int typenum, int re- quirements) The object can be any Python object convertable to an ndarray. If the ob- ject con- verted to an array include: 1) any nested sequence object, 2) any object exposing the array interface, 3) any object with an array method
304 : plat- form.. accept- able. If the object passed in does not satisfy this requirements then a copy is made so that thre returned object will satisfy the requirements.
305 these ndarray can use a very generic pointer to memory. This flag al- lows specification of the desired properties of the returned array object. All of the flags are explained in the detailed API chapter. The flags most commonly needed are NPY IN ARRAY, NPY OUT ARRAY, and NPY INOUT ARRAY: NPY IN ARRAY Equivalent to NPY CONTIGUOUS | NPY ALIGNED. This combination of flags is useful for arrays that must be in C-contiguous order and aligned. These kinds of arrays are usually input arrays for some algorithm. NPY OUT ARRAY Equivalent to NPY CONTIGUOUS | NPY ALIGNED | NPY WRITEABLE | NPY Cast to the desired type, even if it can’t be done without losing information. NPY ENSURECOPY Make sure the resulting array is a copy of the original. NPY ENSUREARRAY Make sure the resulting object is an actual ndarray and not a sub-class.
306 NOTE Whether or not an array is byte-swapped is determined by the data-type of the array. Native byte-order arrays are always re- quested by PyArray FROM OTF and so there is no need for a NPY NOTSWAPPED flag in the requirements argument. There is also no way to get a byte-swapped array from this routine.
This function allocates new memory and places it in an ndarray with nd dimen- sions whose shape is determined by the array of at least nd items pointed to by dims. The memory for the array is uninitialized (unless typenum is PyArray OBJECT in which case each element in the array is set to NULL). The typenum argument allows specification of any of the builtin data-types such as PyArray FLOAT or PyArray LONG. The memory for the array can be set to zero if desired using PyArray FILLWBYTE(return object, 0)..
307.
308otherwise must be made.
14.5 ExampleThe following example shows how you might write a wrapper that accepts two inputarguments (that will be converted to an array) and an output argument (that mustbe, ‘‘OOO&’’, &arg1, *arg2, &PyArrayType, .
fail:
309 Py XDECREF(arr1); Py XDECREF(arr2); PyArray XDECREF ERR(oarr); return NULL;}
310Chapter 15
—Marcel Proust
Discovery is seeing what everyone else has seen and thinking what no one else has thought.
—Albert Szent-Gyorgi
311usually cast to PyArrayIterObject* so that its members can be accessed. The onlymembers that are needed are iter->size which contains the total size of thearray, iter->index, which contains the current 1-d index into the array, anditer->dataptr which is a pointer to the data for the current element of thearray. Sometimes it is also useful to access iter->ao which is a pointer to theunderlying ndarray object. After processing data at the current element of the array, the next elementof the array can be obtained using the macro PyArray ITER NEXT(iter).The iteration always proceeds in a C-style contiguous fashion (last index varyingthe fastest). The PyArray ITER GOTO(iter, destination) can be used tojump to a particular point in the array, where destination is an array of npy intpdata-type with space to handle at least the number of dimensions in the underlyingarray. Occasionally it is useful to use PyArray ITER GOTO1D(iter, index)which will jump to the 1-d index given by the value of index. The most commonusage, however, is given in the following example.
You can also use PyArrayIter Check(obj) to ensure you have an iterator ob-ject and PyArray ITER RESET(iter) to reset an iterator object back to thebeginning of the array. It should be emphasized at this point that you may not need the array iteratorif your array is already contiguous (using an array iterator will work but will beslower than the fastest code you could write). The major purpose of array iteratorsis to encapsulate iteration over N-dimensional arrays with arbitrary strides. Theyare used in many, many places in the NumPy source code itself. If you alreadyknow your array is contiguous (Fortran or C), then simply adding the element-sizeto a running pointer variable will step you through the array very efficiently. In
312other words, code like this will probably be faster for you in the contiguous case(assuming doubles).
313is iterate over arrays with the same shape, then simply creating several iteratorobjects is the standard procedure. For example, the following code iterates overtwo arrays assumed to be the same shape and size (actually obj1 just has to haveat least as many total elements as does obj2):
314 ptr1 = PyArray MultiIter DATA(mobj, 0); ptr2 = PyArray MultiIter DATA(mobj, 1); /* code using contents of ptr1 and ptr2 */ PyArray MultiIter NEXT(mobj); }
• broadcasting
• N-dimensional looping
It is not difficult to create your own ufunc. All that is required is a 1-d loop for eachdata-type you want to support. Each 1-d loop must have a specific signature, andonly ufuncs for fixed-size data-types can be used. The function call used to createa new ufunc to work on built-in data-types is given below. A different mechanismis used to register ufuncs for user-defined data-types.
315func) args An array of pointers to the actual data for the input and output arrays. The input arguments are given first followed by the output arguments. dimensions A pointer to the size of the dimension over which this func- tion is looping. steps A pointer to the number of bytes to jump to get to the next ele- ment in this dimension for each of the input and output arguments. data Arbitrary data (extra arguments, function names, etc.) that can be stored with the ufunc and will be passed in when it is called.
static void double add(char *args, npy intp *dimensions, npy intp *steps, voi { corre-
316 sponding
char my sigs[] = \ {NPY INT, NPY INT, NPY CDOUBLE, NPY DOUBLE, NPY DOUBLE, NPY CDOUBLE}; re- sponse to <ufunc name>. doc ). Do not include the function signature or the name as this is generated automatically. check return Not presently used, but this integer value does get set in the structure-member of similar name.
317 ); ...
31815.3.1 Adding the new data-typeTo begin to make use of the new data-type, you need to first define a new Pythontype to hold the scalars of your new data-type. It should be acceptable to inheritfrom one of the array scalars if your new type has a binary compatible layout.This will allow your new data type to have the methods and attributes of arrayscalars. New data-types must have a fixed memory size (if you want to definea data-type that needs a flexible representation, like a variable-precision number,then use a pointer to the object as the data-type). The memory layout of the objectstructure for the new Python type must be PyObject HEAD followed by the fixed-size memory needed for the data-type. For example, a suitable structure for thenew Python type is:
typedef struct { PyObject HEAD; some data type obval; /* the name can be whatever you want */ } PySomeDataTypeObject;
After you have defined a new Python type object, you must then define a newPyArray Descr structure whose typeobject member will contain a pointer to thedata-type you’ve just defined. In addition, the required functions in the “.f” membermust be defined: nonzero, copyswap, copyswapn, setitem, getitem, and cast. Themore functions in the “.f” member you define, however, the more useful the newdata-type will be. It is very important to intialize unused functions to NULL. Thiscan be achieved using PyArray InitArrFuncs(f). Once a new PyArray Descr structure is created and filled with the needed infor-mation and useful functions you call PyArray RegisterDataType(new descr).The return value from this call is an integer providing you with a uniquetype number that specifies your data-type. This type number should be storedand made available by your module so that other modules can use it to recognizeyour data-type (the other mechanism for finding a user-defined data-type number isto search based on the name of the type-object associated with the data-type usingPyArray TypeNumFromName).
319casting function with the data-type you want to be able to cast from. This requireswriting low-level casting functions for each conversion you want to support andthen registering these functions with the data-type descriptor. A low-level castingfunction has the signature.
castfunc (void) (void* from, void* to, npy intp n, void* fromarr, void* toarr)
320with type number totype number. If you are not trying to alter scalar coercionrules, then use PyArray NOSCALAR for the scalarkind argument. If you want to allow your new data-type to also be able to share in the scalarcoercion rules, then you need to specify the scalarkind function in the data-typeobject’s “.f” member to return the kind of scalar the new data-type should be seenas (the value of the scalar is available to that function). Then, you can registerdata-types that can be cast to separately for each scalar kind that may be returnedfrom your user-defined data-type. If you don’t register scalar coercion handling,then all of your user-defined data-types will be seen as PyArray NOSCALAR.
usertype The user-defined type this loop should be indexed under. This number must be a user-defined type or an error occurs.
function The ufunc inner 1-d loop. This function must have the signature as explained in Section 15.2..
32115.4 Subtyping the ndarray in COne of the lesser-used features that has been lurking in Python since 2.2 is theability to sub-class types in C. This facility is one of the important reasons forbasing NumPy off of the Numeric code-base which was already in C. A sub-type inC allows much more flexibility with regards to memory management. Sub-typingin C is not difficult even if you have only a rudimentary understanding of how tocreate new types for Python. While it is easiest to sub-type from a single parenttype, sub-typing from multiple parent types is also possible. Multiple inheritencein C is generally less useful than it is in Python because a restriction on Pythonsub-types is that they have a binary compatible memory layout. Perhaps for thisreason, it is somewhat easier to sub-type from a single parent type. All C-structures corresponding to Python objects must begin with PyOb-ject HEAD (or PyObject VAR HEAD). In the same way, any sub-type must havea C-structure that begins with exactly the same memory layout as the parent type(or all of the parent types in the case of multiple-inheritance). The reason for thisis that Python may attempt to access a member of the sub-type structure as if ithad the parent structure (i.e. it will cast a given pointer to a pointer to the parentstructure and then dereference one of it’s members). If the memory layouts are notcompatible, then this attempt will cause unpredictable behavior (eventually leadingto a memory violation and program crash). One of the elements in PyObject HEAD is a pointer to a type-object structure.A new Python type is created by creating a new type-object structure and popu-lating it with functions and pointers to describe the desired behavior of the type.Typically, a new C-structure is also created to contain the instance-specific informa-tion needed for each object of the type as well. For example, &PyArray Type is apointer to the type-object table for the ndarray while a PyArrayObject* variable isa pointer to a particular instance of an ndarray (one of the members of the ndarraystructure is, in turn, a pointer to the type-object table &PyArray Type). FinallyPyType Ready(<pointer to type object>) must be called for every new Pythontype.
322 1. If needed create a new C-structure to handle each instance of your type. A typical C-structure would be
Notice that the full PyArrayObject is used as the first entry in order to en- sure that the binary layout of instances of the new type is identical to the PyArrayObject.
3..
323allocated and the appropriate instance-structure members are filled in. Finally,the array finalize attribute is looked-up in the object dictionary. If it ispresent and not None, then it can be either a CObject containing a pointer toa PyArray FinalizeFunc or it can be a method taking a single argument (whichcould be None). If the array finalize attribute is a CObject, then the pointer must be apointer to a function with the signature:
The first argument is the newly created sub-type. The second argument (if notNULL) is the “parent” array (if the array was created using slicing or some otheroperation where a clearly-distinguishable parent is present). This routine can doanything it wants to. It should return a -1 on error and 0 otherwise. If the array finalize attribute is not None nor a CObject, then it must bea Python method that takes the parent array as an argument (which could be Noneif there is no parent), and returns nothing. Errors in this method will be caughtand handled.
This attribute allows simple but flexible determination of which sub-type should beconsidered “primary” when an operation involving two or more sub-types arises. Inoperations where different sub-types are being used, the sub-type with the largest array priority attribute will determine the sub-type of the output(s). If twosub-types have the same array prioirty then the sub-type of the first argumentdetermines the output. The default array priority attribute returns a valueof 0.0 for the base ndarray type and 1.0 for a sub-type. This attribute can alsobe defined by objects that are not sub-types of the ndarray and can be used todetermine which array wrap method should be called for the return output.
Any class or type can define this method which should take an ndarray argumentand return an instance of the type. It can be seen as the opposite of the arraymethod. This method is used by the ufuncs (and other NumPy functions) to allowother objects to pass through. For Python >2.4, it can also be used to write adecorator that converts a function that works only with ndarrays to one that workswith any type with array and array wrap methods.
324Chapter 16
—Michel de Montaigne
Duct tape is like the force. It has a light side, and a dark side, and it holds the universe together.
—Carl Zwanzig
Many people like to say that Python is a fantastic glue language. Hopefully,this Chapter will convince you that this is true. The first adopters of Python forscience were typically people who used it to glue together large applicaton codesrunning on super-computers. Not only was it much nicer to code in Python thanin a shell script or Perl, in addition, the ability to easily extend Python made itrelatively easy to create new classes and types specifically adapted to the problemsbeing solved. From the interactions of these early contributors, Numeric emergedas an array-like object that could be used to pass data between these applications. As Numeric has matured and developed into NumPy, people have been able towrite more code directly in NumPy. Often this code is fast-enough for productionuse, but there are still times that there is a need to access compiled code. Eitherto get that last bit of efficiency out of the algorithm or to make it easier to accesswidely-available codes written in C/C++ or Fortran. This chapter will review many of the tools that are available for the purposeof accessing code written in other compiled languages. There are many resources
325available for learning to call other compiled libraries from Python and the purposeof this Chapter is not to make you an expert. The main goal is to make you awareof some of the possibilities so that you will know what to “Google” in order to learnmore. The website also contains a great deal of use-ful information about many of these tools. For example, there is anice description of using several of the tools explained in this chapter at. This link provides several ways to solvethe same problem showing how to use and connect with compiled code to get thebest performance. In the process you can get a taste for several of the approachesthat will be discussed in this chapter.
WARNING Calling C-code from Python can result in Python crashes if you are not careful. None of the approaches in this chapter are immune. You have to know something about the way data is handled by both NumPy and by the third-party library being used.
32616.2 Hand-generated wrappersExtension modules were discussed in Chapter 14.1. The most basic way to interfacewith compiled code is to write an extension module and construct a module methodthat calls the compiled code. For improved readability, your method should takeadvantage of the PyArg ParseTuple call to convert between Python objects and Cdata-types. For standard C data-types there is probably already a built-in converter.For others you may need to write your own converter and use the “O&” format stringwhich allows you to specify a function that will be used to perform the conversionfrom the Python object to whatever C-structures are needed. Once the conversions to the appropriate C-structures and C data-types havebeen performed, the next step in the wrapper is to call the underlying function.This is straightforward if the underlying function is in C or C++. However, in orderto call Fortran code you must be familiar with how Fortran subroutines are calledfrom C/C++ using your compiler and platform. This can vary somewhat platformsand compilers (which is another reason f2py makes life much simpler for interfacingFortran code) but generally involves underscore mangling of the name and the factthat all variables are passed by reference (i.e. all arguments are pointers). The advantage of the hand-generated wrapper is that you have complete controlover how the C-library gets used and called which can lead to a lean and tight in-terface with minimal over-head. The disadvantage is that you have to write, debug,and maintain C-code, although most of it can be adapted using the time-honoredtechnique of “cutting-pasting-and-modifying” from other extension modules. Be-cause, the procedure of calling out to additional C-code is fairly regimented, code-generation procedures have been developed to make this process easier. One of thesecode-generation techniques is distributed with NumPy and allows easy integrationwith Fortran and (simple) C code. This package, f2py, will be covered briefly in thenext session.
16.3 f2pyF2py allows you to automatically construct an extension module that interfaces toroutines in Fortran 77/90/95 code. It has the ability to parse Fortran 77/90/95 codeand automatically generate Python signatures for the subroutines it encounters,or you can guide how the subroutine interfaces with Python by constructing aninterface-defintion-file (or modifying the f2py-produced one).
32716.3.1 Creating source for a basic extension moduleProbably the easiest way to introduce f2py is to offer a simple example. Here is oneofin a third. The memory for all three arrays must be provided by the calling routine.A very basic interface to this routine can be automatically generated by f2py:
You should be able to run this command assuming your search-path is set-up prop-erly. This command will produce an extension module named addmodule.c in thecurrent directory. This extension module can now be compiled and used fromPython just like any other extension module.
This command leaves a file named add.<ext> in the current directory (where <ext>is the appropriate extension for a python extension module on your platform — so,pyd, etc.). This module may then be imported from Python. It will contain amethod for each subroutin in add (zadd, cadd, dadd, sadd). The docstring of eachmethod contains information about how the module method may be called:
328 >>> import add >>> print add.zadd. doc zadd - Function signature: zadd(a,b,c,n) Required arguments: a : input rank-1 array(’D’) with bounds (*) b : input rank-1 array(’D’) with bounds (*) c : input rank-1 array(’D’) with bounds (*) n : input int
>>> add.zadd([1,2,3],[1,2],[3,4],1000)
will cause a program crash on most systems. Under the covers, the lists are beingconverted to proper arrays but then the underlying add loop is told to cycle waybeyond the borders of the allocated memory. In order to improve the interface, directives should be provided. This is accom-plished by constructing an interface definition file. It is usually best to start fromthe interface file that f2py can produce (where it gets its default behavior from).To get f2py to generate the interface file use the -h option:
This command leaves the file add.pyf in the current directory. The section of thisfile corresponding to zadd is:
329 integer :: n end subroutine zadd
By placing intent directives and checking code, the interface can be cleaned up quitea bit until the Python module method is both easier to use and more robust.
The intent directive, intent(out) is used to tell f2py that c is an output variableand should be created by the interface before being passed to the underlying code.The intent(hide) directive tells f2py to not allow the user to specify the variable, n,but instead to get it from the size of a. The depend(a) directive is necessary to tellf2py that the value of n depends on the input a (so that it won’t try to create thevariable n until the variable a is created). The new interface has docstring:
>>> add.zadd([1,2,3],[4,5,6]) array([ 5.+0.j, 7.+0.j, 9.+0.j])
330
The resulting signature for the function add.zadd is exactly the same one that wascreated previously. If the original source code had contained A(N) instead of A(*)and so forth with B and C, then I could obtain (nearly) the same interface simplyby placing the INTENT(OUT) :: C comment line in the source code. The onlydifference is that N would be an optional input that would default to the length ofA.
SUBROUTINE DFILTER2D(A,B,M,N) C DOUBLE PRECISION A(M,N) DOUBLE PRECISION B(M,N)
331
This will produce an extension module named filter.so in the current directory witha method named dfilter2d that returns a filtered version of the input.
The source string can be any valid Fortran code. If you want to save the extension-module source code then a suitable file-name can be provided by the source fnkeyword to the compile function.
33216.3.7 Automatic extension module generationIf you want to distribute your f2py extension module, then you only need to includethe .pyf file and the Fortran code. The distutils extensions in NumPy allow you todefine an extension module entirely in terms of this interface file. A valid setup.pyfile allowing distribution of the add.f module (as part of the package f2py examplesso that it would be loaded as f2py examples.add) is
if name == ’ main ’: from numpy.distutils.core import setup setup(**configuration(top path=’’).todict())
assuming you have the proper permissions to write to the main site-packages direc-tory for the version of Python you are using. For the resulting package to work, youneed to create a file named init .py (in the same directory as add.pyf). Noticethe extension module is defined entirely in terms of the “add.pyf” and “add.f” files.The conversion of the .pyf file to a .c file is handled by numpy.disutils.
16.3.8 ConclusionThe interface definition file (.pyf) is how you can fine-tune the interface be-tween Python and Fortran. There is decent documentation for f2py found in thenumpy/f2py/docs directory where-ever NumPy is installed on your system (usuallyunder site-packages). There is also more information on using f2py (including howto use it to wrap C codes) at under the “UsingNumPy with Other Languages” heading. The f2py method of linking compiled code is currently the most sophisticated andintegrated approach. It allows clean separation of Python with compiled code whilestill allowing for separate distribution of the extension module. The only draw-backis that it requires the existence of a Fortran compiler in order for a user to install
333the code. However, with the existence of the free-compilers g77, gfortran, and g95,as well as high-quality commerical compilers, this restriction is not particularlyonerous. In my opinion, Fortran is still the easiest way to write fast and clearcode for scientific computing. It handles complex numbers, and multi-dimensionalindexing in the most straightforward way. Be aware, however, that some Fortrancompilers will not be able to optimize code as well as good hand-written C-code.
16.4 weaveWeave is a scipy package that can be used to automate the process of extendingPython with C/C++ code. It can be used to speed up evaluation of an arrayexpression that would otherwise create temporary variables, to directly “inline”C/C++ code into Python, or to create a fully-named extension module. You musteither install scipy or get the weave package separately and install it using thestandard python setup.py install. You must also have a C/C++-compiler installedand useable by Python distutils in order to use weave. Somewhat dated, but still useful documentation for weave can be found at thelink. There are also many examples found in the examplesdirectory which is installed under the weave directory in the place where weave isinstalled on your system.
334 d = 4*a + 5*a*b + 6*b*c
where a, b, and c are all arrays of the same type and shape. When the data-type isdouble-precision and the size is 1000x1000, this expression takes about 0.5 secondsto compute on an 1.1Ghz AMD Athlon machine. When this expression is executedinstead using blitz:
execution time is only about 0.20 seconds (about 0.14 seconds spent in weave andthe rest in allocating space for d). Thus, we’ve sped up the code by a factor of 2using only a simnple command (weave.blitz). Your mileage may vary, but factorsof 2-8 speed-ups are possible with this very simple technique. If you are interested in using weave in this way, then you should also look atscipy.numexpr which is another similar way to speed up expressions by eliminat-ing the need for temporary variables. Using numexpr does not require a C/C++compiler.
code = r""" int i; py::tuple results(2); for (i=0; i<a.length(); i++) { a[i] = i; } results[0] = 3.0; results[1] = 4.0; return val = results;
335 """ a = [None]*10 res = weave.inline(code,[’a’])
The C++ code shown in the code string uses the name ’a’ to refer to the Pythonlist that is passed in. Because the Python List is a mutable type, the elements ofthe list itself are modified by the C++ code. A set of C++ classes are used toaccess Python objects using simple syntax. The main advantage of using C-code, however, is to speed up processing on anarray of data. Accessing a NumPy array in C++ code using weave, depends onwhat kind of type converter is chosen in going from NumPy arrays to C++ code.The default converter creates 5 variables for the C-code for every NumPy arraypassed in to weave.inline. The following table shows these variables which can allbe used in the C++ code. The table assumes that myvar is the name of the arrayin Python with data-type <dtype> (i.e. float64, float32, int8, etc.)
The in-lined code can contain references to any of these variables as well asto the standard macros MYVAR1(i), MYVAR2(i,j), MYVAR3(i,j,k), and MY-VAR4(i,j,k,l). These name-based macros (they are the Python name capitalizedfollowed by the number of dimensions needed) will de-reference the memory for thearray at the given location with no error checking (be-sure to use the correct macroand ensure the array is aligned and in correct byte-swap order in order to get usefulresults). The following code shows how you might use these variables and macrosto
336 + (A2(i-1,j-1) + A2(i-1,j+1) + A2(i+1,j-1) + A2(i+1,j+1))*0.25 } }
The above code doesn’t have any error checking and so could fail with a Pythoncrash if, a had the wrong number of dimensions, or b did not have the same shapeas a. However, it could be placed inside a standard Python function with thenecessary error checking to produce a robust but fast subroutine. One final note about weave.inline: if you have additional code you want to in-clude in the final extension module such as supporting function calls, include stat-ments, etc. you can pass this code in as a string using the keyword support code:weave.inline(code, variables, support code=support). If you needthe extension module to link against an additional library then you can also passin distutils-style keyword arguments such as library dirs, libraries, and/or run-time library dirs which point to the appropriate libraries and directories.
337 5. when all the functions are added, compile the extension with its .compile() method.
Several examples are available in the examples directory where weave is installed onyour system. Look particularly at ramp2.py, increment example.py and fibonacii.py
16.4.4 ConclusionWeave is a useful tool for quickly routines in C/C++ and linking them into Python.It’s caching-mechanism allows for on-the-fly compilation which makes it particularlyattractive for in-house code. Because of the requirement that the user have a C++-compiler, it can be difficult (but not impossible) to distribute a package that usesweave to other users who don’t have a compiler installed. Of course, weave could beused to construct an extension module which is then distributed in the normal way( using a setup.py file). While you can use weave to build larger extension moduleswith many methods, creating methods with a variable-number of arguments is notpossible. Thus, for a more sophisticated module, you will still probably want aPython-layer that calls the weave-produced extension.
16.5 PyrexPyrex is a way to write C-extension modules using Python-like syntax. It is aninteresting way to generate extension modules that is growing in popularity, par-ticularly among people who have rusty or non-existent C-skills. It does require theuser to write the “interface” code and so is more time-consuming than SWIG orf2py if you are trying to interface to a large library of code. However, if you arewriting an extension module that will include quite a bit of your own algorithmiccode, as well, then Pyrex is a good match. A big weakness perhaps is the inabilitytocalled build ext which lets you build an extension module from a .pyx source. Thus,you could write in a setup.py file
338 import numpy py ext = Extension(’mine’, [’mine.pyx’], include dirs=[numpy.get include()])
setup(name=’mine’, description=’Nothing’, ext modules=[pyx ext], cmdclass = {’build ext’:build ext})
Adding the NumPy include directory is, of course, only necessary if you are usingNumPy arrays in the extension module (which is what I assume you are using Pyrexfor). The distutils extensions in NumPy also include support for automaticallyproducing the extension-module and linking it from a .pyx file. It works so thatif the user does not have Pyrex installed, then it looks for a file with the samefile-name but a .c extension which it then uses instead of trying to produce the .cfile again. Pyrex does not natively understand NumPy arrays. However, it is not diffi-cult to include information that lets Pyrex deal with them usefully. In fact, thenumpy.random.mtrand module was written using Pyrex so an example of Pyrex us-age is already included in the NumPy source distribution. That experience led to thecreation of a standard c numpy.pxd file that you can use to simplify interacting withNumPy array objects in a Pyrex-written extension. The file may not be complete(it wasn’t at the time of this writing). If you have additions you’d like to contribute,please send them. The file is located in the .../site-packages/numpy/doc/pyrex di-rectory where you have Python installed. There is also an example in that directoryof using Pyrex to construct a simple extension module. It shows that Pyrex looksa lot like Python but also contains some new syntax that is necessary in order toget C-like speed. If you just use Pyrex to compile a standard Python module, then you will geta C-extension module that runs either as fast or, possibly, more slowly than theequivalent Python module. Speed increases are possible only when you use cdef tostatically define C variables and use a special construct to create for loops:
cdef int i for i from start <= i < stop
Let’s look at two examples we’ve seen before to see how they might be implementedusing Pyrex. These examples were compiled into extension modules using Pyrex-0.9.3.1.
33916.5.1 Pyrex-addHere is part of a Pyrex-file I named add.pyx which implements the add functionswe previously implemented using f2py:
cimport c numpy from c numpy cimport import array, ndarray, npy intp, npy cdouble, \ npy cfloat, NPY DOUBLE, NPY CDOUBLE, NPY FLOAT, \ NPY CFLOAT
This module shows use of the cimport statement to load the definitions from thec numpy.pxd file. As shown, both versions of the import statement are supported.It also shows use of the NumPy C-API to construct NumPy arrays from arbitraryinput objects. The array c is created using PyArray SimpleNew. Then the c-arrayis filled by addition. Casting to a particiular data-type is accomplished using <cast*>. Pointers are de-referenced with bracket notation and members of structures areaccessed using ’.’ notation even if the object is techinically a pointer to a structure.
340The use of the special for loop construct ensures that the underlying code will havea similar C-loop so the addition calculation will proceed quickly. Notice that wehave not checked for NULL after calling to the C-API — a cardinal sin when writingC-code. For routines that return Python objects, Pyrex inserts the checks for NULLinto the C-code for you and returns with failure if need be. There is also a way toget Pyrex to automatically check for exceptions when you call functions that don’treturn Python objects. See the documentation of Pyrex for details.
16.5.2 Pyrex-filterThe two-dimensional example we created using weave is a bit uglierto implementin Pyrex because two-dimensional indexing using Pyrex is not as simple. But, it isstraightforward (and possibly faster because of pre-computed indices). Here is thePyrex-file I named image.pyx.
cimport c numpy from c numpy cimport import array, ndarray, npy intp,\ NPY DOUBLE, NPY CDOUBLE, \ NPY FLOAT, NPY CFLOAT, NPY ALIGNED \
341computations are done only as needed. However, it is not particularly easy tounderstand what is happening. A 2-d image, in, can be filtered using this codevery quickly using
import image out = image.filter(in)
16.5.3 ConclusionThere are several disadvantages of using Pyrex:
1. The syntax for Pyrex can get a bit bulky, and it can be confusing at first to understand what kind of objects you are getting and how to interface them with C-like constructs.
342 (a) Pyrex failing to generate the extension module source code, (b) Compiler failure while generating the extension module binary due to incorrect C syntax, (c) Python failure when trying to use the module.
3. It is easy to lose a clean separation between Python and C which makes re- using your C-code for other non-Python-related projects more difficult.
5. The C-code generated by Prex is hard to read and modify (and typically compiles with annoying but harmless warnings).
Writing a good Pyrex extension module still takes a bit of effort because not onlydoes it require (a little) familiarity with C, but also with Pyrex’s brand of Python-mixed-with C. One big advantage of Pyrex-generated extension modules is thatthey are easy to distribute using distutils. In summary, Pyrex is a very capable toolfor either gluing C-code or generating an extension module quickly and should notbe over-looked. It is especially useful for people that can’t or won’t write C-codeor Fortran code. But, if you are already able to write simple subroutines in C orFortran, then I would use one of the other approaches such as f2py (for Fortran),ctypes (for C shared-libraries), or weave (for inline C-code).
16.6 ctypesCtypes is a python extension module (downloaded separately for Python <2.5 andincluded with Python 2.5) that allows you to call an arbitrary function in a sharedlibrary directly from Python. This approach allows you to interface with C-codedirectly from Python. This opens up an enormous number of libraries for use fromPython. The drawback, however, is that coding mistakes can lead to ugly programcrashes very easily (just as can happen in C) because there is little type or boundschecking done on the parameters. This is especially true when array data is passedin as a pointer to a raw memory location. The responsibility is then on you that thesubroutine will not access memory outside the actual array area. But, if you don’tmind living a little dangerously ctypes can be an effective tool for quickly takingadvantage of a large shared library (or writing extended functionality in your ownshared library).
343 Because the ctypes approach exposes a raw interface to the compiled code it isnot always tolerant of user mistakes. Robust use of the ctypes module typicallyinvolves an additional layer of Python code in order to check the data types andarray bounds of objects passed to the underlying subroutine. This additional layerof checking (not to mention the conversion from ctypes objects to C-data-typesthat ctypes itself performs), will make the interface slower than a hand-writtenextension-module interface. However, this overhead should be neglible if the C-routine being called is doing any significant amount of work. If you are a greatPython programmer with weak C-skills, ctypes is an easy way to write a usefulinterface to a (shared) library of compiled code. To use c-types you must
4. Call the function from the library with the ctypes arguments.
• A shared library must be compiled in a special way (e.g. using the -shared flag with gcc).
• On some platforms (e.g. Windows) , a shared library requires a .def file that specifies the functions to be exported. For example a mylib.def file might contain.
LIBRARY mylib.dll EXPORTS cool function1 cool function2
344There is no standard way in Python distutils to create a standard shared library(an extension module is a “special” shared library Python understands) in a cross-platform manner. Thus, a big disadvantage of ctypes at the time of writing this bookis that it is difficult to distribute in a cross-platform manner a Python extensionthat uses c-types and includes your own code which should be compiled as a sharedlibrary on the users system.
However, on Windows accessing an attribute of the cdll method will load the firstDLL by that name found in the current directory or on the PATH. Loading theabsolute path name requires a little finesse for cross-platform work since the exten-sion of shared libraries varies. There is a ctypes.util.find library utilityavailable that can simplify the process of finding the library to load but it is notfoolproof. Complicating matters, different platforms have different default exten-sions used by shared libraries (e.g. .dll – Windows, .so – Linux, .dylib – Mac OSX). This must also be taken into account if you are using c-types to wrap code thatneeds to work on several platforms. NumPy provides a convenience function called ctypeslib.load library(name,path). This function takes the name of the shared library (including any prefixlike ’lib’ but excluding the extension) and a path where the shared library canbe located. It returns a ctypes library object or raises an OSError if the librarycannot be found or raises an ImportError if the ctypes module is not available.(Windows users: the ctypes library object loaded using load library is alwaysloaded assuming cdecl calling convention. See the ctypes documentation underctypes.windll and/or ctypes.oledll for ways to load libraries under other callingconventions). The functions in the shared library are available as attributes of thectypes library object (returned from ctypeslib.load library) or as items usinglib[’func name’] syntax. The latter method for retrieving a function name is par-ticularly useful if the function name contains characters that are not allowable inPython variable names.
34516.6.3 Converting argumentsPython ints/longs, strings, and unicode objects are automatically converted asneeded to equivalent c-types arguments The None object is also converted auto-matically to a NULL pointer. All other Python objects must be converted toctypes-specific types. There are two ways around this restriction that allow c-typesto integrate with other objects.
1. Don’t set the argtypes attribute of the function object and define an as parameter method for the object you want to pass in. The as parameter method must return a Python int which will be passed directly to the function.
2. Set the argtypes attribute to a list whose entries contain objects with a class- method named from param that knows how to convert your object to an object that ctypes can understand (an int/long, string, unicode, or object with the as parameter attribute).
NumPy uses both methods with a preference for the second method because itcan be safer. The ctypes attribute of the ndarray returns an object that has an as parameter attribute which returns an integer representing the address of thendarray to which it is associated. As a result, one can pass this ctypes attributeobject directly to a function expecting a pointer to the data in your ndarray. Thecaller must be sure that the ndarray object is of the correct type, shape, and hasthe correct flags set or risk nasty crashes if the data-pointer to inappropriate arraysare passsed in. To implement the second method, NumPy provides the class-factory functionndpointer in the ctypeslib module. This class-factory function produces an ap-propriate class that can be placed in an argtypes attribute entry of a ctypes function.The class will contain a from param method which ctypes will use to convert anyndarray passed in to the function to a ctypes-recognized object. In the process,the conversion will perform checking on any properties of the ndarray that werespecified by the user in the call to ndpointer. Aspects of the ndarray that can bechecked include the data-type, the number-of-dimensions, the shape, and/or thestate of the flags on any array passed. The return value of the from param methodis the ctypes attribute of the array which (because it contains the as parameterattribute pointing to the array data area) can be used by ctypes directly. The ctypes attribute of an ndarray is also endowed with additional attributesthat may be convenient when passing additional information about the array intoa ctypes function. The attributes data, shape, and strides can provide c-types
346compatible types corresponding to the data-area, the shape, and the strides of thearray. The data attribute reutrns a c void p representing a pointer to the dataarea. The shape and strides attributes each return an array of ctypes integers (orNone representing a NULL pointer, if a 0-d array). The base ctype of the array is actype integer of the same size as a pointer on the platform. There are also methodsdata as(<ctype>), shape as(<base ctype>), and strides as(<base ctype>). Thesereturn the data as a ctype object of your choice and the shape/strides arrays usingan underlying base type of your choice. For convenience, the ctypeslib modulealso contains c intp as a ctypes integer data-type whose size is the same as the sizeof c void p on the platform (it’s value is None if ctypes is not installed).
func1.restype = None
As previously discussed, you can also set the argtypes attribute of the function inorder to have ctypes check the types of the input arguments when the function iscalled. Use the ndpointer factory function to generate a ready-made class for data-type, shape, and flags checking on your new function. The ndpointer function hasthe signature
347 saferto call a C-function using ctypes and the data-area of an ndarray. You may stillwant to wrap the function in an additional Python wrapper to make it user-friendly(hiding some obvious arguments and making some arguments output arguments).In this process, the requires function in NumPy may be useful to return the rightkind of array from a given input.
with similar code for cadd, dadd, and sadd that handles complex float, double, andfloat data-types, respectively:
348 a++; b++; c++; } } void dadd(double *a, double *b, double *c, long n) { while (n--) { *c++ = *a++ + *b++; } } void sadd(float *a, float *b, float *c, long n) { while (n--) { *c++ = *a++ + *b++; } }] + \
349 a[rm1+cp1] + a[rm1+cp1])*0.25; } } }
A possible advantage this code has over the Fortran-equivalent code is that it takesarbitrarily strided (i.e. non-contiguous arrays) and may also run faster depending onthe optimization capability of your compiler. But, it is a obviously more complicatedthan the simple code in filter.f. This code must be compiled into a shared library.On my Linux system this is accomplished using
Which creates a shared library named code.so in the current directory. On Windowsdon’t forget to either add declspec(dllexport) in front of void on the line preceedingeach function definition, or write a code.def file that lists the names of the functionsto be exported. A suitable Python interface to this shared library should be constructed. To dothis create a file named interface.py with the following lines at the top:
import numpy as N import os
350 ’writeable’), N.ctypeslib.c intp]
This code loads the shared library named code.<ext> located in the same path asthis file. It then adds a return type of void to the functions contained in the library.It also adds argument checking to the functions in the library so that ndarrays canbe passed as the first three arguments along with an integer (large enough to holda pointer on the platform) as the fourth argument. Setting up the filtering function is similar and allows the filtering function tobe called with ndarray arguments as the first two arguments and with pointers tointegers (large enough to handle the strides and shape of an ndarray) as the lasttwo
351
16.6.6 ConclusionUsing ctypes is a powerful way to connect Python with arbitrary C-code. It’sadvantages for extending Python include
352 • Very little support for C++ code and it’s different library-calling conventions. You will probably need a C-wrapper around C++ code to use with ctypes (or just use Boost.Python instead).
16.7.1 SWIGSimplified Wrapper and Interface Generator (SWIG) is an old and fairly stablemethod for wrapping C/C++-libraries to a large variety of other languages. It doesnot specifically understand NumPy arrays but can be made useable with NumPythrough the use of typemaps. There are some sample typemaps in the numpy/-doc/swig directory under numpy.i along with an example module that makes useof them. SWIG excels at wrapping large C/C++ libraries because it can (almost)parse their headers and auto-produce an interface. Technically, you need to generatea .i file that defines the interface. Often, however, this .i file can be parts of theheader itself. The interface usually needs a bit of tweaking to be very useful. Thisability to parse C/C++ headers and auto-generate the interface still makes SWIGa useful approach to adding functionalilty from C/C++ into Python, despite the
353other methods that have emerged that are more targeted to Python. SWIG can ac-tually target extensions for several languages, but the typemaps usually have to belanguage-specific. Nonetheless, with modifications to the Python-specific typemaps,SWIG can be used to interface a library with other languages such as Perl, Tcl, andRuby. My experience with SWIG has been generally positive in that it is relativelyeasy to use and quite powerful. I used to use it quite often before becoming moreproficient at writing C-extensions. However, I struggled writing custom interfaceswith SWIG because it must be done using the concept of typemaps which are notPython specific and are written in a C-like syntax. Therefore, I tend to prefer othergluing strategies and would only attempt to use SWIG to wrap a very-large C/C++library. Nonetheless, there are others who use SWIG quite happily.
16.7.2 SIPSIP is another tool for wrapping C/C++ libraries that is Python specific and ap-pears to have very good support for C++. Riverbank Computing developed SIP inorder to create Python bindings to the QT library. An interface file must be writtento generate the binding, but the interface file looks a lot like a C/C++ header file.While SIP is not a full C++ parser, it understands quite a bit of C++ syntax aswell as its own special directives that allow modification of how the Python bindingis accomplished. It also allows the user to define mappings between Python typesand C/C++ structrues and classes.
35416.7.4 InstantThis is a relatively new package (called pyinstant at sourceforge) that builds on topof SWIG to make it easy to inline C and C++ code in Python very much like weave.However, Instant builds extension modules on the fly with specific module namesand specific method names. In this repsect it is more more like f2py in its behavior.The extension modules are built on-the fly (as long as the SWIG is installed). Theycan"], import test2b ext
355 a = numpy.arange(1000) b = numpy.arange(1000) d = test2b ext.add(a,b)
16.7.5 PyInlineThis is a much older module that allows automatic building of extension modulesso that C-code can be included with Python code. It’s latest release (version 0.03)was in 2001, and it appears that it is not being updated.
16.7.6 PyFortPyFort is a nice tool for wrapping Fortran and Fortran-like C-code into Pythonwith support for Numeric arrays. It was written by Paul Dubois, a distinguishedcomputer scientist and the very first maintainer of Numeric (now retired). It isworth mentioning in the hopes that somebody will update PyFort to work withNumPy arrays as well which now support either Fortran or C-style contiguousarrays.
356Chapter 17
Code Explanations
—George Santayana
—Unknown
This Chapter attempts to explain the logic behind some of the new pieces ofcode. The purpose behind these explanations is to enable somebody to be ableto understand the ideas behind the implementation somewhat more easily thanjust staring at the code. Perhaps in this way, the algorithms can be improved on,borrowed from, and/or optimized.
357accepts strides, you just have to use (char *) pointers because strides are in unitsof bytes. Keep in mind also that strides do not have to be unit-multiples of theelement size. Also, remember that if the number of dimensions of the array is 0(sometimes called a rank-0 array), then the strides and dimensions variables areNULL. Besides the structural information contained in the strides and dimensions mem-bers of the PyArrayObject, the flags contain important information about how thedata may be accessed. In particular, the NPY ALIGNED flag is set when the mem-ory is on a suitable boundary according to the data-type array. Even if you havea contiguous chunk of memory, you cannot just assume it is safe to dereference adata-type-specific pointer to an element. Only if the NPY ALIGNED flag is setis this a safe operation (on some platforms it will work but on others, like Solaris,it will cause a bus error). The NPY WRITEABLE should also be ensured if youplan on writing to the memory area of the array. It is also possible to obtain apointer to an unwriteable memory area. Sometimes, writing to the memory areawhen the NPY WRITEABLE flag is not set will just be rude. Other times it cancause program crashes (e.g. a data-area that is a read-only memory-mapped file).
35817.3 N-D IteratorsA very common operation in much of NumPy code is the need to iterate over allthe elements of a general, strided, N-dimensional array. This operation of a general-purpose N-dimensional loop is abstracted in the notion of an iterator object. Towrite an N-dimensional loop, you only have to create an iterator object from anndarray, work with the dataptr member of the iterator object structure and callthe macro PyArray ITER NEXT(it) on the iterator object to move to the nextelement. The “next” element is always in C-contiguous order. The macro works byfirst special casing the C-contiguous, 1-d, and 2-d cases which work very simply. For the general case, the iteration works by keeping track of a list of coordinatecounters in the iterator object. At each iteration, the last coordinate counter isincreased (starting from 0). If this counter is smaller then one less than the size ofthe array in that dimension (a pre-computed and stored value), then the counteris increased and the dataptr member is increased by the strides in that dimensionand the macro ends. If the end of a dimension is reached, the counter for the lastdimension is reset to zero and the dataptr is moved back to the beginning of that di-mension by subtracting the strides value times one less than the number of elementsin that dimension (this is also pre-computed and stored in the backstrides memberof the iterator object). In this case, the macro does not end, but a local dimensioncounter is decremented so that the next-to-last dimension replaces the role thatthe last dimension played and the previously-described tests are executed again onthe next-to-last dimension. In this way, the dataptr is adjusted appropriately forarbitrary striding. The coordinates member of the PyArrayIterObject structure maintains thecurrent N-d counter unless the underlying array is C-contiguous in which casethe coordinate counting is by-passed. The index member of the PyArrayIterOb-ject keeps track of the current flat index of the iterator. It is updated by thePyArray ITER NEXT macro.
17.4 BroadcastingIn Numeric, broadcasting was implemented in several lines of code buried deep inufuncobject.c. In NumPy, the notion of broadcasting has been abstracted so thatit can be performed in multiple places. Broadcasting is handled by the functionPyArray Broadcast. This function requires a PyArrayMultiIterObject (or some-thing that is a binary equivalent) to be passed in. The PyArrayMultiIterObject
359keeps track of the broadcasted number of dimensions and size in each dimensionalong with the total size of the broadcasted result. It also keeps track of the numberof arrays being broadcast and a pointer to an iterator for each of the arrays beingbroadcasted. The PyArray Broadcast function takes the iterators that have already been de-fined and uses them to determine the broadcast shape in each dimension (to createthe iterators at the same time that broadcasting occurs then use the PyMuliIter Newfunction). Then, the iterators are adjusted so that each iterator thinks it is iterat-ing over an array with the broadcasted size. This is done by adjusting the iteratorsnumber of dimensions, and the shape in each dimension. This works because theiterator strides are also adjusted. Broadcasting only adjusts (or adds) length-1dimensions. For these dimensions, the strides variable is simply set to 0 so thatthe data-pointer for the iterator over that array doesn’t move as the broadcastingoperation operates over the extended dimension. Broadcasting was always implemented in Numeric using 0-valued strides for theextended dimensions. It is done in exactly the same way in NumPy. The big dif-ference is that now the array of strides is kept track of in a PyArrayIterObject, theiterators involved in a broadcasted result are kept track of in a PyArrayMultiIter-Object, and the PyArray BroadCast call implements the broad-casting rules.
36017.6 Advanced (“Fancy”) IndexingThe implementation of advanced indexing represents some of the most difficultcode to write and explain. In fact, there are two implementations of advancedindexing. The first works only with 1-d arrays and is implemented to handle ex-pressions involving a.flat[obj]. The second is general-purpose that works for arraysof “arbitrary dimension” (up to a fixed maximum). The one-dimensional indexingapproaches were implemented in a rather straightforward fashion, and so it is thegeneral-purpose indexing code that will be the focus of this section. There is a multi-layer approach to indexing because the indexing code can attimes return an array scalar and at other times return an array. The functions with“ nice” appended to their name do this special handling while the function withoutthe nice appendage always return an array (perhaps a 0-dimensional array). Somespecial-case optimizations (the index being an integer scalar, and the index beinga tuple with as many dimensions as the array) are handled in array subscript nicefunction which is what Python calls when presented with the code “a[obj].” Theseoptimizations allow fast single-integer indexing, and also ensure that a 0-dimensionalarray is not created only to be discarded as the array scalar is returned instead.This provides significant speed-up for code that is selecting many scalars out of anarray (such as in a loop). However, it is still not faster than simply using a list tostore standard Python scalars, because that is optimized by the Python interpreteritself. After these optimizations, the array subscript function itself is called. Thisfunction first checks for field selection which occurs when a string is passed as theindexing object. Then, 0-d arrays are given special-case consideration. Finally, thecode determines whether or not advanced, or fancy, indexing needs to be performed.If fancy indexing is not needed, then standard view-based indexing is performedusing code borrowed from Numeric which parses the indexing object and returnsthe offset into the data-buffer and the dimensions necessary to create a new view ofthe array. The strides are also changed by multiplying each stride by the step-sizerequested along the corresponding dimension.
361an array, then fancy indexing is automatically assumed. If the indexing objectis any other kind of sequence, then fancy-indexing is assumed by default. Thisis over-ridden to simple indexing if the sequence contains any slice, newaxis, orEllipsis objects, and no arrays or additional sequences are also contained in thesequence. The purpose of this is to allow the construction of “slicing” sequenceswhich is a common technique for building up code that works in arbitrary numbersof dimensions.
The first step is to convert the indexing objects into a standard form where iteratorsare created for all of the index array inputs and all Boolean arrays are convertedto equivalent integer index arrays (as if nonzero(arr) had been called). Finally, allinteger arrays are replaced with the integer 0 in the indexing object and all of theindex-array iterators are “broadcast” to the same shape.
When the mapping object is created it does not know which array it will be usedwith so once the index iterators are constructed during mapping-object creation,the next step is to associate these iterators with a particular ndarray. This processinterprets any ellipsis and slice objects so that the index arrays are associated withthe appropriate axis (the axis indicated by the iteraxis entry corresponding to theiterator for the integer index array). This information is then used to check theindices to be sure they are within range of the shape of the array being indexed.The presence of ellipsis and/or slice objects implies a sub-space iteration that is
362accomplished by extracting a sub-space view of the array (using the index objectresulting from replacing all the integer index arrays with 0) and storing the infor-mation about where this sub-space starts in the mapping object. This is used laterduring mapping-object iteration to select the correct elements from the underlyingarray.
After the mapping object is successfully bound to a particular array, the mappingobject contains the shape of the resulting item as well as iterator objects that willwalk through the currently-bound array and either get or set its elements as needed.The walk is implemented using the PyArray MapIterNext function. This functionsets the coordinates of an iterator object into the current array to be the nextcoordinate location indicated by all of the indexing-object iterators while adjusting,if necessary, for the presence of a sub-space. The result of this function is that thedataptr member of the mapping object structure is pointed to the next position inthe array that needs to be copied out or set to some value. When advanced indexing is used to extract an array, an iterator for the new arrayis constructed and advanced in phase with the mapping object iterator. Whenadvanced indexing is used to place values in an array, a special “broadcasted”iterator is constructed from the object being placed into the array so that it willonly work if the values used for setting have a shape that is “broadcastable” to theshape implied by the indexing object.
36317.7.1 SetupEvery ufunc calculation involves some overhead related to setting up the calcula-tion. The practical significance of this overhead is that even though the actualcalculation of the ufunc is very fast, you will be able to write array and type-specific code that will work faster for small arrays than the ufunc. In particular,using ufuncs to perform many calculations on 0-d arrays will be slower than otherPython-based solutions (the silently-imported scalarmath module exists preciselyto give array scalars the look-and-feel of ufunc-based calculations with significantlyreduced overhead). When a ufunc is called, many things must be done. The information collectedfrom these setup operations is stored in a loop-object. This loop object is a C-structure (that could become a Python object but is not initialized as such becauseit is only used internally). This loop object has the layout needed to be used withPyArray Broadcast so that the broadcasting can be handled in the same way as itis handled in other sections of code. The first thing done is to look-up in the thread-specific global dictionary thecurrent values for the buffer-size, the error mask, and the associated error object.The state of the error mask controls what happens when an error-condiction isfound. It should be noted that checking of the hardware error flags is only performedafter each 1-d loop is executed. This means that if the input and output arrays arecontiguous and of the correct type so that a single 1-d loop is performed, thenthe flags may not be checked until all elements of the array have been calcluated.Looking up these values in a thread-specific dictionary takes time which is easilyignored for all but very small arrays. After checking, the thread-specific global variables, the inputs are evaluated todetermine how the ufunc should proceed and the input and output arrays are con-structed if necessary. Any inputs which are not arrays are converted to arrays (usingcontext if necessary). Which of the inputs are scalars (and therefore converted to0-d arrays) is noted. Next, an appropriate 1-d loop is selected from the 1-d loops available to theufunc based on the input array types. This 1-d loop is selected by trying to matchthe signature of the data-types of the inputs against the available signatures. Thesignatures corresponding to built-in types are stored in the types member of theufunc structure. The signatures corresponding to user-defined types are stored ina linked-list of function-information with the head element stored as a CObjectin the userloops dictionary keyed by the data-type number (the first user-defined
364type in the argument list is used as the key). The signatures are searched until asignature is found to which the input arrays can all be cast safely (ignoring anyscalar arguments which are not allowed to determine the type of the result). Theimplication of this search procedure is that “lesser types” should be placed below“larger types” when the signatures are stored. If no 1-d loop is found, then an erroris reported. Otherwise, the argument list is updated with the stored signature —in case casting is necessary and to fix the output types assumed by the 1-d loop. If the ufunc has 2 inputs and 1 output and the second input is an Object arraythen a special-case check is performed so that NotImplemented is returned if thesecond input is not an ndarray, has the array priority attribute, and has an r<op> special method. In this way, Python is signaled to give the other object achance to complete the operation instead of using generic object-array calculations.This allows (for example) sparse matrices to override the multiplication operator1-d loop. For input arrays that are smaller than the specified buffer size, copies are madeof all non-contiguous, mis-aligned, or out-of-byteorder arrays to ensure that forsmall arrays, a single-loop is used. Then, array iterators are created for all theinput arrays and the resulting collection of iterators is broadcast to a single shape. The output arguments (if any) are then processed and any missing return arraysare constructed. If any provided output array doesn’t have the correct type (or ismis-aligned) and is smaller than the buffer size, then a new output array is con-structed with the special UPDATEIFCOPY flag set so that when it is DECREF’don completion of the function, it’s contents will be copied back into the outputarray. Iterators for the output arguments are then processed. Finally, the decision is made about how to execute the looping mechanism toensure that all elements of the input arrays are combined to produce the outputarrays of the correct type. The options for loop execution are one-loop (for con-tiguous, aligned, and correct data-type), strided-loop (for non-contiguous but stillaligned and correct data-type), and a buffered loop (for mis-aligned or incorrectdata-type situations). Depending on which execution method is called for, the loopis then setup and computed.
365Interpreter Lock (GIL) is released prior to calling all of these loops (as long as theydon’t involve object arrays). It is re-acquired if necessary to handle error conditions.The hardware error flags are checked only after the 1-d loop is calcluated.
This is the simplest case of all. The ufunc is executed by calling the underlying 1-dloop exactly once. This is possible only when we have aligned data of the correcttype (including byte-order) for both input and output and all arrays have uniformstrides (either contiguous, 0-d, or 1-d). In this case, the 1-d computational loop iscalled once to compute the calculation for the entire array. Note that the hardwareerror flags are only checked after the entire calculation is complete.
When the input and output arrays are aligned and of the correct type, but thestriding is not uniform (non-contiguous and 2-d or larger), then a second loopingstructure is employed for the calculation. This approach converts all of the iteratorsfor the input and output arguments to iterate over all but the largest dimension.The inner loop is then handled by the underlying 1-d computational loop. Theouter loop is a standard iterator loop on the converted iterators. The hardwareerror flags are checked after each 1-d loop is completed.
This is the code that handles the situation whenever the input and/or output arraysare either misaligned or of the wrong data-type (including being byte-swapped)from what the underlying 1-d loop expects. The arrays are also assumed to benon-contiguous. The code works very much like the strided loop except for theinner 1-d loop is modified so that pre-processing is performed on the inputs andpost-processing is performed on the outputs in bufsize chunks (where bufsize isa user-settable parameter). The underlying 1-d computational loop is called ondata that is copied over (if it needs to be). The setup code and the loop code isconsiderably more complicated in this case because it has to handle:
• deciding whether or not to use buffers on the input and output data (mis- aligned and/or wrong data-type)
366 • copying and possibly casting data for any inputs or outputs for which buffers are necessary.
• breaking up the inner 1-d loop into bufsize chunks (with a possible remainder).
Again, the hardware error flags are checked at the end of each 1-d loop.
17.7.4 MethodsTheir are three methods of ufuncs that require calculation similar to the general-purpose ufuncs. These are reduce, accumulate, and reduceat. Each of these methodsrequires a setup command followed by a loop. There are four loop styles possible forthe methods corresponding to no-elements, one-element, strided-loop, and buffered-loop. These are the same basic loop styles as implemented for the general purposefunction call except for the no-element and one-element cases which are special-casesoccurring when the input array objects have 0 and 1 elements respectively.
17.7.4.1 Setup
The setup function for all three methods is construct reduce. This functioncreates a reducing loop object and fills it with parameters needed to complete theloop. All of the methods only work on ufuncs that take 2-inputs and return 1 output.
367Therefore, the underlying 1-d loop is selected assuming a signature of [otype,otype, otype] where otype is the requested reduction data-type. The buffer sizeand error handling is then retrieved from (per-thread) global storage. For smallarrays that are mis-aligned or have incorrect data-type, a copy is made so that theun-buffered section of code is used. Then, the looping strategy is selected. If thereis 1 element or 0 elements in the array, then a simple looping method is selected.If the array is not mis-aligned and has the correct data-type, then strided loopingis selected. Otherwise, buffered looping must be performed. Looping parametersare then established, and the return array is constructed. The output array isof a different shape depending on whether the method is reduce, accumulate, orreduceat. If an output array is already provided, then it’s shape is checked. Ifthe output array is not C-contiguous, aligned, and of the correct data type, thena temporary copy is made with the UPDATEIFCOPY flag set. In this way, themethods will be able to work with a well-behaved output array but the resultwill be copied back into the true output array when the method computation iscomplete. Finally, iterators are set up to loop over the correct axis (dependingon the value of axis provided to the method) and the setup routine returns to theactual computation routine.
17.7.4.2 Reduce
All of the ufunc methods use the same underlying 1-d computational loops withinput and output arguments adjusted so that the appropriate reduction takes place.For example, the key to the functioning of reduce is that the 1-d loop is called withthe output and the second input pointing to the same position in memory and bothhaving a step-size of 0. The first input is pointing to the input array with a step-size given by the appropriate stride for the selected axis. In this way, the operationperformed is
o = i[0] o = i[k] ¡op¿ o k = 1 . . . N
where N + 1 is the number of elements in the input, i, o is the output, and i[k] isthe k th element of i along the selected axis. This basic operations is repeated forarrays with greater than 1 dimension so that the reduction takes place for every 1-dsub-array along the selected axis. An iterator with the selected dimension removedhandles this looping. For buffered loops, care must be taken to copy and cast data before the loop
368function is called because the underlying loop expects aligned data of the correctdata-type (including byte-order). The buffered loop must handle this copying andcasting prior to calling the loop function on chunks no greater than the user-specifiedbufsize.
17.7.4.3 Accumulate
The accumulate function is very similar to the reduce function in that the outputand the second input both point to the output. The difference is that the secondinput points to memory one stride behind the current output pointer. Thus, theoperation performed is
o[0] = i[0] o[k] = i[k] ¡op¿ o[k − 1] k = 1 . . . N.
The output has the same shape as the input and each 1-d loop operates over Nelements when the shape in the selected axis is N + 1. Again, buffered loops takecare to copy and cast the data before calling the underlying 1-d computational loop.
17.7.4.4 Reduceat
The reduceat function is a generalization of both the reduce and accumulate func-tions. It implements a reduce over ranges of the input array specified by indices.The extra indices argument is checked to be sure that every input is not too largefor the input array along the selected dimension before the loop calculations takeplace. The loop implementation is handled using code that is very similar to thereduce code repeated as many times as there are elements in the indices input. Inparticular: the first input pointer passed to the underlying 1-d computational looppoints to the input array at the correct location indicated by the index array. Inaddition, the output pointer and the second input pointer passed to the underlying1-d loop point to the same position in memory. The size of the 1-d computationalloop is fixed to be the difference between the current index and the next index(when the current index is the last index, then the next index is assumed to be thelength of the array along the selected dimension). In this way, the 1-d loop willimplement a reduce over the specified indices. Mis-aligned or a loop data-type that does not match the input and/or outputdata-type is handled using buffered code where-in data is copied to a temporary
369buffer and cast to the correct data-type if necessary prior to calling the underlying1-d function. The temporary buffers are created in (element) sizes no bigger thanthe user settable buffer-size value. Thus, the loop must be flexible enough to call theunderlying 1-d computational loop enough times to complete the total calculationin chunks no bigger than the buffer-size.
370Index
371column stack, 99 byteorder, 134compress, 96 char, 134, 135concatenate, 91 descr, 135Configuration, 199 fields, 134conj, 168 flags, 136conjugate, 168 hasobject, 135container class, 152 isbuiltin, 135convolve, 92 isnative, 135copy, 96 itemsize, 134corrcoef, 103 kind, 134correlate, 92 name, 134cos, 170 num, 134cosh, 171 str, 134cov, 102 subdtype, 135cross, 94 type, 134ctypes, 53, 87, 343–353 construction, 136–139ctypeslib, 194 from dict, 139cumproduct, 96 from float, 136cumsum, 96 from list, 138 from None, 136delete, 108 from string, 137deprecate, 127 from tuple, 138diag, 119 from type, 136diagflat, 119 methods, 139–140diagonal, 95 reduce , 140diff, 107 setstate , 140digitize, 104 newbyteorder, 139disp, 108distutils, 199 Ellipsis, 25divide, 167 ellipsis, 80dot, 93 empty, 88dsplit, 100 empty like, 88dstack, 99 equal, 172dtype, 20, 133–140, 358 error handling, 158 adding new, 318–321 exp, 169 attributes, 134–136 expand dims, 100 alignment, 134 extension module, 297–309
372extract, 108 identity, 90eye, 118 imag, 95 index exp, 117f2py, 327–334 indexing, 23, 80–85, 361fft, 180–184 indices, 89finfo, 122 inner, 93fitting, 113 insert, 109fix, 123 Instant, 355flatnonzero, 90 intersect1d, 113fliplr, 119 intersect1d nu, 113flipud, 119 invert, 172floor, 176 iscomplex, 175floor divide, 167 iscomplexobj, 121fmod, 175 isfinite, 175frexp, 175 isfortran, 88frombuffer, 89 isinf, 175fromfile, 89 isnan, 175fromfunction, 90 isneginf, 123fromiter, 89 isposinf, 123frompyfunc, 156 isreal, 175fromstring, 88 isrealobj, 121get include, 126 isscalar, 121get numarray include, 126 issubclass , 120get printoptions, 75, 95 issubdtype, 121gradient, 107 ix , 114greater, 172 kaiser, 125greater equal, 172 kron, 101hamming, 124 ldexp, 175hanning, 124 left shift, 172histogram, 104 less, 172histogram2d, 104 less equal, 172histogramdd, 104 lexsort, 91hsplit, 100 linalg, 177–180hstack, 99 linspace, 105hypot, 170 load, 89i0, 124 loads, 89
373log, 169 flags, 46log10, 169 flat, 51log2, 123 imag, 51logical and, 173 itemsize, 49logical not, 173 nbytes, 49logical or, 173 ndim, 49logical xor, 173 real, 51logspace, 105 recognized by, 142 shape, 48masked arrays, 151–152 size, 49mat, 120 strides, 49matrix, 143–145 T, 51maximum, 173 C-API, 239–289mean, 96 flags, 46–48median, 103 memory model, 357memory maps, 145 methods, 55–70meshgrid, 105 all, 70minimum, 174 any, 70mintypecode, 122 argmax, 68modf, 175 argmin, 68msort, 103 argsort, 64multiply, 167 astype, 57nan to num, 121 byteswap, 57nanargmax, 109 choose, 63nanargmin, 109 clip, 68nanmax, 109 compress, 65nanmin, 109 conj, 68nansum, 109 conjugate, 68ndarray, 45–85 copy, 57 attributes, 45–54 cumprod, 70 array interface , 52 cumsum, 69 array priority , 52 diagonal, 66 array struct , 53 dump, 57 base, 49 dumps, 57 ctypes, 53–54 fill, 58 data, 49 flatten, 62 dtype, 50 getfield, 58
374 item, 55 copy, 72 itemset, 56 deepcopy, 72 max, 66 div, 77 mean, 69 divmod, 77 min, 68 eq, 74 nonzero, 65 float, 79 prod, 70 floordiv, 77 ptp, 68 ge, 74 put, 62 getitem, 76, 80 ravel, 62 getslice, 76, 80 repeat, 62 gt, 74 reshape, 60 hex, 79 resize, 60 iadd, 78 round, 68 iand, 78 searchsorted, 64 idiv, 78 setflags, 58 ifloordiv, 78 sort, 63 ilshift, 78 squeeze, 62 imod, 78 std, 70 imul, 78 sum, 69 init, 74 swapaxes, 61 int, 79 take, 62 invert, 79 tofile, 56 ior, 78 tolist, 55 ipow, 78 tostring, 56 irshift, 78 trace, 68 isub, 78 transpose, 60 itruediv, 78 var, 69 ixor, 78 view, 57 le, 74special methods, 72–79 len, 75 abs, 79 long, 79 add, 76 lshift, 77 and, 77 lt, 74 array, 74 mod, 77 array wrap, 74 mul, 76 complex, 79 ne, 74 contains, 76 neg, 79
375 new, 73 polysub, 112 nonzero, 75 polyval, 113 oct, 79 power, 168 or, 77 product, 96 pos, 79 ptp, 95 pow, 77 put, 95 reduce, 72 putmask, 91 repr, 74 PyArray Type, 214 rshift, 77 PyArrayDescr Type, 215 setitem, 76, 80 PyArrayInterface, 230 setslice, 76, 80 PyArrayIter Type, 226 setstate, 72 pyrex, 338–343 str, 74 PyUFunc Type, 223 sub, 76 r , 115 truediv, 77 random, 184–194 xor, 77 continuous, 187–194 subtyping, 141–142, 322–324 discrete, 185–187 view, 81 rank, 96ndindex, 118 ravel, 95negative, 168 real, 95newaxis, 80 real if close, 121nonzero, 95 record arrays, 147–151not equal, 172 reference counting, 302–303ones, 88 remainder, 168outer, 92 repeat, 95 require, 87piecewise, 106 reshape, 95place, 108 resize, 101poly, 111 right shift, 172poly1d, 111 roll, 99polyadd, 112 rollaxis, 99polyder, 112 roots, 111polydiv, 113 rot90, 119polyfit, 113 round , 110polyint, 112 row stack, 99polymul, 113polynomials, 110 s , 117
376searchsorted, 95 The, 134select, 105 tile, 101set operations, 113–114 trace, 95set numeric ops, 126 transpose, 95set printoptions, 75, 95 trapz, 107set string function, 95 tri, 119setbufsize, 158 tril, 120setdiff1d, 114 trim zeros, 107seterr, 158 triu, 120seterrcall, 159 true divide, 167setmember1d, 114 ufunc, 30, 156–176, 363–370setxor1d, 114shape, 96 adding new, 315–317 attributes, 160signbit, 175sin, 170 C-API, 289–296sinc, 123 casting rules, 161 keyword arguments, 159single-segment, 28sinh, 170 methods, 162–166 accumulate, 164, 369SIP, 354size, 96 outer, 166 reduce, 164, 368sometrue, 96sort, 95 reduceat, 165, 369 union1d, 114sort complex, 108split, 100 unique, 108 unique1d, 113sqrt, 169squeeze, 95 universal function, 30 unravel index, 118std, 96stride, 29 unwrap, 108 user array, 152subtract, 167sum, 96 vander, 118swapaxes, 95 var, 96swig, 353 vdot, 93take, 95 vectorize, 109 vsplit, 100tan, 170tanh, 171 vstack, 99tensordot, 93 weave, 334–338
377where, 90
zeros, 88zeros like, 88
378 | https://de.scribd.com/document/50360827/numpybook | CC-MAIN-2019-43 | refinedweb | 56,704 | 62.88 |
Mixing SDK and NDK
Android app development is split into two, very distinct worlds.
On the one side, there's the Android SDK, which is what the bulk of Android apps is being developed in. The SDK is based on the Java Runtime and the standard Java APIs, and it provides a very high-level development experience. Traditionally, the Java language or Kotlin would be used to develop in this space.
And then there's the Android NDK, which sits at a much lower level and allows to write code directly for the native CPUs (e.g. ARM or x86). This code works against lower-level APIs provided by Android and the underlying Linux operating system that Android is based on, and traditionally one would use a low-level language such as C to write code at this level.
The Java Native Interface, or JNI, allows the two worlds to interact, making it possible for SDK-level JVM code to call NDK-level native functions, and vice versa.
Elements makes it really easy to develop apps that mix SDK and NDK, in several ways:
- A shared language for SDK and NDK
- Easy bundling, with Project References
- Automatic generation of JNI imports
- Mixed Mode Debugging
A Shared Language for SDK and NDK
The first part is the most obvious and trivial. Since Elements decouples language form platform, whatever the language of choice is, you can use it to develop both the JVM-based SDK portion of your app and the native NDK part. No need to fall back to a low-level language like C for the native extension.
Easy Bundling of NDK Extensions, with Project References
Once you have an SDK-based app and one or more native extensions in your project, you can bundle the extension(s) into your fina .apk simply adding a conventional Project Reference to them, for example by dragging the extension project onto the app project in Fire or Water.
Even though the two projects are of a completely different type, the EBuild build chain takes care of establishing the appropriate relationship and adding the final NDK binaries into the "JNI" subfolder of your final .apk.
Automatic Generation of JNI Imports
Establishing a project reference to your NDK extension also automatically generates JNI imports for any APIs you expose from our native project. All you need to do is mark your native methods with the
JNIExport aspect, as such:
[JNIExport(ClassName := 'com.example.myandroidapp.MainActivity')] method HelloFromNDK(env: ^JNIEnv; this: jobject): jstring; begin result := env^^.NewStringUTF(env, 'Hello from NDK!'); end;
[JNIExport(ClassName = "com.example.myandroidapp.MainActivity")] public jstring HelloFromNDK(^JNIEnv env, jobject thiz) { return (**env).NewStringUTF(env, "Hello from NDK!"); }
@JNIExport(ClassName = "com.example.myandroidapp.MainActivity") public func HelloFromNDK(_ env: ^JNIEnv, _ this: jobject) -> jstring { return (**env).NewStringUTF(env, "Hello from NDK!"); }
@JNIExport(ClassName = "com.example.myandroidapp.MainActivity") public jstring HelloFromNDK(^JNIEnv env, jobject thiz) { return (**env).NewStringUTF(env, "Hello from NDK!"); }
As part of the build, the compiler will generate a source file with import stubs for any such APIs, and inject that into your main Android SDK project. That source file will contain Partial Classes (or Extensions, in Swift parlance) matching the namespace and class name you specified.
All you need to do (in Oxygene, C# or Java) is to mark your own implementation of the Activity as
partial (
__partial in Java, and no action is needed in Swift), and the new methods implemented in your NDK extension will automatically be available to your code:
namespace com.example.myandroidapp; type MainActivity = public partial class(Activity) public method onCreate(savedInstanceState: Bundle); override; begin inherited; // Set our view from the "main" layout resource ContentView := R.layout.main; HelloFromNDK; end; end; end;
namespace com.example.myandroidapp { public partial class MainActivity : Activity { public override void onCreate(Bundle savedInstanceState) { base(savedInstanceState); // Set our view from the "main" layout resource ContentView = R.layout.main; HelloFromNDK(); } } }
public class MainActivity : Activity { override func onCreate(_ savedInstanceState: Bundle) { super(savedInstanceState) // Set our view from the "main" layout resource ContentView = R.layout.main HelloFromNDK() } }
package com.example.myandroidapp; public partial class MainActivity : Activity { public override void onCreate(Bundle savedInstanceState) { base(savedInstanceState); // Set our view from the "main" layout resource ContentView = R.layout.main; HelloFromNDK(); } }
Of course you can use any arbitrary class name in the
JNIExport aspect, it does not have to match an existing type in your SDK project. If you do that, rather than becoming available as part of your Activity (or whatever other class), the imported APIs will be on a separate class you can just instantiate.
To see the generated imports, search your build log for "
JNI.pas" to get the full path to the file that gets generated and injected into your project. You can also just invoke "Go to Definition" (^⌥D in Fire, Ctrl+Alt+D in Water) on a call to one of the methods, to open the file, as the IDE will treat it as regular part of your project. (The same, by the way, is also true of the
R.java file generated by the build that define the
R class that gives access to all your resources.)
Mixed Mode Debugging
Finally, Elements allows to debug both your SDK app and its embedded NDK extensions at the same time. You can set breakpoints in both Java and native code, and explore both sides of your app and how they interact.
All of this is controlled by two settings, but Fire and Water, our IDEs, automate the process for you so you don't even have to worry about them yourself.
First, there's the "Support Native Debugging" option in your NDK project. It's enabled by default for the Debug configuration in new projects, and it instructs the build chain to deploy the LLDB debugger library as part of your native library (and have it, in turn, bundled into your
.apk). This is what allows the debugger to attach to the NDK portion of your app later.
Secondly, there's the "Debug Engine" option in your SDK project. It defaults to "Java", for JVM-only debugging, but as soon as you add a Project Reference to an NDK extension to your app, it will switch to "Both" (again, only for the Debug configuration), instructing the Elements Debugger to start both JVM and native debug sessions when you launch your app.
This, of course, works both in the Emulator and on the device.
See Also
- Android SDK and Android NDK
- Debugging Android Projects
JNIExportAspect
- Java Native Interface
- Video: Mixed Mode Android Apps
- Blog post: Debugging Mixed-Mode Android Apps
Note that the video and blog post above were created before the automatic generation of JNI Imports was available, so it still mentions having to define the import manually. | https://docs.elementscompiler.com/Platforms/Android/Mixing/ | CC-MAIN-2022-40 | refinedweb | 1,125 | 50.57 |
I have done some work on VMSBACKUP, a (partial) clone of the VMS BACKUP utility. The lastest version as far as I know is 4.1.1. There's source code for 4.1 at. I don't think I still have a copy. I'd suggest asking on the free-vms mailing list; see free-vms.org. Last I looked VMSBACKUP4-1-1.ZIP was available for download at (Richard Levitte's site).
Errata/issues (some of these may be helpful in building/using VMSBACKUP, some are probably more of interest to future maintainers):
#include "getopt.h"to
#include <unistd.h>. | http://www.panix.com/~kingdon/vms/backup.html | crawl-002 | refinedweb | 102 | 78.96 |
Here we will see a program to swap two numbers using a temporary third variable. The steps are as follows:
1. User is asked to enter the value of first and second number. The input values are stored in first(num1) and second(num2) variable.
2. Assigning the value of first variable to the third variable.
3. Assigning the value of second variable to the first variable.
4. Assigning the value of third variable to the second variable.
Example: Program to swap two numbers
#include <iostream> using namespace std; int main() { int num1, num2, temp; cout<<"Enter 1st Number: "; cin>>num1; cout<<"Enter 2nd Number: "; cin>>num2; //displaying numbers before swapping cout<<"Before Swapping: First Number: "<<num1<<" Second Number: "<<num2; //swapping temp=num1; num1=num2; num2=temp; //displaying numbers after swapping cout<<"\nAfter Swapping: First Number: "<<num1<<" Second Number: "<<num2; return 0; }
Output:
| https://beginnersbook.com/2017/12/cpp-program-swap-two-numbers-using-third-variable/ | CC-MAIN-2018-30 | refinedweb | 143 | 54.73 |
[Solved] Column vs ColumnLayout - bug or feature
Hi folks,
I found some "strange" differences beetwen Column and ColumnLayout.
Seems like a bug to me in ColumnLayout but maybe someone can explain it to me?
My usecae was: Some main-item holds a list of items as a property. The list can be set from outside.
The items from the list should be dynamically added to a layout of the main-item. And when the main-item is resized then the items of the layout should be resized too.
Attached you see my code which works if I use a Column for layouting the items:
@
import QtQuick 2.3
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1
Window {
visible: true
width: 360
height: 360
Rectangle { property list<Rectangle> rectList: [ Rectangle { color: "red" }, Rectangle { color: "green" } // Rectangle { color: "red"; width: 50; height: 50 }, // Rectangle { color: "green"; width: 50; height: 50 } ] id: mainRect anchors.fill: parent color: "yellow" Column { // ColumnLayout { id: mainLayout spacing: 2 anchors { horizontalCenter: parent.horizontalCenter bottom: parent.bottom bottomMargin: 0 } } Component.onCompleted: { for ( var i = 0; i < rectList.length; ++i ) { rectList[i].parent = mainLayout rectList[i].width = Qt.binding( function() { return mainRect.width * 0.3 } ) rectList[i].height = Qt.binding( function() { return mainRect.width * 0.3 } ) } } }
}@
If I exchange the Column with a ColumnLayout it does not work.
Nothing will be displayed inside of main-item (here it is a yellow Rectangle).
To solve this problem I have to give the rectangles of the rectangle-list an initial width and height (see comments). After this the Rectangles (red and green) are visible inside of the main-item.
But the resizing still does not work (it works only in the horizontal direction).
So what is it?
What must be done for using the ColumnLayout?
Thanks in advance.
Best regards
Kai
Column and ColumnLayout are very different, you cannot exchange them easily.
The purpose for which they have been created it's very different.
Before explaining the difference, it's important to note the basis on which they are based on.
Before Qt introduced the Qt Quick, there was only QWidget and the way to organize the QWidget was based on QLayout hierarchy. The QLayout is an non-visual object that take the responsability to dynamically change the dimension of the QWidget according to a policy in order to fit all QWidget in a specified dimension.
When Qt introduced the Qt Quick, the 'anchors' mechanism was introduced to organize the item into the window. The 'anchors' are a quite different approach. There isn't an intermediate object that dynamically resize the Items, but instead there are constraints the bind the Items to move (and in some case to stretch) depending on how they have been 'anchored'.
Initially, there was no way to the fan of QLayout to use the same way on Qt Quick. But with Qt Quick 2.0 (I think), Qt introduced a mechanism that mimics the QLayout way to arrange things into the Qt Quick: ColumLayout, etc.
And now back to Colum and ColumLayout.
Column: it's created to allow an easy way to arrange via 'anchors' the children Items into a Column. And then, you cannot explicitly set or bind vertical 'anchors' and properties like 'y'. Because they are under Column control. But width and height properties are under your control and you can bind to whatever you want.
In fact, Column has an height variable depending on the heights of the children.
ColumnLayout: it's created to mimic the QVBoxLayout, and arrange the Item by dynamically changing the width and the height in order to keep them arranged into a column that fits inside the width and height of ColumnLayout. In this case, the width and the height of items are under the ColumnLayout. You cannot (should) set directly, instead you have to use the Layout attached properties in order to inform ColumnLayout how they should changed. Some of these properties are: Layout.preferredWidth/Height, Layout.minimumWidth/Height, Layout.maximumWidth/Height
ColumnLayout tend to stretch and to shrink the Item in order to keep them into a specified space and also it allow to specify a relative proportion between items in order to achieve an effect that some item are bigger that other: Layout.rowSpan, Layout.columnSpan
So, the code that works with Column doesn't works with ColumnLayout and viceversa.
Try to understand which one is more suitable for your.
You'd probably benefit from my latest Pluralsight course on "Qt Quick Fundamentals": on Pluralsight. Module 6 is "Positioning" and clips 06 and 07 are on Layouts. Pluralsight is a subscription service but if you send me an email through the forum I can give you a free week long VIP pass good for unlimited hours of watching, plus you can download course materials and watch offline during the week. The downloaded video does expire when the pass expires.
@Gianluca:
Perfect explanation!
I would like to find your text in the docs. Please put it there!
@Rolias:
Thanks for your offer but at the moment my problems are solved.
(But the next one will come soon.....)
Thank you very much :-)
I don't know where to start for contributing to the Qt documentation.
- SGaist Lifetime Qt Champion
@ Gianluca, the same way as you would do for code.
Create a jira account
Clone the repository
Update the documentation
Submit for review
Add reviewers (e.g. the documentation team members)
Have some patience :)
Long version "here": | https://forum.qt.io/topic/47844/solved-column-vs-columnlayout-bug-or-feature | CC-MAIN-2018-43 | refinedweb | 910 | 66.03 |
Debug Python related CRASH
hi, I rely heavily on Python Tags for some tasks
the setup is a bit complex, because the tags import my own modules,
but it worked reliable for years.
Now I get freezes / crashes on Windows when I open my file
and strangely that does not happen on macOS.
Is there a way to
have cinema4d log all python console output to a file?
maybe I then can see what causes the crashes
safe start c4d without the execution of python tags in the scene?
best, index
Hi,
your problem sounds a bit like a violation of Cinema's Threading restrictions, but it is hard to tell without any code.
- Not natively, but you can mess around with
sys.stdoutlike in any Python interpreter. If you want to have both a console output and a log, you could use something like I did provide at the end of my post. Please remember that my code below is an example and not meant to be used directly.
- Also not possible, afaik.
Cheers,
zipit
Code example for a logger object. You have to save the code to a file for this script to work. Details in the doc string.
"""A very simple logger that writes both to the console and to a file. Saves this code to a file and run the file from the script manager. Cinema will start logging all console output to a file in the same folder as this script is located in. The file will only be finalized / updated when you close Cinema, or when you restart the logger, i.e. type the following into the console: import sys sys.stdout.restart() To 'undo' what this script has done, either restart Cinema or type this into the console: import sys sys.stdout = sys.stdout._stdout """ import datetime import os import sys class ConsoleLogger(object): """A very simple logger that writes both to the console and to a file. The logger uses a dangling file (a file that is being kept open) which is mostly considered a big no-no the days. The safer approach would be to use a file context in `write`, but reopening a file for each write access comes at a cost. The purpose of the whole class is to imitate file object so that it can be attached to sys.stdout. The relevant methods are ConsoleLogger.write and ConsoleLogger.flush. The rest is more or less fluff. If you want to be on the safe side, you could also implement the whole file object interface, but I wasn't in the mood for doing that ;) """ def __init__(self): """Initializes the logger. """ self._file = None self._stdout = sys.stdout self.restart() def __del__(self): """Destructor. We have to close the file when the logger is getting destroyed. Also reverts sys.stdout to its original state upon instantiation. """ sys.stdout = self._stdout self._file.close() def restart(self): """Starts a new logger session. """ # Some date-time and file path gymnastics. time_stamp = datetime.datetime.now().ctime().replace(":", "-") file_path = "{}.log".format(time_stamp) file_path = os.path.join(os.path.split(__file__)[0], file_path) # Close old file and create a new one. if self._file is not None: self._file.close() self._file = open(file_path, "w+") def close(self): """Closes the logger manually. """ self._file.close() self._file = None def write(self, message): """Writes a message. Writes both to the console `sys.stdout` object and the log file. Args: message (str): The message. Raises: IOError: When the log file has been closed. """ self._stdout.write(message) if self._file is None: msg = "Logger file has been closed" raise IOError(msg) self._file.write(message) def flush(self): """Flushes sys.stdout. Needed for Python, you could also flush the file, but that is probably not what you want. """ self._stdout.flush() if __name__ == "__main__": sys.stdout = ConsoleLogger()
thx zipit,
can i apply that stdout redirection at the root somewhere, so that it applies for all python output?
somewhere in resource/modules/python/ ...
as my file crashes c4d on open, i need a temp hack to get that output :)
index
nevermind... i figured it out and added the console logger in
resource/modules/python/libs/python27/_maxon_init
to get live output in the file I also added
self._file.flush()
to the write() method
... the ConsoleLogger works nicely, but it didnt help me finding the bug :-)
in the end it was this function, executed in a lot (±100) of python tags :)
macos can handle that, on windows it leads to a crash.
I added it, because (most of the time) after opening a file the Python Tags "Tag" tab is active showing the code.
Actually a single function call would be enough, but how can you achieve that when the tags dont know of each other.
I'd need to store an info globally which doesn't stay alive when saving / reopening the file.
is that possible? (store info outside the python tags scope, accessible from all python tags)
Hi,
@indexofrefraction said in Debug Python related CRASH:
I'd need to store an info globally which doesn't stay alive when saving / reopening the file.
- To store stuff 'globally' the common approach is to inject your objects into the Python interpreter. There are many places you can choose from and they are all equally bad. It's a hack. I like to use Python's module dictionary, because it has the benefit of a nice syntax (you can import your stuff). Just make sure not to overwrite any modules.
import sys if "my_stuff" not in sys.modules.keys(): sys.modules["my_stuff"] = "bob is your uncle!" # Somewhere else in the same interpreter instance. import my_stuff print my_stuff
- The life time of objects depends on their document being loaded. So if you want to 'cache' nodes beyond the life time of their hosting document, you have to do that manually. Below you will find a rough sketch on how you can approach that. There are many other ways to approach that. The UUIDs for a document will work beyond save boundaries, so you can cache something with that approach, save the document, even relocate it, and then load it again and feed the document into the cache interface query and will spit out the clones of the cached nodes.
Cheers,
zipit
"""A simple interface to cache nodes. This is an example, not finished code. Run in the script manager, read the comments. The *meat* is in CacheInterface.add() and CacheInterface.query(), start reading in main(). """ import c4d class CacheInterface (object): """A simple interface to cache nodes. """ def __init__(self): """Init. """ self._cache = {} def _get_cache(self, uuid): """Returns the cache for a cache document identifier. Args: uuid (c4d.storage.ByteSequence): The document identifier for the cache. Returns: dict["doc": c4d.documents.BaseDocument, "nodes": list[c4d.GeListNode]]: The cache for the given identifier. """ if not uuid in self._cache.keys(): doc = c4d.documents.BaseDocument() self._cache[uuid] = {"doc": doc, "nodes": []} return self._cache[uuid] def _get_tag_index(self, node, tag): """Returns the index of a tag. Args: node (c4d.BaseObject): The object the tag is attached to. tag (c4d.BaseTag): The tag. Returns: int or None: The index or None when the tag is not attached to the object. """ current = node.GetFirstTag() index = 0 while current: if current == tag: return index current = current.GetNext() return None def add(self, node): """Adds a node to the cache. Args: node (c4d-GeListNode): The node to cache. Currently only BaseObjects and BaseTags have been implemented. Returns: c4d-storage.ByteSeqeunce: The identifier for the cache the node has been inserted in. Raises: NotImplementedError: When an unimplemented node type has been passed. ValueError: When the passed node is not attached to a document. """ doc = node.GetDocument() if doc is None: raise ValueError("Can only cache nodes attached to a document.") uuid = doc.FindUniqueID(c4d.MAXON_CREATOR_ID) cache = self._get_cache(uuid) # BaseObjects if isinstance(node, c4d.BaseObject): # Pretty easy, clone and inject clone = node.GetClone(0) cache["doc"].InsertObject(clone) cache["nodes"].append(clone) # BaseTags elif isinstance(node, c4d.BaseTag): # For tags things are a bit more complicated. # First we get the index of the tag. index = self._get_tag_index(node.GetObject(), node) if index is None: msg = "Could not find tag on source object." raise AttributeError(msg) # Then we clone the host of object of the tag and the tag. clone_object = node.GetObject().GetClone(0) clone_tag = clone_object.GetTag(node.GetType(), index) # Insert the host object into our cache document. cache["doc"].InsertObject(clone_object) # And append the tag of the same type at the given index # to our cache list. A bit dicey, you might wanna add some # checks to ensure that we actually got the right tag. cache["nodes"].append(clone_tag) # Other node types go here ... else: msg = "The node type {} has not been implemented for caching." raise NotImplementedError(msg.format(type(node))) return uuid def query(self, identifier): """ Args: identifier (c4d.storage.ByteSeqence | c4d.documents.BaseDocument): The identifier for the cache to query or the document that has been the source for the cache. Returns: list[c4d.GeListNode]: The cached nodes. Raises: KeyError: When the provided identifier does not resolve. TypeError: When the identifier is neither a document nor an uuid. """ if isinstance(identifier, c4d.documents.BaseDocument): identifier = identifier.FindUniqueID(c4d.MAXON_CREATOR_ID) if not isinstance(identifier, c4d.storage.ByteSeq): msg = "Illegal identifier type: {}" raise TypeError(msg.format(type(uuid))) uuid = identifier if uuid not in self._cache.keys(): msg = "Provided uuid is not a key in the cache." raise KeyError(msg) return self._cache[uuid]["nodes"] def main(): """Entry point. """ if op is None: raise ValueError("Please select an object to cache.") # The cache interface = CacheInterface() # Some stuff to cache obj, tag = op, op.GetFirstTag() # Inject the nodes into the cache. uuid = interface.add(obj) # We do not need to store the uuid here, since both nodes come from # the same document. interface.add(tag) print "Original nodes:", obj, tag print "Their cache:", interface.query(uuid) if __name__ == "__main__": main()
- indexofrefraction last edited by
hi zipit,
thank u a lot for those tips ! :)
about the CacheInterface i dont know if i do that right,
but if i select a cube and execute in the script manager
R20 crashes right away .-)
Hi,
that is a bit weird. I had ran the example code above in R21 without any crashes. The code is also quite tame, there isn't anything in there which I would see as an obvious candidate for conflicts, as it does not mess with scene or something like that.
Could you elaborate under which circumstances the code above produces a crash?
Cheers,
zipit
Hi @indexofrefraction glad you found the cause of the issue, however I'm wondering in which context)
Is called.
Since it does crash when you open the file directly, I assume you have the previous code called during the Execute of a Tag or a Python Generator.
But both functions are threaded functions. Meaning Any GUI related call is not allowed, because as you experienced, doing GUI stuff within a thread can make Cinema 4D crash for more information please read threading information
This could also confirm why it works on Mac OS and not on Windows since they are 2 different OS where the drawing pipeline is slightly different so you may found some cases where something does work in one Os but not on the other and vise-versa.
Cheers,
Maxime.
just FYI, the CacheInterface immediately crashes R20 but works on R21
Ok, thanks!
I was doing this in every Python Tag and I have 100-200 of those in the File.
I don't really need to do this, it was just a "beauty" thing... that did end up ugly :-D | https://plugincafe.maxon.net/topic/12876/debug-python-related-crash | CC-MAIN-2020-50 | refinedweb | 1,951 | 67.86 |
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo
#!/usr/bin/env python
#Boa:App:BoaApp
import wx
import Frame1
modules ={'Frame1': [1, 'Main frame of Application', 'Frame1.py']}
class BoaApp(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
self.main = Frame1.create(None)
self.main.Show()
self.SetTopWindow(self.main)
return True
def main():
application = BoaApp(0)
application.MainLoop()
if __name__ == '__main__':
main()
Jeff Peery <jeffpeery <at> seametrics.com> writes:
>
> Hello, I attached a quick sample code that I am tinkering
> with to learn how to use py2exe with maplotlib. I followed the directions
described in:
>
>
>
> Although this still doesn’t work. I attached my code, setup.py, and the errlog
that is
> created when I try to execute the executable created by py2exe. What might I be
> missing here? Thanks.
>
Hi Jeff,.
- Daniel
In article <loom.20060207T181254-585@...>,
Daniel McQuillen <daniel@...> wrote:
> Jeff Peery <jeffpeery <at> seametrics.com> writes:
>
> > Hello, I attached a quick sample code that I am tinkering
> > with to learn how to use py2exe with maplotlib...
>
>.
I believe there are two unrelated problems at work here, only one of
which I have solved:
1) The current matplotlib keeps its files in a new location, so the
existing py2exe examples don't work.
I've appended code that does copy the matplotlib data correctly. (I do
copy the nibs subdirectory over but I'm not sure it's necessary). In any
case, my application can import matplotlib and print
matplotlib.get_data_path() and the value is correct.
2) Tons of missing modules are missing, some of which are crucial to my
application, such as win32com.shell. (I've put an abbreviated list at
the end of this message.)
My (Tkinter-based) application works fine if I simply don't try to
include matplotlib (but then users will have to install it themselves).
Somehow the act of including matplotlib prevents important modules from
Something like this was reported a few months ago -- here's a reference:
<
style=nested&viewmonth=200510> (search for libgdk_pixbuf-2.0-0.dll).
At the time, a py2exe module was fixed, but py2exe 0.6.4 has come out
since then so I assume the fix is included in that! (I confess I've not
tried downloading that one patched module since it's older than the one
in 0.6.4; perhaps I should.)
Any ideas? I'm using py2exe 0.6.4 and matplotlib 0.87 (both installed
from binary) in case it matters.
-- Russell
Here is my setup.py with some minor bits missing:
from distutils.core import setup
import os
import py2exe
import matplotlib
def addDataFiles(dataFiles, fromDir, toSubDir=None,
inclHiddenDirs=False):
"""Find data files and format data for the data_files argument of
setup.
In/Out:
- dataFiles: a list to which is appended zero or more of these
elements:
[subDir, list of paths to resource files]
Inputs:
- fromDir: path to root directory of existing resource files
- toSubDir: relative path to resources in package;
if omitted then the final dir of fromDir is used
- inclHiddenDirs: if True, the contents of directories whose names
start with "." are included
Returns a list of the following elements:
"""
lenFromDir = len(fromDir)
if toSubDir == None:
toSubDir = os.path.split(fromDir)[1]
for (dirPath, dirNames, fileNames) in os.walk(fromDir):
if not inclHiddenDirs:
dirNamesCopy = dirNames[:]
for ii in range(len(dirNamesCopy)-1, -1, -1):
if dirNamesCopy[ii].startswith("."):
del(dirNames[ii])
if not dirPath.startswith(fromDir):
raise RuntimeError("Cannot deal with %r files; %s does not
start with %r" %\
(resBase, dirPath, fromDir))
toPath = os.path.join(toSubDir, dirPath[lenFromDir+1:])
filePaths = [os.path.join(dirPath, fileName) for fileName in
fileNames]
dataFiles.append((toPath, filePaths))
tuiRoot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
mainProg = os.path.join(tuiRoot, "runtui.py")
# add matplotlib's data files
matplotlibDataPath = matplotlib.get_data_path()
addDataFiles(dataFiles, matplotlibDataPath, "matplotlibdata")
setup(
options = dict(
py2exe = dict (
dll_excludes = [
# the following are needed to avoid errors:
"libgdk_pixbuf-2.0-0.dll",
"libgobject-2.0-0.dll",
"libgdk-win32-2.0-0.dll",
],
excludes = [ # modules to exclude
"_gtkagg",
],
includes = [ # modules to include
],
packages = [
"numarray",
"matplotlib",
"matplotlib.backends",
"matplotlib.numerix",
"encodings", "dateutil", "pytz",
],
)
),
console=[ # windows= for no console, console= for console
dict(
script = mainProg,
icon_resources = [(1, "TUI.ico")],
),
],
data_files = dataFiles,
)
The following modules appear to be missing
['AppKit', 'Convolve', 'Convolve.Lineshape', 'Foundation',
'PyObjCTools', '_wxagg', 'backends.draw_if_interactive',
'backends.new_figure_manager', 'backends.pylab_setup', 'backends.show',
'cairo', 'cairo.gtk', 'cephes', 'fltk', 'gd', 'gobject', 'gtk',
'matplotlib.enthought.pyface.action', 'numerix.ArrayType',
'numerix.Complex', ...'numerix.zeros', 'numpy'...'numpy.testing',
'objc', 'paint', 'pango', 'pyemf', 'qt', 'resource', 'timing',
'trait_sheet', 'win32.com.shell', 'win32.com.shell.shell',
'win32com.gen_py', 'win32com.shell', 'wx',
'matplotlib.numerix.absolute', 'matplotlib.numerix.equal',
'matplotlib.numerix.sqrt', 'numarray.Complex', 'numarray.Complex32',...
'numarray.zeros']
In article <rowen-BE35E7.16245324022006@...>,
"Russell E. Owen" <rowen@...> wrote:
> I believe there are two unrelated problems at work here, only one of
> which I have solved:
>
> 1) The current matplotlib keeps its files in a new location, so the
> existing py2exe examples don't work....
>
> 2) Tons of missing modules are missing, some of which are crucial to my
> application, such as win32com.shell. (I've put an abbreviated list at
> the end of this message.)
It turns out win32com.shell missing is unrelated. I've posted about that
separately but basically the standard workaround for this problem
<>
which my code already had in it doesn't seem to work for me in py2exe
0.6.4 even though the same code works fine 0.6.3.
I'm not yet sure about the other missing packages reported since py2exe
0.6.3 cannot handle matplotlib (without a patched file, which I've not
tried yet).
-- Russell | http://sourceforge.net/p/py2exe/mailman/py2exe-users/thread/rowen-BE35E7.16245324022006@sea.gmane.org/ | CC-MAIN-2015-22 | refinedweb | 948 | 58.99 |
I have this so far. I want to increment the counter every time a GET request is sent to counter#add. What am I doing wrong?
class CounterController < ApplicationController
def initialize
@counter = 0
end
def home
end
def add
@counter += 1
end
end
Every get request is a NEW instance of
CounterController, so it's always starting at zero. This is why whenever you create an instance variable like
@post it's not there on the next request.
@counter is just another example of that.
An alternative might be to make it a class instance...
class CounterController < ApplicationController @counter = 0 def self.add @counter += 1 end def self.counter @counter end def home end def add class.add end def show_counter class.counter end end | https://codedump.io/share/dK15VPzIbiJ0/1/increment-counter-on-page-hit-in-rails | CC-MAIN-2017-51 | refinedweb | 125 | 78.45 |
Hi!... Here is my code: module BinFileReader where import qualified Data.ByteString.Lazy as ByteString import Data.Binary.Get import Data.Word data FileData = FileData { source_filename::String, data = [Word16] } deriving (Show) readBinaryString::FilePath -> IO ByteString.ByteString readBinaryString filename = do input_string <- ByteString.readFile filename putStrLn ((show (ByteString.length input_string) ) ++ " Bytes read") return input_string -- Problems start here: Why the hell does the next function know where its -- data come from? There are no parameters; if I wanted -- to apply another function inside readAsWord that takes the bytestring as well as -- other items, how would I do that? readAsWords::Get [Word16] readAsWords = do empty <- isEmpty if empty then return [] else do v <- getWord16be rest <- readAsWords return (v : rest) readBinaryFile::FilePath -> IO FileData readBinaryFile filename = (FileData filename raw_data) where raw_data = readBinaryString filename word_list = runGet readAsWords raw_data string_length = length word_list -- And here, it ends... I've been trying my best to find a function -- that glues all of the above together, but without any success. -- It should be so trivial, but, somehow, it isn't Any hints? Greetings! Moritz | http://www.haskell.org/pipermail/beginners/2008-November/000457.html | CC-MAIN-2014-41 | refinedweb | 174 | 56.76 |
Improving your code
In 2014, IDRsolutions have been busy adding FindBugs tests which we run on our Java PDF library and PDF to HTML5/SVG converter. So the end of the year seems a good time to share some things we have learnt about using FindBugs….
What is FindBugs?
FindBugs is a powerful, free, Open Source static analysis tool that can easily be used and integrated into Ant to provide bug free and consistent code after every build.
It works by analysing Java byte code and checking every line against its growing database of common mistakes, dodgy code, bad practices and other more complex errors such multithreading problems and security risks. After running, FindBugs produces an html error report listing all the possible mistakes and explaining the problem and what can be done to remedy it.
An Example of the Optimizations
One particular rule that FindBugs checks for under the category of performance is called “Method concatenates strings using + in a loop.” It provides a short explanation of the problem and an example of the solution.
// This is bad String s = ""; for (int i = 0; i < field.length; ++i) { s = s + field[i]; } // This is better StringBuffer buf = new StringBuffer(); for (int i = 0; i < field.length; ++i) { buf.append(field[i]); } String s = buf.toString();
The explanation for this performance drop when using the “+” to append strings in a loop is given by FindBugs. “In the first case, in each iteration, the String is converted to a StringBuilder, appended to, and converted back to a String. This can lead to a cost quadratic in the number of iterations, as the growing string is recopied in each iteration.”
It’s these kinds of small adjustments and bugs that FindBugs picks up on and gives great guidance about.
Getting FindBugs
FindBugs is available as a command line tool, ant and swing interface and has a plugin for Eclipse and netbeans.
Downloads are available from the FindBugs download page
Integrating with Ant
FindBugs can be configured in ant to run as part of a static analysis test or during build each time as a code quality check.
Integration is simple and requires you to add the following rules to your jbuild.xml file:
<property name="findbugs.home" location="${lib.dir}/findbugs-3.0.0/" /> <taskdef name="findbugs" classname="edu.umd.cs.findbugs.anttask.FindBugsTask" />
This simply defines where FindBugs is located (findbugs.home) and defines the initial command FindBugs
<target name="findBugs" depends="jar"> <echo>[findBugs]</echo> <findbugs home="${findbugs.home}" includeFilter="findBugsRules.xml" output="html" outputFile="findbugs.html" failOnError="true"> <sourcePath path="${build.dir}/src" /> <class location="${dist.dir}/your_jar_here.jar" /> </findbugs> </target>
This defines the command and its parameters such as the path to the source you want it to scan and other self explanatory fields such as “failOnError” and “outputFile”. I recommend you keep the html as it provides an easy way to view the bugs and statistics about your code. More information about the structure of the build file can be found here.
The “includeFilter” parameter utilises the feature in FindBugs to include/exclude only certain rules when testing.
Using FindBugs in NetBeans
NetBeans is available inside NetBeans general download. To configure this, in NetBeans after installing the plugin, goto Tools->Options->Editor->Hints. Choose FindBugs as the language and it should display a tree list.
Here you can tick/untick the corresponding tests you want to run. To run the inspection simply goto Source->Inspect and select the Configuration as FindBugs. However, running the test with all the rules checked will normally result in a enormous about of bugs found in your code. It’s recommended that over the course of days and weeks you slowly activate and fix the different rules while still maintaining new code with those rules.
However, this list does not naturally sync with the an script list. To sync this private list with the “includeFilter” list that is used by ant you must find the private list file “global-settings.properties” for FindBugs which is normally located at “C:\…\AppData\Roaming\NetBeans\8.0\config\Preferences\org\netbeans\modules\findbugs” This file is a list of all the settings that you have selected, however to be used by ant it must first be converted to the correct xml format.
To do this we have written a small bit of code
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FindBugsRulesConverter { public static String"); xmlOutputWriter.write(list.toString()); xmlOutputWriter.newLine(); textInputReader.close(); //Write closing xml lines xmlOutputWriter.write(" </Match>"); xmlOutputWriter.newLine(); xmlOutputWriter.write("</FindBugsFilter>"); xmlOutputWriter.close(); }catch(final IOException e) { e.printStackTrace(); } } }
This will convert the properties file into a useful xml file containing the list of rules you want to include in the test, but remember to change “textInputRuleSet” and “xmlOutputRuleSet” to match the path to the appropriate files. This now allows you to easily generate the rules that you want to test for when using an ant script to run FindBugs. This helps to produce cleaner, faster and less buggy code after every build.
I hope you’ve enjoyed our article, please let us know in the comments below.
IDRsolutions develop a Java PDF library, a PDF forms to HTML5 converter, a PDF to HTML5 or SVG converter and a Java Image Library that doubles as an ImageIO replacement. On the blog our team post about anything interesting they learn about. | https://blog.idrsolutions.com/2014/12/using-findbugs-squash-bugs-java-netbeans-ant/ | CC-MAIN-2020-40 | refinedweb | 913 | 56.55 |
This is your resource to discuss support topics with your peers, and learn from each other.
04-20-2014 02:23 PM
Hi I just wanted to invoke calendar app from qml. So far I tried with no success. Any working code would be highly appreciated. Thanks.
04-21-2014 03:50 AM
Is many of workarounds of how to invoke calendar app. Hope the best way for you is use a Invoker class by greenmr
Here you have an invocations params
04-22-2014 12:34 PM
And why can't the following code work?
import bb.cascades 1.2 Page { Container { Button { text: qsTr("Click to edit Calendar") onClicked: { cal.trigger("bb.action.EDIT") } } } attachedObjects: [ Invocation { id: cal query { InvokeQuery { invokeActionId: "bb.action.EDIT" invokeTargetId: "sys.pim.calendar.view.eventcreate" mimeType: "text/calendar" } } } ] }
What's missing in the above code? Actually, I want to open the calendar app from my app in qml when a button is clicked. Any help would highly be appreciated. Thanks.
04-24-2014 11:21 AM - edited 04-24-2014 11:21 AM
Hi bDev,
Checkout this link for the exact way on how to use the Invocation API in QML: | https://supportforums.blackberry.com/t5/Native-Development/invoking-calendar-from-qml/m-p/2860792 | CC-MAIN-2017-04 | refinedweb | 198 | 66.94 |
Ok, here is how you write the shortest one
About... here's how it's done.
Sadly, it's pretty much impossible to put the code on the web because it has some really non-ascii stuff in it ;-)
Here's the key tricks (thanks to Remi and the others):
One of the key tricks is writing a short version of a very long octal number (or three).
I tried using base36 and int('gobledygook',36).
You could use 0xhexacodehere.
But here's the most space-efficient one: use base 256!
For each byte you want, create a char using chr(byte). Then paste them all together. Then put it in your code as a string. If you are lucky you will have no quotes or newlines in it, and the python interpreter will eat it.
You can later get the byte number x using ord('h!alsdf'[x]), and each byte by some dividing and modulo operation.
Another important piece is encoding 7 3-character strings as compactly as possible, and splitting them by offsets (which are encoded in the previosuly mentioned big number in base 8 ;-)
One extra squeeze is finding the shortest way to concatenate strings.
It's ''.join(), but if you are using it twice (or more), you save space by doing j=''.join and using j later.
Last one: Instead of defining a function, do a lambda:
def seven_seg(x): return .....
seven_seg=lambda x:
6 chars less!
And here is the shortest code I got so far (121 characters, requires python 2.4. On 2.2, it has to be 124).
In the contest, some guys are at 120. I don't know how. I can't even guess how ;-)
Update: it turns out I did know how to do it check it out I think it's the first public 120 :-)
BTW: you can't write that using kwrite. Vim works, though.
cool, well done.
I'd taken your earlier post and played around with [foo:][:3] instead of [foo::7], and also compressing the strings by overlapping 1st and last chars but you beat me to it. GHuess it didn't help that I was learnign python at the same time.
One other thing I tried was to note hat you only actually need one bit for each character. Try this:
[' |_'[(94685>>a&1)*((a/7&1)+1)] for a in range(21)]
But I coudln't see how to get the decoding compact enough to be a win
Probably soemthing could be done to do it with &7 and remake binary encoding of the data... Then it will be 119?
I do not have time to check, but maybe ' _...' thingie could be made shorter by ' '*2 trick - this way the end + the beginning serve too. However, my math intuition tells me it doesn help.
That's almost exactly like mine, except where you do '...'/u&14, I do '...'>>u&14, which takes one more character, but means later I use (6,0,3) (different numbers for a different string) where you use (64,8,1), and I get the one character back.
This is my 120 byte version, I made on change: the x7f was a literal ASCII code 127 in the submitted version.
j=''.join;seven_seg=lambda x:j(j(' _|?|'[ord('w$km>c&b;]for a in x for b in(2,1,4))+'n'for c in(6,3,0))
I can't wait to see the 119 byte one, it's killing me! I've tortured my mind for an hour trying to save one more byte, I think the 119 byte algorithm must be fundamentally different.
Joost: even worse: andre claims a 117 should be possible!
Joost: Just to torture you some more...
Indeed, I found a potential 117 character solution but the encoding string had some ascii character which couldn't be printed. (The way I built my solution was to write the encoding string directly to a file; I got a null file in that case.) I tried again, shifted all the values in the string by -1 and found a way (using a two character combination ...) to shift it back in my seven_seg.py program. There is perhaps a way to include the string that wouldn't "print" directly inside a file, thereby allowing for a 117 character solution.
Note that, other than my first name, I am posting this anonymously so as not to scoop the official announcement.
Any solution that contains non-printable chars doesn't look "clean" enough. BTW it's non-portable, and portability might count if you decide to incorporate this code into some embedded hardware (which it should belong to).
It is perfectly portable.
The default encoding for python source code is 8-bit ascii, and the program is written in 8-bit ascii.
If you need to use any other encoding you have to explicitly set it on a specially formatted comment, regardless of current locale.
And no, this kind of code doesn' t belong anywhere outside of a contest, IMHO :-) | https://ralsina.me/weblog/posts/P333.html | CC-MAIN-2021-17 | refinedweb | 847 | 82.04 |
\.info
@dircategory GnuPG
@direntry
* gpg: (gpg). GnuPG encryption and signing tool.
@end direntry
@node top
@top gpg
@end menu
@majorheading Name
gpg ---- encryption and signing tool>
@majorheading Synopsis
@majorheading DESCRIPTION
@code "---".
@majorheading COMMANDS
@code{gpg} recognizes these commands:
@table @asis
@item -s, ---sign
Make a signature. This command may be combined
with ---encrypt.
@item ---clearsign
Make a clear text signature.
@item -b, ---detach-sign
Make a detached signature.
@item -e, ---encrypt
Encrypt data. This option may be combined with ---sign.
@item -c, ---symmetric
Encrypt with a symmetric cipher using a passphrase. The default
symmetric cipher used is CAST5, but may be chosen with the
---cipher-algo option.
@item ---store
Store only (make a simple RFC1991 packet).
@item ---decrypt @code{file}
Decrypt @code
@item ---verify @code{sigfile} @code{signed-files}
Assume that @code @samp{-} as the second filename.
For security reasons a detached signature cannot read the signed
material from stdin without denoting it in the above way.
@item ---verify-files @code.
@item ---encrypt-files @code.
@item ---decrypt-files @code{files}
The same as ---encrypt-files with the difference that files will be
decrypted. The syntax or the filenames is the same.
@item ---list-keys @code{names}
@itemx ---list-public-keys @code{names}
List all keys from the public keyrings, or just the
ones given on the command line.
@item ---list-secret-keys @code{names}
List all keys from the secret keyrings, or just the ones given on the
command line. A '#' after the letters 'sec' means that the secret key
is not usable (for example, if it was created via
---export-secret-subkeys).
@item ---list-sigs @code{names}
Same as ---list-keys, but the signatures are listed too.
@item ---check-sigs @code{names}
Same as ---list-sigs, but the signatures are verified.
@item ---fingerprint @code.
@item ---list-packets
List only the sequence of packets. This is mainly
useful for debugging.
@item ---gen-key
Generate a new key pair. This command is normally only used
interactively.
There is an experimental feature which allows you to create keys
in batch mode. See the file @file{doc/DETAILS}
in the source distribution on how to use this.
@item ---edit-key @code{name}
Present a menu which enables you to do all key
related tasks:
@table @asis
@item repeated for all users specified
with -u.
@item lsign
Same as ---sign but the signature is marked as
non-exportable and will therefore never be used
by others. This may be used to make keys valid
only in the local environment.
@item nrsign
Same as ---sign but the signature is marked as non-revocable and can
therefore never be revoked.
@item nrlsign
Combines the functionality of nrsign and lsign to make a signature
that is both non-revocable and
non-exportable.
@item tsign
Make a trust signature. This is a signature that combines the notions
of certification (like a regular signature), and trust (like the
"trust" command). It is generally only useful in distinct communities
or groups.
@item revsig
Revoke a signature. For every signature which has been generated by
one of the secret keys, GnuPG asks whether a revocation certificate
should be generated.
@item trust
Change the owner trust value. This updates the
trust-db immediately and no save is required.
@item disable
@itemx enable
Disable or enable an entire key. A disabled key can not normally be
used for encryption.
@item adduid
Create an alternate user id.
@item addphoto
Create a photographic user id. This will prompt for a JPEG file that
will be embedded into the user ID.
@item deluid
Delete a user id.
@item revuid
Revoke a user id.
@item addkey
Add a subkey to this key.
@item delkey
Remove a subkey.
@item addrevoker
Add a designated revoker. This takes one optional argument:
"sensitive". If a designated revoker is marked as sensitive, it will
not be exported by default (see
export-options).
@item revkey
Revoke a subkey.
@item expire
Change the key expiration time. If a subkey is selected, the
expiration time of this subkey will be changed. With no selection,
the key expiration of the primary key is changed.
@item passwd
Change the passphrase of the secret key.
@item.
@item uid @code{n}
Toggle selection of user id with index @code{n}.
Use 0 to deselect all.
@item key @code{n}
Toggle selection of subkey with index @code{n}.
Use 0 to deselect all.
@item check
Check all selected user ids.
@item showphoto
Display the selected photographic user
id.
@item pref
List preferences from the selected user ID. This shows the actual
preferences, without including any implied preferences.
@item showpref
More verbose preferences listing for the selected user ID. This shows
the preferences in effect by including the implied preferences of
3DES (cipher), SHA-1 (digest), and Uncompressed (compression) if they
are not already included in the preference list.
@item setpref @code{string}
Set the list of user ID preferences to @code{string},.
@item.
@item toggle
Toggle between public and secret key listing.
@item save
Save all changes to the key rings and quit.
@item quit
Quit the program without updating the
key rings.
@end table:
@item ---sign-key @code{name}
Signs a public key with your secret key. This is a shortcut version of
the subcommand "sign" from ---edit.
@item ---lsign-key @code{name}
Signs a public key with your secret key but marks it as
non-exportable. This is a shortcut version of the subcommand "lsign"
from ---edit.
@item ---nrsign-key @code{name}
Signs a public key with your secret key but marks it as non-revocable.
This is a shortcut version of the subcommand "nrsign".
@item ---delete-secret-and-public-key @code{name}
Same as ---delete-key, but if a secret key exists, it will be removed
first. In batch mode the key must be specified by fingerprint.
@item ---gen-revoke
Generate a revocation certificate for the complete key. To revoke
a subkey or a signature, use the ---edit command.
@item ---desig-revoke
Generate a designated revocation certificate for a key. This allows a
user (with the permission of the keyholder) to revoke someone else's
key.
@item ---export @code.
@item ---send-keys @code{names}
Same as ---export but sends the keys to a keyserver.
Option ---keyserver must be used to give the name
of this keyserver. Don't send your complete keyring
to a keyserver - select only those keys which are new
or changed by you.
@item ---export-all @code{names}
Same as ---export, but also exports keys which
are not compatible with OpenPGP.
@item ---export-secret-keys @code{names}
@itemx ---export-secret-subkeys @code.
@item ---import @code{files}
@itemx ---fast-import @code.
@item ---recv-keys @code{key IDs}
Import the keys with the given key IDs from a keyserver. Option
---keyserver must be used to give the name of this keyserver.
@item ---refresh-keys @code{key IDs}
Request updates from a keyserver for keys that already exist on the
local keyring. This is useful for updating a key with the latest
signatures, user IDs, etc. Option ---keyserver must be used to give
the name of this keyserver.
@item ---search-keys @code{names}
Search the keyserver for the given names. Multiple names given here
will be joined together to create the search string for the keyserver.
Option ---keyserver must be used to give the name of this keyserver.
@item --.
@item --.
@item ---export-ownertrust
Send the ownertrust values to stdout. This is useful for backup
purposes as these values are the only ones which can't be re-created
from a corrupted trust DB.
@item ---import-ownertrust @code{files}
Update the trustdb with the ownertrust values stored
in @code{files} (or stdin if not given); existing
values will be overwritten.
@item ---rebuild-keydb-caches
When updating from version 1.0.6 to 1.0.7 this command should be used
to create signature caches in the keyring. It might be handy in other
situations too.
@item ---print-md @code{algo} @code{files}
@itemx ---print-mds @code{files}
Print message digest of algorithm ALGO for all given files or stdin.
With the second form (or a deprecated "*" as algo) digests for all
available algorithms are printed.
@item ---gen-random @code{0|1|2} @code{count}
Emit} @code{qbits}
Use the source, Luke :-). The output format is still subject to change.
@item ---version
Print version information along with a list
of supported algorithms.
@item ---warranty
Print warranty information.
@item -h, ---help
Print usage information. This is a really long list even though it
doesn't list all options. For every option, consult this manual.
@end table
@majorheading.
@code{gpg} recognizes these options:
@table @asis
@item -a, ---armor
Create ASCII armored output.
@item -o, ---output @code{file}
Write output to @code{file}.
@item ---mangle-dos-filenames
@itemx ---no-mangle-dos-filenames
The Windows version of GnuPG replaces the extension of an output
filename to avoid problems with filenames containing more than one
dot. This is not necessary for newer Windows versions and so
---no-mangle-dos-filenames can be used to switch this feature off and
have GnuPG append the new extension. This option has no effect on
non-Windows platforms.
@item -u, ---local-user @code{name}
Use @code{name} as the user ID to sign.
This option is silently ignored for the list commands,
so that it can be used in an options file.
@item ---default-key @code{name}
Use @code{name} as default user ID for signatures. If this
is not used the default user ID is the first user ID
found in the secret keyring.
.
@item ---no-default-recipient
Reset ---default-recipient and --default-recipient-self.
@item ---encrypt-to @code.
@item ---hidden-encrypt-to @code.
@item ---no-encrypt-to
Disable the use of all ---encrypt-to and --hidden-encrypt-to keys.
@item -v, ---verbose
Give more information during processing. If used
twice, the input data is listed in detail.
@item -q, ---quiet
Try to be as quiet as possible.
@item -z @code{n}, ---compress @code{n}
Set compression level to @code{n}. A value of 0 for @code{n}
disables compression. Default is to use the default
compression level of zlib (normally 6).
@item -t, ---textmode
@itemx ---no-textmode
Use canonical text mode. ---no-textmode disables this option..
@item -n, ---dry-run
Don't make any changes (this is not completely implemented).
@item -i, ---interactive
Prompt before overwriting any files.
@item ---batch
@itemx ---no-batch
Use batch mode. Never ask, do not allow interactive commands.
---no-batch disables this option.
@item ---no-tty
Make sure that the TTY (terminal) is never used for any output.
This option is needed in some cases because GnuPG sometimes prints
warnings to the TTY if ---batch is used.
@item ---yes
Assume "yes" on most questions.
@item ---no
Assume "no" on most questions.
@item ---default-cert-check-level @code.
@item ---trusted-key @code.
@item ---trust-model @code{pgp|classic|always}
Set what trust model GnuPG should follow. The models are:
@table @asis
@item pgp
This is the web-of-trust combined with trust signatures as used in PGP
5.x and later. This is the default trust model.
@item classic
This is the standard web-of-trust as used in PGP 2.x and earlier.
@item.
@end table
@item ---always-trust
Identical to `---trust-model always'
@item ---keyserver @code{name}
Use @code{name} as your keyserver. This is the server that ---recv-keys,
---send-keys, and --search-keys will communicate with to receive keys
from, send keys to, and search for keys on. The format of the
@code.
@item ---keyserver-options @code:
@table @asis
@item include-revoked
When searching for a key with ---search-keys, include keys that are
marked on the keyserver as revoked. Note that this option is always
set when using the NAI HKP keyserver, as this keyserver does not
differentiate between revoked and unrevoked keys.
@item include-disabled
When searching for a key with ---search-keys, include keys that are
marked on the keyserver as disabled. Note that this option is not
used with HKP keyservers.
@item include-subkeys
When receiving a key, include subkeys as potential targets. Note that honor-http-proxy
For keyserver schemes that use HTTP (such as HKP), try to access the
keyserver over the proxy set with the environment variable
"http_proxy".
@item auto-key-retrieve
This option enables the automatic retrieving of keys from a keyserver
when verifying signatures made by keys that are not on the local
keyring.
@end table
@item ---import-options @code{parameters}
This is a space or comma delimited string that gives options for
importing keys. Options can be prepended with a `no-' to give the
opposite meaning. The options are:
@table @asis
@item allow-local-sigs
Allow importing key signatures marked as "local". This is not
generally useful unless a shared keyring scheme is being used.
Defaults to no.
@item.
@end table
@item ---export-options @code{parameters}
This is a space or comma delimited string that gives options for
exporting keys. Options can be prepended with a `no-' to give the
opposite meaning. The options are:
@table @asis
@item include-non-rfc
Include non-RFC compliant keys in the export. Defaults to yes.
@item include-local-sigs
Allow exporting key signatures marked as "local". This is not
generally useful unless a shared keyring scheme is being used.
Defaults to no.
@item include-attributes
Include attribute user IDs (photo IDs) while exporting. This is
useful to export keys if they are going to be used by an OpenPGP
program that does not accept attribute user IDs. Defaults to yes.
@item include-sensitive-revkeys
Include designated revoker information that was marked as
"sensitive". Defaults to no.
@end table
@item ---show-photos
@itemx ---no-show-photos
Causes ---list-keys, --list-sigs, --list-public-keys,
---list-secret-keys, and verifying a signature to also display the
photo ID attached to the key, if any. See also ---photo-viewer.
---no-show-photos disables this option.
@item ---photo-viewer @code"
@item ---exec-path @code{string}
Sets a list of directories to search for photo viewers and keyserver
helpers. If not provided, keyserver helpers use the compiled-in
default directory, and photo viewers use the $PATH environment
variable.
@item ---show-keyring
Causes ---list-keys, --list-public-keys, and --list-secret-keys to
display the name of the keyring a given key resides on. This is only
useful when you're listing a specific key or set of keys. It has no
effect when listing all keys.
@item ---keyring @code{file}
Add @code{file} to the list of keyrings. If @code{file} begins with a
tilde and a slash, these are replaced by the HOME directory. If the
filename does not contain a slash, it is assumed to be in the GnuPG
home directory ("~/.gnupg" if ---homedir is not used). The filename
may be prefixed with a scheme:
"gnupg-ring:" is the default one.
It might make sense to use it together with ---no-default-keyring.
@item ---secret-keyring @code{file}
Same as ---keyring but for the secret keyrings.
@item ---primary-keyring @code{file}
Designate @code{file} as the primary public keyring. This means that
newly imported keys (via ---import or keyserver --recv-from) will go to
this keyring.
@item ---trustdb-name @code{file}
Use @code{file} instead of the default trustdb. If @code{file} begins
with a tilde and a slash, these are replaced by the HOME directory. If
the filename does not contain a slash, it is assumed to be in the
GnuPG home directory ("~/.gnupg" if ---homedir is not used).
---charset @code @code{name} are:
@table @asis
@item iso-8859-1
This is the Latin 1 set.
@item iso-8859-2
The Latin 2 set.
@item iso-8859-15
This is currently an alias for
the Latin 1 set.
@item koi8-r
The usual Russian set (rfc1489).
@item utf-8
Bypass all translations and assume
that the OS uses native UTF-8 encoding.
@end table
@item ---utf8-strings
@itemx --.
@item ---options @code{file}
Read options from @code{file} and do not try to read
them from the default options file in the homedir
(see ---homedir). This option is ignored if used
in an options file.
@item ---no-options
Shortcut for "---options /dev/null". This option is
detected before an attempt to open an option file.
Using this option will also prevent the creation of a
"~./gnupg" homedir.
@item ---load-extension @code{name}
Load an extension module. If @code{name} does not contain a slash it is
searched for in the directory configured when GnuPG was built
(generally "/usr/local/lib/gnupg"). Extensions are not generally
useful anymore, and the use of this option is deprecated.
@item ---debug @code{flags}
Set debugging flags. All flags are or-ed and @code{flags} may
be given in C syntax (e.g. 0x0042).
@item ---debug-all
Set all useful debugging flags.
@item ---enable-progress-filter
Enable certain PROGRESS status outputs. This option allows frontends
to display a progress indicator while gpg is processing larger files.
There is a slight performance overhead using it.
@item ---status-fd @code{n}
Write special status strings to the file descriptor @code{n}.
See the file DETAILS in the documentation for a listing of them.
@item ---logger-fd @code{n}
Write log output to file descriptor @code{n} and not to stderr.
---no-comment
See ---no-sk-comments. This option is deprecated and may be removed
soon.
@item ---comment @code{string}
Use @code{string} as the comment string in clear text signatures. The
default behavior is not to use a comment string.
@item ---default-comment
Force to write the standard comment string in clear
text signatures. Use this to overwrite a ---comment
from a config file. This option is now obsolete because there is no
default comment string anymore.
@item ---emit-version
@itemx ---no-emit-version
Force inclusion of the version string in ASCII armored output.
---no-emit-version disables this option.
@item ---sig-notation @code{name=value}
@itemx ---cert-notation @code{name=value}
@itemx -N, ---notation-data @code{name=value}
Put the name value pair into the signature as notation data.
@code{name} must consist only of printable characters or spaces, and
must contain a '@@' character. This is to help prevent pollution of
the IETF reserved notation namespace. The ---expert flag overrides the
'@@' check. @code{value} may be any printable string; it will be
encoded in UTF8, so you should check that your ---charset is set
correctly. If you prefix @code{name} with an exclamation mark, the
notation data will be flagged as critical (rfc2440:5.2.3.15).
---sig-notation sets a notation for data signatures. --cert-notation
sets a notation for key signatures (certifications). ---notation-data
sets both.
There are special codes that may be used in notation names. "%k" will
be expanded into the key ID of the key being signed, "%K" for the long
key ID of the key being signed, "%f" for the key fingerprint of the
key being signed, "%s" for the key ID of the key making the signature,
"%S" for the long key ID of the key making the signature, and "%%"
results in a single "%". %k, %K, and %f are only meaningful when
making a key signature (certification).
@item ---show-notation
@itemx ---no-show-notation
Show signature notations in the ---list-sigs or --check-sigs listings
as well as when verifying a signature with a notation in it.
---no-show-notation disables this option.
@item ---sig-policy-url @code{string}
@itemx ---cert-policy-url @code{string}
@itemx ---set-policy-url @code{string}
Use @code{string} as Policy URL for signatures (rfc2440:5.2.3.19). If
you prefix it with an exclamation mark, the policy URL packet will be
flagged as critical. ---sig-policy-url sets a a policy url for data
signatures. ---cert-policy-url sets a policy url for key signatures
(certifications). ---set-policy-url sets both.
The same %-expandos used for notation data are available here as well.
@item ---show-policy-url
@itemx ---no-show-policy-url
Show policy URLs in the ---list-sigs or --check-sigs listings as well
as when verifying a signature with a policy URL in it.
---no-show-policy-url disables this option.
@item ---set-filename @code{string}
Use @code{string} as the filename which is stored inside messages.
This overrides the default, which is to use the actual filename of the
file being encrypted.
@item ---for-your-eyes-only
@itemx --.
@item ---use-embedded-filename
Try to create a file with a name as embedded in the data.
This can be a dangerous option as it allows to overwrite files.
@item ---completes-needed @code{n}
Number of completely trusted users to introduce a new
key signer (defaults to 1).
@item ---marginals-needed @code{n}
Number of marginally trusted users to introduce a new
key signer (defaults to 3)
@item ---max-cert-depth @code{n}.
@item ---digest-algo @code{name}
Use @code{name} as the message digest algorithm. Running the program
with the command ---version yields a list of supported algorithms.
@item ---compress-algo @code{name}
Use compression algorithm @code{name}. "zlib" is RFC1950 ZLIB
compression. "zip" is RFC-1951 ZIP compression which is used by PGP.
"uncompressed" or "none" disables compression. If this option is not
used, the default behavior is to examine the recipient key preferences
to see which algorithms the recipient supports. If all else fails,
ZIP is used for maximum compatibility. Note, however, that ZLIB may
give better compression results if that is more important, as the
compression window size is not limited to 8k.
@item ---cert-digest-algo @code{name}
Use @code.
@item ---s2k-cipher-algo @code{name}
Use @code{name} as the cipher algorithm used to protect secret keys.
The default cipher is CAST5. This cipher is also used for
conventional encryption if ---personal-cipher-preferences and
---cipher-algo is not given.
@item ---s2k-digest-algo @code{name}
Use @code{name} as the digest algorithm used to mangle the passphrases.
The default algorithm is SHA-1.
@item ---s2k-mode @code{n}
Selects how passphrases are mangled. If @code.
@item --).
@item ---disable-cipher-algo @code{name}
Never allow the use of @code{name} as cipher algorithm.
The given name will not be checked so that a later loaded algorithm
will still get disabled.
@item ---disable-pubkey-algo @code{name}
Never allow the use of @code{name} as public key algorithm.
The given name will not be checked so that a later loaded algorithm
will still get disabled.
@item --.
@item --.
@item ---auto-check-trustdb
@itemx ---no-auto-check-trustdb
If GnuPG feels that its information about the Web-of-Trust has to be
updated, it automatically runs the ---check-trustdb command internally.
This may be a time consuming process. ---no-auto-check-trustdb
disables this option.
@item ---throw-keyid
Do not put the keyids into encrypted packets. This option hides the
receiver of the message and is a countermeasure against traffic
analysis. It may slow down the decryption process because all
available secret keys are tried.
@item ---no-throw-keyid
Resets the ---throw-keyid option.
@item --.
@item ---escape-from-lines
@itemx --.
.
@item ---command-fd @code.
@item ---use-agent
@itemx ---no-use-agent
Try to use the GnuPG-Agent. Please note that this agent is still under
development. With this option, GnuPG first tries to connect to the
agent before it asks for a passphrase. ---no-use-agent disables this
option.
@item ---gpg-agent-info
Override the value of the environment variable
@samp{GPG_AGENT_INFO}. This is only used when ---use-agent has been given
@item.
@table @asis
@item --.
.
@item ---rfc1991
Try to be more RFC-1991 (PGP 2.x) compliant.
@item --.
@item --id, and making signatures with signing subkeys as PGP 6
does not understand signatures made by signing subkeys.
This option implies `---disable-mdc --no-sk-comment --escape-from-lines
---force-v3-sigs --no-ask-sig-expire'
@item --.
@item ---pgp8
Set up all options to be as PGP 8 compliant as possible. PGP 8 is a
lot closer to the OpenPGP standard than previous versions of PGP, so
all this does is disable ---throw-keyid and set --escape-from-lines.
The allowed algorithms list is the same as ---pgp7 with the addition of
the SHA-256 digest algorithm.
@end table
@item ---force-v3-sigs
@itemx ---no disables this
option.
@item ---force-v4-certs
@itemx ---no-force-v4-certs
Always use v4 key signatures even on v3 keys. This option also
changes the default hash algorithm for v3 RSA keys from MD5 to SHA-1.
---no-force-v4-certs disables this option.
@item --
Disable the use of the modification detection code. Note that by
using this option, the encrypted message becomes vulnerable to a
message modification attack.
@item ---allow-non-selfsigned-uid
@itemx ---no-allow-non-selfsigned-uid
Allow the import and use of keys with user IDs which are not
self-signed. This is not recommended, as a non self-signed user ID is
trivial to forge. ---no-allow-non-selfsigned-uid disables.
@item ---allow-freeform-uid
Disable all checks on the form of the user ID while generating a new
one. This option should only be used in very special environments as
it does not ensure the de-facto standard format of user IDs.
@item ---ignore-time-conflict
GnuPG normally checks that the timestamps associated with keys and
signatures have plausible values. However, sometimes a signature seems to
be older than the key due to clock problems. This option makes these
checks just a warning.
@item ---ignore-valid-from
GnuPG normally does not select and use subkeys created in the future. This
option allows the use of such keys and thus exhibits the pre-1.0.7
behaviour. You should not use this option unless you there is some
clock problem.
@item --.
@item --.
@item ---lock-once
Lock the databases the first time a lock is requested
and do not release the lock until the process
terminates.
@item ---lock-multiple
Release the locks every time a lock is no longer
needed. Use this to override a previous ---lock-once
from a config file.
.
@item ---no-random-seed-file
GnuPG uses a file to store its internal random pool over invocations.
This makes random generation faster; however sometimes write operations
are not desired. This option can be used to achieve that with the cost of
slower random generation.
@item ---no-verbose
Reset verbose level to 0.
@item ---no-greeting
Suppress the initial copyright message.
@item ---no-secmem-warning
Suppress the warning about "using insecure memory".
@item ---no-permission-warning
Suppress the warning about unsafe file permissions. Note that the
file permission checks that GnuPG performs are not intended to be
authoritative, rather they simply warn about certain common permission
problems. Do not assume that the lack of a warning means that your
system is secure.
@item ---no-mdc-warning
Suppress the warning about missing MDC integrity protection.
@item ---no-armor
Assume the input data is not in ASCII armored format.
@item ---no-default-keyring
Do not add the default keyrings to the list of
keyrings.
@item ---skip-verify
Skip the signature verification step. This may be
used to make the decryption faster if the signature
verification is not needed.
@item ---with-colons
Print key listings delimited by colons. Note, that the output will be
encoded in UTF-8 regardless of any ---charset setting.
@item ---with-key-data
Print key listings delimited by colons (like ---with-colons) and print the public key data.
@item ---with-fingerprint
Same as the command ---fingerprint but changes only the format of the output
and may be used together with another command.
@item --.
@item ---fixed-list-mode
Do not merge primary user ID and primary key in ---with-colon listing
mode and print all timestamps as seconds since 1970-01-01.
@item ---list-only
Changes the behaviour of some commands. This is like ---dry-run but
different in some cases. The semantic of this command may be extended in
the future. Currently it only skips the actual decryption pass and
therefore enables a fast listing of the encryption keys.
@item ---no-literal
This is not for normal use. Use the source to see for what it might be useful.
@item ---set-filesize
This is not for normal use. Use the source to see for what it might be useful.
@item --.
@item --.
@item ---override-session-key @code{string}
Don't use the public key but the session key @code.
@item ---ask-sig-expire
@itemx ---no-ask-sig-expire
When making a data signature, prompt for an expiration time. If this
option is not specified, the expiration time is "never".
---no-ask-sig-expire disables this option.
@item ---ask-cert-expire
@itemx ---no-ask-cert-expire
When making a key signature, prompt for an expiration time. If this
option is not specified, the expiration time is "never".
---no-ask-cert-expire disables this option.
@item ---expert
@itemx ---no-expert
Allow the user to do certain nonsensical or "silly" things like
things like generating deprecated key types. This also disables
certain warning messages about potentially incompatible actions. As
the name implies, this option is for experts only. If you don't fully
understand the implications of what it allows you to do, leave this
off. ---no-expert disables this option.
@item ---merge-only
Don't insert new keys into the keyrings while doing an import.
@item ---allow-secret-key-import
This is an obsolete option and is not used anywhere.
@item --.
@item ---enable-special-filenames
This options enables a mode in which filenames of the form
@file{-&n}, where n is a non-negative decimal number,
refer to the file descriptor n and not to a file with that name.
@item ---no-expensive-trust-checks
Experimental use only.
@item ---group @code{name=value1 value2 value3 ...}
Sets up a named group, which is similar to aliases in email programs.
Any time the group name is a recipient (-r or ---recipient), it will
be expanded to the values specified.
The values are @code.
@item ---preserve-permissions
Don't change the permissions of a secret keyring back to user
read/write only. Use this option only if you really know what you are doing.
@item ---personal-cipher-preferences @code{string}
Set the list of personal cipher preferences to @code.
@item ---personal-digest-preferences @code{string}
Set the list of personal digest preferences to @code
@item ---personal-compress-preferences @code{string}
Set the list of personal compression preferences to @code).
@item ---default-preference-list @code{string}
Set the list of default preferences to @code{string}, this list should
be a string similar to the one printed by the command "pref" in the
edit menu. This affects both key generation and "updpref" in the edit
@end table
@major.
@item 234AABBCC34567C4
@itemx 0F323456784E56EAB
@itemx 01AB3FED1347A5612
@itemx 0x234AABBCC34567C4
Here the key ID is given in the long form as used by OpenPGP
(you can get the long key ID using the option ---with-colons).
@item 1234343434343434C434343434343434
@itemx 123434343434343C3434343434343734349A3434
@itemx 0E12343434343434343434EAB3484343434343434
@itemx).
@item =Heinrich Heine
Using an exact to match string. The equal sign indicates this.
@item
Using the email address part which must match exactly. The left angle bracket
indicates this email address mode.
@item +Heinrich Heine duesseldorf
All words must match exactly (not case sensitive) but can appear in
any order in the user ID. Words are any sequences of letters,
digits, the underscore and all characters with bit 7 set.
exactly the given primary
or secondary key and not to try to figure out which secondary or
primary key to use.
@majorheading RETURN VALUE
The program returns 0 if everything was fine, 1 if at least
a signature was bad, and other error codes for fatal errors.
@majorheading EXAMPLES
@table @asis
@item gpg -se -r @code{Bob} @code{file}
sign and encrypt for user Bob
@item gpg ---clearsign @code{file}
make a clear text signature
@item gpg -sb @code{file}
make a detached signature
@item gpg ---list-keys @code{user_ID}
show keys
@item gpg ---fingerprint @code{user_ID}
show fingerprint
@item gpg ---verify @code{pgpfile}
@itemx gpg ---verify @code{sigfile} @code{files}
Verify the signature of the file but do not output the data. The second form
is used for detached signatures, where @code{sigfile} is the detached
signature (either ASCII armored of binary) and @code{files} are the signed
data; if this is not given the name of the file holding the signed data is
constructed by cutting off the extension (".asc" or ".sig") of
@code{sigfile} or by asking the user for the filename.
@end table
@majorheading ENVIRONMENT
@table @asis
@item HOME
Used to locate the default home directory.
@item GNUPGHOME
If set directory used instead of "~/.gnupg".
@item.
@item http_proxy
Only honored when the keyserver-option
honor-http-proxy is set.
@end table
@majorheading FILES
@table @asis
~/.gnupg/gpg.conf
Default configuration file
@item ~/.gnupg/options
Old style configuration file; only used when gpg.conf
is not found
@item /usr[/local]/share/gnupg/options.skel
Skeleton options file
@item /usr[/local]/lib/gnupg/
Default location for extensions
@end table
@majorheading @samp{-} to specify stdin.
@majorheading version of official PGP supports
the BLOWFISH cipher algorithm. If you use it, no PGP user will be
able to decrypt your message. The same thing applies to the ZLIB
compression algorithm. By default, GnuPG uses the OpenPGP preferences
system that will always do the right thing and create messages that
are usable by all recipients, regardless of which OpenPGP program they
use. Only override this safe default if you know what you are doing.
If you absolutely must override the safe default, or if the
preferences on a given key are invalid for some reason, you are far
better off using the ---pgp2, --pgp6, --pgp7, or --pgp8 options. These
options are safe as they do not force any particular algorithms in
violation of OpenPGP, but rather reduce the available algorithms to a
"PGP-safe" list.
@majorheading.
@bye | http://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob_plain;f=doc/gpg.texi;hb=27ec3d920162edc2b4f3a3a2a5691df52b60461d | CC-MAIN-2019-39 | refinedweb | 5,607 | 58.89 |
None
0 Points
Jun 16, 2005 08:15 AM|jbowen|LINK
You may be able accomplish what you want using the Request.Servervariables("REMOTE_ADDR") header.
These may help:
All-Star
17785 Points
Aug 19, 2006 01:27 PM|vik20000in|LINK
Oct 30, 2006 03:41 AM|etariq|LINK
HttpContext.Current.Request.UserHostAddress;
or
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
To get the IP address of the machine and not the proxy use the following code
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
Get users IP address
Jul 13, 2007 09:33 AM|eramseur|LINK
Take a look at the log module as it shows IP information. You can just copy that functionality.
Jul 13, 2007 10:18 AM|eramseur|LINK
Rainbow has a log module. You can find this on the portal by going on the Admin menu and clicking on logs and then Monitoring and Logs. This will show you IP info and you can get the functionality from DesktopModules\Monitoring.
Jul 13, 2007 10:29 AM|eramseur|LINK
When you login to rainbow, you see the admin menu correct? Off of the admin menu is a logs tab, off the logs tab is monitoring. I dont mean admin to the server; I mean admin to your portal.
None
0 Points
Jan 08, 2008 01:42 AM|balamurugan nagarajan|LINK
Getting user's country name using ip Address
Jan 24, 2008 01:16 PM|vitta|LINK
Even I have simillar kind of problem.
We have intranet application and I need to cature the IPAddress of the client.
I am trying to capture the remote address.
I tried in different ways as below.. but the result of all is 127.0.0.1
HttpContext.Current.Request.ServerVariables(
I guess firewall/NAT Box hiding internal IP addresses.
is there any way to get actual IP.
Thanks in advance.
Feb 06, 2008 08:54 AM|zestq|LINK
Hi vitta, I got the same problem and I found the solution by doing dis:
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
I got this solution from C# corner. website
client ip address
Member
10 Points
Feb 12, 2008 02:22 AM|satender88|LINK
This example demonstrates how to find out the visitor's browser type, IP address, and more:
<html> <body> <p> <b>You are browsing this site with:</b> <%Response.Write(Request.ServerVariables("http_user_agent"))%> </p> <p> <b>Your IP address is:</b> <%Response.Write(Request.ServerVariables("remote_addr"))%> </p> <p> <b>The DNS lookup of the IP address is:</b> <%Response.Write(Request.ServerVariables("remote_host"))%> </p> <p> <b>The method used to call the page:</b> <%Response.Write(Request.ServerVariables("request_method"))%> </p> <p> <b>The server's domain name:</b> <%Response.Write(Request.ServerVariables("server_name"))%> </p> <p> <b>The server's port:</b> <%Response.Write(Request.ServerVariables("server_port"))%> </p> <p> <b>The server's software:</b> <%Response.Write(Request.ServerVariables("server_software"))%> </p> </body> </html>
ip
Mar 31, 2008 04:22 PM|vitta|LINK
Thanks Zestq..its working fine.. This is what I exactly want..
I really wonder why others given examples with server variables.
I already said, I tried with server variables and couldnt succeed in INTRNET environment where proxy is hiding the original IP.
API's under DNS class are solution for my problem.
Thanks again Zestq
Member
62 Points
Apr 13, 2008 03:14 PM|Simon Deshaies|LINK
etariq
HttpContext.Current.Request.UserHostAddress;To get the IP address of the machine and not the proxy use the following code
or
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
Thanks this works for me.
HttpContext.Current.Request.UserHostAddress;
So I can log every user login and their IP.
I use it like this in c#. Using
This Sql Connection class as MySql.
MySqlConnection MySql = new MySqlConnection();
string ip = HttpContext.Current.Request.UserHostAddress;
MySql.CreateConn();
MySql.Command = MySql.Connection.CreateCommand();
MySql.Command.CommandType = CommandType.Text;
MySql.Command.CommandText = "INSERT INTO dbo.[log.login] (userID, IP, DateTimeStamp, TargetPage) VALUES (" + myUserID + ", '" + ip + "', '" + DateTime.Now + "', '" + Server.UrlDecode(Request.QueryString["p"]) + "')";
MySql.Command.ExecuteNonQuery();
MySql.Command.Dispose();
MySql.CloseConn();
May 04, 2008 09:13 AM|Rizwan328|LINK
Thanks ZESTQ, It really works for me......
May 07, 2008 10:44 PM|Hideyoshi|LINK
dear zestq,
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
I got this solution from C# corner. website
for the solution that you provided on February, Do u know how to solve it by using vb.NET?
Hope to hear anyone of you, thank you
Jun 12, 2008 07:14 AM|zestq|LINK
Hi guyz, The solution I have provided gives the IP Address but If you look into it, It gives you the server IP not the client;s IP Address, while I guess we all need the client's IP Address or the visitor's IP.
To get the Client's IP Address, try this:
stringclientIPAddress = this.Page.Request.ServerVariables["REMOTE_ADDR"];
NOTE: when you run this it will give you "127.0.0.1", this is because, you are using from the HOST Machine i.e. the application is on ur machine and it is giving you, ur IP address but when any visitor or client hits ur page it will give you the exact IP Address of the Client.
I have checked this on my LAN and its working fine,,,,,try this and if it fails do inform me or any 1 got any better solution please let me know.
client ip address visitors ip address client machine ip address
Jun 12, 2008 07:21 AM|zestq|LINK
Hi Hideyoshi here is the VB version of both of my codes:
Dim strHostName As String = System.Net.Dns.GetHostName()
Dim clientIPAddress As String = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString()
Dim clientIPAddress As String = Me.Page.Request.ServerVariables("REMOTE_ADDR"
Following site address is the converter of VB.NET code to C# and vice versa (I have also used this site 2 convert my code).
VB.NET code to C# Converter
Nov 10, 2008 02:41 AM|TATWORTH|LINK
>I want to get the time zone of the Ip Address.how to get the timezone of the particular IP
IP Address is frequently wrong even on country let alone Time Zone within a country. Whilst being in the UK, I have been told that according to my IP address one time I was in Germany and another in the US. Given the way IP address blocks are allocated
to an Internet Service Provider, it is quite lilely that a national ISP in the US willl have users from a different time zone to where that block is registered.
Nov 10, 2008 10:48 AM|Rizwan328|LINK
GeoByte is providing good services like these.......
following link may help you
Member
1 Points
Nov 14, 2008 09:15 AM|mick breen|LINK
Good Post but I want to removed the domain and only keep the host name eg
Q1111.xxxxx.xx.xx.xx
I only want Q1111.
My code that returns the Q1111.xxxxx.xx.xx.xx is on page load as follows:System.Net.IPHostEntry HostIP = new System.Net.IPHostEntry();HostIP = System.Net.Dns.GetHostEntry(Request.ServerVariables["Remote_Host"]);
lbl_NetBiosNameDetail.Text = HostIP.HostName;
Can anyone assist?
Mick
Nov 14, 2008 09:26 AM|TATWORTH|LINK
I will write you some code for you, once I clarify what you require. You cited Q1111.xxxxx.xx.xx.xx
IP addresses have four components, but you show 5.
However you may like to go to and try the IP Extensions project.
Member
1 Points
Nov 14, 2008 09:58 AM|TATWORTH|LINK
Here is the function plus some unit test code
#region " Copyle
#endregion
namespace Demo
{
using System;
using NUnit.Framework;
/// <summary>
/// IpAddressTest
/// </summary>
[TestFixture]
public class IpAddressTest
{
/// <summary>
/// Test GetBlock1
/// </summary>
[Test]
public void GetBlock1Test1()
{
Assert.AreEqual("123", GetBlock1("123.111.222.103"));
}
/// <summary>
/// Test GetBlock1
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void GetBlock1Test2()
{
Assert.AreEqual("123", GetBlock1("123.111.222"));
}
/// <summary>
/// Get Block 1
/// </summary>
/// <param name="input">IP Address</param>
/// <returns>Block 1</returns>
public string GetBlock1(string input)
{
var work = (string.Empty + input).Split('.');
if (work.Length != 4)
{
throw new ArgumentException("input is not in form xxx.xxx.xxx.xxx");
}
return work[0];
}
}
}
Member
171 Points
Jan 20, 2009 04:53 AM|svibuk|LINK
i am using Dim IPAddress IPAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR") If IPAddress = "" Then IPAddress = Request.ServerVariables("REMOTE_ADDR") End If but i am getting 127.0.0.1 i suppose i am getting it due to my local host
based on this ip i need to find the country of that IP using vb.net or javascript. how ca i achieve it
hope to get help
country ip address
Jan 20, 2009 09:56 AM|TATWORTH|LINK
>based on this ip i need to find the country of that IP using vb.net or javascript. how ca i achieve it
Getting Country from IP address is somewhat problematical. For example whist I have been in the United Kingdom, I have been told that I am in Germany one and in America at another time.
Code for Address look up
Star
9953 Points
Jan 28, 2009 05:14 AM|yrb.yogi|LINK
Get Users IP address...???
but How???
can u expalin me????
All-Star
52658 Points
Jan 28, 2009 05:32 AM|mudassarkhan|LINK
yrb.yogi<div id=ctl00_ctl00_bcr_bcr_PostForm__QuoteText>
Get Users IP address...???
but How???
can u expalin me????</div>
Jan 28, 2009 05:40 AM|TATWORTH|LINK
You can get the user's IP Address by:
var useraddress = Request.UserHostAddress;
For details, see:
Jan 28, 2009 05:45 AM|TATWORTH|LINK
Or more fully using the function I gave earlier.
var useraddress = Request.UserHostAddress;
var test = IPAddress.Parse(useraddress);
var result = CommonData.IPAddressToBytes(test);
lblOutput.Text = result[0] + "." + result[1] + "." + result[2] + "." + result[3];
This displays (not surpringly) 127.0.0.1
None
0 Points
May 02, 2009 02:58 AM|sunnyhasan|LINK
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
Is the uppoer statement returning the client ip address? That is a hexcode. But IP address should not be in that format right?
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(1).ToString(); I have used this GetValue(1) instead GetValue(0).
Is that ok? Can you please explain that? I need to log all the ip address of the users when they visit a specific website...please help me.
Thanks.
-
ip ip address
May 02, 2009 05:39 AM|TATWORTH|LINK
Try
var ipAddress = Request.UserHostAddress.ToString();
or if using an earlier version of the framework
string ipAddress = Request.UserHostAddress.ToString();
Nov 05, 2009 05:44 AM|Manwatkar|LINK
dear sir.
i have applied your code in my project
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
but it working correctly on localhost but when i am trying on the server it is giving as address like this 10.49.23.4 which address is this please reply me what is the problem....my email address is pank_manwatkar2007@yahoo.com thanks in advance....
None
0 Points
None
0 Points
Nov 15, 2009 02:42 PM|jamalqudah|LINK
simply if you run the code on a class or the global you wont be able to get the remote IP address
just run this code on any code behind page and you'll get the remote user IP
Request.UserHostName
you can try my URL
if you need the IP on the class just pass it through string
hope this help
Dec 19, 2009 12:23 PM|samuel24|LINK
Hi Getting users Ip address code is in the below link.may be it will useful for some one.
Get users IP address
None
0 Points
Dec 19, 2009 01:27 PM|jamalqudah|LINK
just use this code
">if you need to use inside the class just pass it with the class<">ex code:</div>
inside the code behind page page.aspx.vb not inside a class and it will work
if you need to use inside the class just pass it with the class
ex code:Imports Microsoft.VisualBasic Public Class Testing Public Shared Function TEsting(ByVal IPaddress As string) As String 'insert to database as log dim IP as string = IPaddress connect.ExecuteScaler("INSERT INTO blabla(IP_Address) " & _ "VALUES (" & IPaddress & ")") Dim result As String = "" Return result End Function End Class
in code behind page call the function and pass the IP
TEsting(Request.UserHostName)
thats it
hope this help
Mar 01, 2011 02:12 AM|raji539|LINK
if ur want in assemblly..
string strHostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); IPAddress[] addr = ipEntry.AddressList; string ipAddress = addr[0].ToString();
if ur using web application
HttpContext.Current.Request.UserHostAddress
Participant
949 Points
Mar 02, 2011 11:40 PM|chandradev1|LINK
Hi
check this code
protected void Button1_Click(object sender, EventArgs e) { string strHostName = System.Net.Dns.GetHostName(); string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString(); SqlCommand cmd = new SqlCommand(“insert into tblIpAddress(IPAddress)values(@IPAddress)”, con); cmd.Parameters.AddWithValue(“@IPAddress”, clientIPAddress); con.Open(); cmd.ExecuteNonQuery(); con.Close(); }
Member
120 Points
Mar 02, 2011 11:57 PM|prakash.radhwani|LINK
//use the below code Session["ipAddress"] = Request.ServerVariables["REMOTE_HOST"]; Session["macAddress"] = GetMacAddress(Session["ipAddress"].ToString()); public string GetMacAddress(string IPAddress) { string strMacAddress = string.Empty ; try { string strTempMacAddress= string.Empty ; ProcessStartInfo objProcessStartInfo = new ProcessStartInfo(); Process objProcess = new Process(); objProcessStartInfo.FileName = "nbtstat"; objProcessStartInfo.RedirectStandardInput = false; objProcessStartInfo.RedirectStandardOutput = true; objProcessStartInfo.Arguments = "-A " + IPAddress; objProcessStartInfo.UseShellExecute = false; objProcess = Process.Start(objProcessStartInfo); int Counter = -1; while (Counter <= -1) { Counter = strTempMacAddress.Trim().ToLower().IndexOf("mac address", 0); if (Counter > -1) { break; } strTempMacAddress = objProcess.StandardOutput.ReadLine(); } objProcess.WaitForExit(); strMacAddress = strTempMacAddress.Trim(); } catch (Exception Ex) { //Console.WriteLine(Ex.ToString()); //Console.ReadLine(); } return strMacAddress; }
47 replies
Last post Mar 02, 2011 11:57 PM by prakash.radhwani | https://forums.asp.net/t/892765.aspx | CC-MAIN-2017-30 | refinedweb | 2,303 | 50.94 |
I'm about to plunge into some code to convert various musical note formats back and forth - "BB-" <->"Bb2" <->"bf3" etc. Looking around, I guess there are between 5 and 10 different formats that I'll eventually want to build in.
My problem is how to structure this. Possible options would appear to be...
One wrinkle is that different formats may require / return additional parameters - ABC format, for instance, sets up a key and a default octave as part of its header, so they may need to be passed in ("F" in the key "D" would convert to "F#" etc.).
Atm, I'm favouring the named parameter style (easy to maintain and pass extra parameters ) but I'd be grateful for any input before I "get my coding pencil out" :)
Cheers, Ben.
Title edit by tye
Nevertheless I don't think you need any "convert-from-to" routines.
What I think you would need is:
'No param' OO style - notetype->new("BB-","kern")->as_abc()
I like that one best. I'd just convert everything to an internal format on object creation, though. SomeClass->new(type => "notetype", ...)->as_abc. From there, you can create very simple wrappers for people who like different methods better, so everyone can have it their way.
Juerd
# { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }
The way to think about this is to consider Date::Calc or Date::Manip, two standard date manipulation modules. You give them a date string in pretty much any format and they will parse it. You can then manipulate it in nearly any way you can think of. You can then ask for the date back in pretty much any format.
The point here is that Date::Calc doesn't store weekdays as Monday, Tuesday, etc. It stores them as 1, 2, etc. But, it knows how to convert Day 1 to Monday (or lundi, or Mon, or whatever.), or vice versa. That's what you should strive few interesting links:
A Representation and Conversion System for Musical Notation; and
Music Notation Links (has some Perl scripts);
also do your own search :)
Ben
Doh! Yes indeed. This is all part of an ongoing discussion about how stuff should be represented in the Music:: namespace, once I get around to writing Music::Chord and Music::Keysignature etc. I'd so far been going with ISO format for input/output, just because it looked nicer :)
Thinking just a little into the future though (I *must* get into the habit of doing that :) ), it'd make a lot more sense if eveything dealt with Music::Note objects - I then get to do all the cool functions like $note->transpose(), $note->enharmonic_equivalent('natural') and $note->is_jazz_accidental_and_not_a_mistake().
Thanks all - I knew that posting would save me days of re-coding :)
Priority 1, Priority 2, Priority 3
Priority 1, Priority 0, Priority -1
Urgent, important, favour
Data loss, bug, enhancement
Out of scope, out of budget, out of line
Family, friends, work
Impossible, inconceivable, implemented
Other priorities
Results (252 votes),
past polls | http://www.perlmonks.org/?node_id=283141 | CC-MAIN-2015-32 | refinedweb | 505 | 59.94 |
Results 1 to 7 of 7
isometric tile game (swapdepths problems?)
hi
Hoi
Ok am working on a iso type game too.
Not as far as you.
I looked at you fla and I hope you don't mind but I don't feel like looking through all your code
but I did note that you swap the depths of all your tiles and hero...bad idea. You are going to make a mess of all your depths so this is that I was thinking of
Have each tile on its own depth and never change it. The topmost tile has the lows depth and the lowest tile have the highest depth. Then the have the rest of you tile in between that. Keep some space in between the depths of your tiles, 2 or more see attachment
just look at one of the tiles, if you look at the tiles above it your depths are all lower and if you look at the tile under it, are all higher
like this they are all nicely sorted. The spaces are for the hero to move around in. ok here is a function the calculates the depth
Code:
calculateDepth = function(x, z, worldXMax, worldZMax ) { var leeway = 2; var x = Math.abs(x)*leeway; var z = Math.abs(z)*leeway; var a = worldXMax; var b = worldYMax; var floor = a*(b-1)+x; var depth = a*(z-1)+x+floor; return depth; };
There
hope that helps
.....
cool - thanks for the reply.
I'll have a go at that tonight!
bit quiet at work at the moment, so I thought I'd try it quickly. I had to change your code slightly as my tile (0,0) is the furthest left tile (as in the kirupa isometry tutorial) and got this:
PHP Code:
function calculatedepth (tilecoordx, tilecoordy, obj) {
var factor = 2;
// factor is the space between 1 tile's depth and the next
var tiledepth = ((maplengthy-tilecoordy)*10)+(tilecoordx*factor);
if (obj == "tile") {
return tiledepth;
} else {
// for hero's depth:
return (tiledepth+1);
}
}
I've altered the draw map function to this:
PHP Code:
function buildmap () {
for (var x = (herox-visx); x<=(herox+visx); x++) {
for (var y = (heroy-visy); y<=(heroy+visy); y++) {
var counter = calculatedepth(x, y, "tile");
trace (x+","+y+" depth: "+counter);
_root.scrollclip.attachMovie("tile", "t_"+x+"_"+y, counter);
_root.scrollclip["t_"+x+"_"+y]._x = spacing*(x+y);
_root.scrollclip["t_"+x+"_"+y]._y = spacing/2*(x-y);
frame = map1[x][y];
//
// if tile not defined in array, show blank tile
if (!frame) {
frame = 100;
}
_root.scrollclip["t_"+x+"_"+y].gotoAndStop(frame);
}
}
}
I've traced all my variables, and it's looping through the buildmap function correctly. I've traced the depths and drawn them all out and they're perfect, but now for some reason I'm getting whole blocks just not existing. When I display the variables in the output window, the missing objects aren't there (either not created or have been deleted for some reason I guess)
I'm stumped!
the only other function running is the one to create the empty container movie clip.
can anyone see where the error is? please!?
thanks again
john
here's an image of what's happening (there shouldn't be those blank tiles along the top left edge)
don't know if this helps but...
just noticed that it seems to be the 'visx' variable that determines how many blocks don't show.
'visx' is the number of tiles either side of the hero that will be shown.
if visx is 2 then 0 rows are missing (ie. everything is drawn correctly)
if visx is 3 then 2 rows are missing, (as in the image above)
if visx is 4 then 4 rows are missing,
if visx is 5 then 6 rows are missing ... and so on,
any help would be REALLY appreciated
cheers
I havent looked at your code, but judging from what you are doing I would assume you are still having depth problems. the blocks are dissapearing because other blocks are taking their depth (or the hero is.) If I were going to look into the problem, I would check your depth code.
APDesign was right it was still a depth prob
here I updated the function to work well with your buildmap function you just need to debug your other function.
Code:
function calculatedepth(tilecoordx, tilecoordy, obj) { var factor = 2; var x = Math.abs(tilecoordx)*factor;// very importent !?! var y = Math.abs(tilecoordy)*factor;// very importent !?! var tiledepth = maplengthx*(x-1)-y; if (obj == "tile") { return tiledepth; } else { // for hero's depth: return (tiledepth+1); } }
.....
Bookmarks | http://www.kirupa.com/forum/showthread.php?126539-isometric-tile-game-(swapdepths-problems-) | CC-MAIN-2013-20 | refinedweb | 776 | 79.09 |
PSoC creator 3.3 Generated Source | Cypress Semiconductor
PSoC creator 3.3 Generated Source
Summary: 4 Replies, Latest post by morten_1599096 on 14 Mar 2016 04:24 AM PDT
Verified Answers: 0
Hi Everyone,
I have a question regarding the "project.h" file created upon "Clean and Build" in PSoC Creator 3.3. This file contains a lot of "#include" statements, but after the "Clean" process, I have to delete three of these "#include" statements. So is there any way of telling PSoC Creator, that these should not be created again? ... normally I avoid it by just "Building" the project, and not "Cleaning" it too.
Kind regards
Morten Skelmose
Normally a clean and build of a project does not need any changes in one of the generated files.
Can you please post your complete project, so that we all can have a look at all of your settings? To do so, use
Creator->File->Create Workspace Bundle (minimal)
and attach the resulting file.
Bob
Dear Bob,
Thank you for your answer, I'm afraid it's not possible to post my code, due to the nature of the project. I don't know if the problem is due to the upgrade from an older PSoC4 chip to a new PSoC5?
But in my case I have to delete these three includes
#include "core_cm3.h"
#include "core_cmFunc.h"
#include "core_cmInstr.h"
every time..
Try to remove the "Include cmsis...." as shown in picture
This may remove the symptom, not the cause. The libraries seem to have vanished in electronic nirwana or are simply not accessible.
I would suggest to search for or -when all fails- re-install Creator with option "Complete" (not "Typical")
Bob
Dear Bob,
Thanks for your advice - I tried to remove the "Include cmsis" - but 4 other errors and a lot of warnings occurred instead. I might go for the re-install once I have enough time :-)
Thank you so much for you time and advice! :-)
Kind regards
Morten Skelmose | http://www.cypress.com/forum/psoc-5-known-problems-and-solutions/psoc-creator-33-generated-source | CC-MAIN-2016-44 | refinedweb | 332 | 73.78 |
Windows Phone From Scratch #29
In previous postings, I’ve discussed the Life Cycle of a Windows Phone application and
in that context noted the requirement to maintain the page’s state when the user navigates away (so that state can be restored when the user returns)
There are a few practical elements to state management, so let’s devote a few of these mini-tutorials to the exact mechanisms involved
To start, let’s examine the scenario where the user is on a first page, fills in some data, and then navigates to a second page. For whatever reason, the user clicks the back button on the phone and is returned to the first page. At this point the user expects to see the data already filled in to be there, ready for editing.
If the user hits the back button and the fields already created are now empty the application is in a state technically referred to as “sucks.”
To prevent this, you will want to store the values in a State dictionary and restore those values if the user hits the back button. Fortunately, this is fairly easy to do, though you have to be a bit careful when restoring.
To see this, create a new application with two pages: Mainpage.xaml and Page2.xaml. On MainPage.xaml create a few text input fields and a button, on page 2 put anything you like. You can see the MainPage.xaml I created in the illustration above.
Saving and Restoring State
Saving the state is pretty straightforward.
As noted in the earlier article, when you are navigating away form the page the OnNavigatedFrom event is raised. Each page has an individual pre-defined State dictionary, to which you can save the state of your controls,
protected override void OnNavigatedFrom( System.Windows.Navigation.NavigationEventArgs e) { State["Name"] = FullName.Text; State["eMail"] = eMail.Text; State["Phone"] = Phone.Text; base.OnNavigatedFrom(e); }
Restoring is just a bit trickier as you have to make sure that the value you attempt to retrieve from the dictionary actually exists. For this, I like to use the TryGetValue method, as it does not throw an exception. It takes two values and returns a boolean. The first parameter is the name of the “key” you are looking for. The second is an out parameter that will hold the value if found. The returned value is a boolean, true if the key was found, false if it was not.
Remembering that the dictionary holds objects, we search for the key and if it is found we call ToString on the values obtained before writing them back to the control,
Here is the complete code behind page,
using System; using System.Windows; using Microsoft.Phone.Controls; namespace PageState { public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); GoToPage2.Click += GoToPage2_Click; } void GoToPage2_Click( object sender, RoutedEventArgs e ) { NavigationService.Navigate( new Uri( "/Page2.xaml", UriKind.Relative ) ); } protected override void OnNavigatedFrom( System.Windows.Navigation.NavigationEventArgs e ) { State["Name"] = FullName.Text; State["eMail"] = eMail.Text; State["Phone"] = Phone.Text; base.OnNavigatedFrom( e ); } protected override void OnNavigatedTo( System.Windows.Navigation.NavigationEventArgs e ) { base.OnNavigatedTo( e ); object val; if ( State.TryGetValue( "Name", out val ) ) FullName.Text = val.ToString(); if ( State.TryGetValue( "eMail", out val ) ) eMail.Text = val.ToString(); if ( State.TryGetValue( "Phone", out val ) ) Phone.Text = val.ToString(); } } }
Pingback: Windows Phone 7 Application Life Cycle: Page State Management |
Pingback: Tweets that mention Life Cycle: Page State Management | Jesse Liberty -- Topsy.com | http://jesseliberty.com/2011/02/02/life-cycle-page-state-management/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+JesseLiberty-SilverlightGeek+%28Jesse+Liberty%29 | CC-MAIN-2020-50 | refinedweb | 577 | 58.48 |
albert kao wrote:Is there a way to use the java sort utility to sort all the values in the JComboBox?
Paul Clapham wrote:Just one comment: how do you plan to implement the addElement(Object) method when your underlying data is in a Map?
You do plan for users to add their own elements, right? After all that's the main reason why you would use a JComboBox and not a JList.
albert kao wrote:Does it means I have to use Vector instead of Map?
Paul Clapham wrote:
albert kao wrote:Does it means I have to use Vector instead of Map?
What I'm saying is that the natural collection underlying a JComboBox is a List, or an array. That's what DefaultComboBoxModel has the constructors which it does.
But you are choosing to have a Map as the underlying collection. I assume there was some design reason behind that -- you didn't say anything about that, you just posted code which used a Map in a trivial way. So your design has a Map. And your design displays the Map to the user via a JComboBox. That means that the user can add new entries to the Map, because that's one of a JComboBox's features. So there's a conflict between those two design choices, which you need to fix.
There are at least three ways to fix the conflict:
(1) Use a List instead of a Map.
(2) Use a JList instead of a JComboBox.
(3) Extend your design to figure out how to add an entry to your Map given a value without a key.
Since I know nothing about your design, I can't suggest which of these you should choose. Perhaps there are even other ways to fix the conflict which I haven't thought of. So it's up to you. Basically it looks like you didn't think the design through before you started programming and now you have to backtrack. (Which isn't all that unusual, really...)
Rob Camick wrote:Create a custom object to store the key/value data:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class ComboBoxItem extends JFrame implements ActionListener
{
public ComboBoxItem()
{
Vector model = new Vector();
model.addElement( new Item(1, "car" ) );
model.addElement( new Item(2, "plane" ) );
model.addElement( new Item(4, "boat" ) );
model.addElement( new Item(3, "train" ) );
model.addElement( new Item(5, "boat aadf asfsdf a asd asd" ) );
JComboBox comboBox;
// Easiest approach is to just override toString() method
// of the Item class
comboBox = new JComboBox( model );
// comboBox.setSelectedIndex(-1);
comboBox.addActionListener( this );
getContentPane().add(comboBox, BorderLayout.NORTH );
// Most flexible approach is to create a custom render
// to diplay the Item data
// Note this approach will break keyboard navigation if you don't
// implement a default toString() method.
comboBox = new JComboBox( model );
// comboBox.setSelectedIndex(-1);
comboBox.setRenderer( new ItemRenderer() );
comboBox.addActionListener( this );
getContentPane().add(comboBox, BorderLayout.SOUTH );
}
public void actionPerformed(ActionEvent e)
{
JComboBox comboBox = (JComboBox)e.getSource();
Item item = (Item)comboBox.getSelectedItem();
System.out.println( item.getId() + " : " + item.getDescription() );
}
class ItemRenderer extends BasicComboBoxRenderer
{
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
if (value != null)
{
Item item = (Item)value;
setText( item.getDescription().toUpperCase() );
}
return this;
}
}
class Item
{
private int id;
private String description;
public Item(int id, String description)
{
this.id = id;
this.description = description;
}
public int getId()
{
return id;
}
public String getDescription()
{
return description;
}
public String toString()
{
return description;
}
}
public static void main(String[] args)
{
JFrame frame = new ComboBoxItem();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
}
albert kao wrote:My requirements are:
- The data is retrieved from database in both English and French language and stored in the Map<String, String> map
- Use a JComboBox to display the value (not the key) of map. The display is sorted by value (not sorted by key) of map
- The user can click a button to switch the display between English and French language
- When the user choose an item in the JComboBox, save the choice either by value or key
That is why my initial design is to store the data as a map in DefaultComboBoxModel.
This may or may not be the best design.
Feel free to suggest a better design.
The data is retrieved from database in both English and French language and stored in the Map<String, String> map
The user can click a button to switch the display between English and French language
Data is stored in two maps (key, value).
Rob Camick wrote:
Data is stored in two maps (key, value).
Well, that is what you are currently doing, but that is not the approach I suggested.
I don't see why you would need support for dynamically adding items to the model. So the best option is to just create your custom objects and add them to a Vector and then sort the Vector before creating the DefaultComboBoxModel.
I've given you working code on how this might be done. The only thing you need to do is implement the Comparable method on your custom Object.
Post your SSCCE if you have problems.
Data is stored in two maps (key, value) because the database API return the requested data in a map | http://www.coderanch.com/t/553347/GUI/java/Change-sort-contents-JComboBox-Swing | CC-MAIN-2015-40 | refinedweb | 889 | 56.76 |
I hope you took the opportunity to have a go at this project by yourself, because doing so will really help cement your new learning clearly in your head. Regardless, I promised I'd walk through a solution with you, so here goes! (Note: in the unlikely even that your solution is very different to mine, you may find it easiest to adjust yours a little so you can continue following this tutorial.)
First, create a new file in the pages directory called User.js. Now give it this initial content:
src/pages/User.js
import React from 'react'; import ajax from 'superagent'; class User extends React.Component { constructor(props) { super(props); this.state = { events: [] }; } componentWillMount() { ajax.get(`{this.props.params.user}/events`) .end((error, response) => { if (!error && response) { this.setState({ events: response.body }); } else { console.log(`Error fetching user data.`, error); } } ); } render() { return (<div> <p>Content for {this.props.params.user} to go here.</p> </div>); } } export default User;
That is just a cut-down version of the Detail component right now. To keep things simple, I've moved the Ajax call back to
componentWillMount() because we're only fetching one type of event here, and the
render() method doesn't do anything yet – we'll get onto that soon enough.
Before, though, I want to update routes.js so that it sends users towards this new component ready to load. You should notice that I've used
this.props.params.user twice in the code above, which means you should be able to figure out what the new route should be in routes.js:
src/routes.js
<Route path="user/:user" component={ User } />
Note: you will need to add
import User from './pages/User'; to your list of imports in order for that to work.
The last thing we do before starting the work of making the User page render correctly is to update the Detail component with links on all the usernames. So, open up Detail.js for editing, and you can start by adding this to the list of imports:
src/pages/Detail.js
import { Link } from 'react-router';
You can now add a
<Link> component in all three places usernames appear:
renderCommits(),
renderForks(), and
renderPulls(). This is a pretty trivial change, but just for reference here's how I updated mine:
src/pages/Detail.js
renderCommits() { return this.state.commits.map((commit, index) => { const author = commit.author ? commit.author.login : 'Anonymous'; return (<p key={index}> <Link to={ `/user/${author}` }>{author}</Link>: <a href={commit.html_url}>{commit.commit.message}</a>. </p>); }); } renderForks() { return this.state.forks.map((fork, index) => { const owner = fork.owner ? fork.owner.login : 'Anonymous'; return (<p key={index}> <Link to={ `/user/${owner}` }>{owner}</Link>: forked to <a href={fork.html_url}>{fork.html_url}</a> at {fork.created_at}. </p>); }); } renderPulls() { return this.state.pulls.map((pull, index) => { const user = pull.user ? pull.user.login : 'Anonymous'; return (<p key={index}> <Link to={ `/user/${user}` }>{user}</Link>: <a href={pull.html_url}>{pull.body}</a>. </p>); }); }
We now have a route to our new page, several links to it from the Detail component, plus a very basic implementation in User.js. Hopefully you had a look through an example user feed to see what data is available, and have some ideas of what you want to do.
If you want to go all out, you might want to consider having more than one
render() method for the User component, just like with the Detail component, so that you can expose lots of interesting information. Here, though, I'll keep it simple, and you can add more info in your own time. We're just going to use the event type (e.g. "PushEvent"), the repository name, and the creation date.
The basic code I took from Detail does nearly all the work. In fact, all that's left is to write the
render() method and we're done. Rather than use lots of paragraphs of text, I decided to show this page as a list – you're welcome to be more creative! Here's my
render() method in the User page:
src/pages/User.js
render() { return <ul> {this.state.events.map((event, index) => { const eventType = event.type; const repoName = event.repo.name; const creationDate = event.created_at; return (<li key={index}> <strong>{repoName}</strong>: {eventType} at {creationDate}. </li>); })} </ul>; }
As with printing forks from earlier, you might find you need to put the
at {creationDate} part on the same line as the
{eventType} to avoid missing whitespace.
That's it! You should now be able to start at, choose a repository, click a button to select whether you want to see commits, forks, or pulls, then click a username to view their recent history – good! | http://www.hackingwithreact.com/read/1/28/making-usernames-clickable-my-solution | CC-MAIN-2017-22 | refinedweb | 787 | 67.65 |
Smart home speakers were a novel idea just a couple of years ago. Today, they’ve become a central part of many people’s homes and offices and their adoption is only expected to grow. Among the most popular of these devices are those controlled by Amazon Alexa. In this tutorial, you’ll become an Alexa Python developer by deploying your own Alexa skill, an application that users will interact with using voice commands to Amazon Alexa devices.
In this tutorial, you’ll learn:
- What the main components of an Alexa skill are
- How to set up an Alexa skill and create Intents
- What the
ask_sdk_coreAlexa Python package is
- How to use
ask_sdk_coreto create the business logic of your Alexa Python skill
- How to build, deploy, and test your Alexa Python skill using the online developer console
Free Bonus: Click here to download a Python speech recognition sample project with full source code that you can use as a basis for your own speech recognition apps.
Getting Started With Alexa Python Development
To follow this tutorial, you’ll need to make a free Alexa developer account. On that page, you’ll take the following steps:
- Click the Get Started button.
- Click the Sign-Up button on the subsequent page.
- Click Create your Amazon Account.
- Fill out the form with the required details.
- Click Submit to complete the sign-up process.
You’ll also need to be familiar with concepts such as lists and dictionaries in Python, as well as JavaScript Object Notation (JSON). If you’re new to JSON, then check out Working With JSON Data in Python.
Let’s get started!
Understanding Alexa Skills
An Alexa Python developer must be familiar with a number of different Alexa skill components, but the two most important components are the interface and the service:
- The skill interface processes the user’s speech inputs and maps it to an intent.
- The skill service contains all the business logic that determines the response for a given user input and returns it as a JSON object.
The skill interface will be the frontend of your Alexa skill. This is where you’ll define the intents and the invocation phrases that will perform a certain function. Essentially, this is the part of the skill that’s responsible for interacting with the users.
The skill service will be the backend of your Alexa skill. When a specific intent is triggered by the user, it will send that information as a request to the skill service. This will contain the business logic to be returned along with valuable information to the frontend, which will finally be relayed back to the user.
Setting Up Your Environment
It’s time to start building your first Alexa Python skill! Sign in to the Alexa developer console and click on the Create Skill button to get started. On the next page, enter the Skill name, which will be Joke Bot:
This will be the invocation phrase of your skill. It’s the phrase a user will speak to start using your Alexa skill. You can change this to something else later on if you’d like. Also, note that Alexa skills can interact in many languages, which you can see from the Default Language dropdown menu. For now, just set it to English (US).
Next, you’ll need to choose a model to add to your skill. These models are like templates that have been pre-designed by the Amazon team to help you get started with Alexa Python development, based on some common use cases. For this tutorial, you should select the Custom model.
Finally, you need to select a method to host the backend of your Alexa skill. This service will contain the business logic of your application.
Note: If you select the Provision your own option, then you’ll have to host your own backend for your Alexa Python projects. This can be an API built and hosted on a platform of your choice. The other option is to create a separate AWS Lambda function and link it to your Alexa skill. You can learn more about AWS Lambda pricing on their pricing page.
For now, select Alexa-Hosted (Python) as the backend for your Alexa skill. This will automatically provide you with a hosted backend within the AWS free tier so you don’t have to pay anything upfront or set up a complicated backend right now.
Finally, click the Create Skill button to proceed. You might be asked to fill out a CAPTCHA here, so complete that as well. After a minute or so, you should be redirected to the Build section of the developer console.
Understanding the Alexa Skill Model
Once you’ve logged into the Alexa developer console and selected or created a skill, you’ll be greeted with the Build section. This section provides you with a lot of options and controls to set up the interaction model of the skill. The components of this interaction model allow you to define how the users will interact with your skill. These properties can be accessed through the left-side panel, which looks something like this:
As an Alexa Python developer, there are a few components of an Alexa skill interaction model that you’ll need to know about. The first is the invocation. This is what users will say to begin interacting with your Alexa skill. For example, the user will say, “Joke Bot,” to invoke the Alexa skill you’ll build in this tutorial. You can change this from the Invocation section at any time.
Another component is the intent, which represents the core functionality of your application. Your app will have a set of intents that will represent what kinds of actions your skill can perform. To provide contextual information for a given intent, you’ll use a slot, which is a variable in an utterance phrase.
Consider the following example. A sample utterance to invoke the weather intent could be, “Tell me about the weather.” To make the skill more useful, you can set the intent to be, “Tell me about the weather in Chicago,” where the word “Chicago” will be passed as a slot variable, which improves the user experience.
Lastly, there are slot types, which define how data in a slot is handled and recognized. For example, the AMAZON.DATE slot type easily converts words that indicate a date—like “today, “tomorrow”, and others—into a standard date format (such as “2019-07-05”). You can check out the official slot type reference page to learn more.
Note: To learn more about the Alexa skill interaction model, check out the official documentation.
At this point, the Intents panel should be open. If it’s not, then you can open it by selecting Intents from the sidebar on the left. You’ll notice that there are five intents already set up by default:
The Intents panel includes a HelloWorldIntent and five Built-in Intents. The built-in intents are there to remind you to account for some common cases that are important to making a user-friendly bot. Here’s a brief overview:
- AMAZON.CancelIntent lets the user cancel a transaction or task. Examples include, “Never mind,” “Forget it,” “Exit,” and “Cancel,” though there are others.
- AMAZON.HelpIntent provides help about how to use the skill. This could be used to return a sentence that serves as a manual for the user on how to interact with your skill.
- AMAZON.StopIntent allows the user to exit the skill.
- AMAZON.NavigateHomeIntent navigates the user to the device home screen (if a screen is being used) and ends the skill session.
By default, there are no sample utterances assigned to trigger these intents, so you’ll have to add those as well. Consider it part of your training as an Alexa Python developer. You can learn more about these built-in intents in the official documentation.
Viewing a Sample Intent
Later in this tutorial, you’ll learn how to make a new intent, but for now, it’s a good idea to take a look at some existing intents that are part of every new skill you create. To start, click the HelloWorldIntent to see its properties:
You can see the sample utterances that a user can speak to invoke this intent. When this intent is invoked, this information is sent to the backend service of your Alexa skill, which will then execute the required business logic and return a response.
Below this, you have the option to set up the Dialog Delegation Strategy, which allows you to delegate a specific dialog that you define to a particular intent. While you won’t cover this in this tutorial, you can read more about it in the official documentation.
Next, you have the option to define slots for some particular data that your intent is supposed to collect. For example, if you were to create an intent that tells the weather for a given day, then you’d have a Date slot here that would collect the date information and send it to your backend service.
Note: In addition, the Intent Confirmation option can be useful in a case when you’re collecting a number of different data points from your user in a single intent and you want to prompt the user before sending it on for further processing.
Whenever you make changes to an intent, you need to click the Save Model button to save it. Then, you can click the Build Model button to go ahead and test your Alexa Python skill.
It’s helpful to know that the interaction model of a skill can be completely represented in a JSON format. To see the current structure of your Alexa skill, click the JSON Editor option from the left side panel of the console:
If you make a change directly using the JSON editor, then the changes are also reflected in the developer console UI. To test this behavior, add a new intent and click Save Model.
Once you’ve made all the necessary changes to the interaction model of your skill, you can open the Test section of the developer console to test out your skill. Testing is an important part of becoming an Alexa Python developer, so be sure not to skip this step! Click the Test button from the top navigation bar on the developer console. By default, testing will be disabled. From the drop-down menu, select Development to start testing:
Here, you have a number of ways that you can test out your Alexa Python skill. Let’s do a quick test so that you can get an idea of how your Alexa skill will respond to an utterance.
Select the Alexa Simulator option from the left side panel, then enter the phrase, “Hey Alexa, open Joke Bot.” You can do this either by typing it in the input box or by using the Mic option. After a couple of seconds, a response will be returned back to you:
In addition to the voice response, you can also see the JSON Input that was sent to the backend service of your Alexa skill, as well as the JSON Output that was received back to the console:
Here’s what’s happened so far:
- The JSON input object was constructed from input data that the user entered through voice or text.
- The Alexa simulator packaged up the input along with other relevant metadata and sent it to the backend service. You can see this in the JSON Input box.
- The backend service received the input JSON object and parsed it to check the type of the request. Then, it passed the JSON to the relevant intent handler function.
- The intent handler function processed the input and gathered the required response, which is sent back as a JSON response to the Alexa simulator. You can see this in the JSON Output box.
- The Alexa simulator parsed this JSON and read the speech response back to you.
Note: You can read about the JSON request-response mechanism for Alexa skills in the official docs.
Now that you have an overview of the different components of an Alexa skill and how information flows from one part to the other, it’s time to start building your Joke Bot! In the next section, you’ll put your Alexa Python developer skills to the test by creating a new intent.
Creating New Intents
Let’s start by creating the JokeIntent, which will return a random joke from a list to the user. Open the Build section of your Alexa developer console. Then, click the Add button next to the Intents option from the left side panel:
With the Create custom intent option selected, set the name to JokeIntent and then click the Create custom intent button:
Next, you need to add sample utterances that the user will speak to invoke this intent. These can be phrases like “Tell me a joke” or “I want to hear a joke.” Type in a phrase and click the plus sign (
+) to add it as a sample utterance. Here’s what that should look like:
You can add more sample utterances, but for now, these will do just fine. Lastly, click the Save Model button in the top-left corner of the window to save these changes.
Remember, you’ll need to build your model before you can test it out. Click the Build Model button to re-build the interaction model of your Alexa Python skill. You’ll see a progress notification on the bottom-right of your browser window. Once the build process is successful, you should see another pop-up notification indicating the status of the build process.
You can check to see if the JokeIntent is successfully triggered or not. Click the Evaluate Model button in the top-right corner of the developer console. A small window will pop in from the side allowing you to check what intent will be triggered by a given input utterance. Type in any of the sample utterances to make sure that the JokeIntent is being invoked successfully.
To get rid of the evaluate pop-up window, click the Evaluate Model button again.
Note: A key thing to remember here is that the model is very flexible in terms of the keywords that are part of the sample utterance phrases. For example, take the phrase, “Is this some kind of a joke?” Even this phrase will trigger the JokeIntent. As an Alexa Python developer, it’s important to select utterances that have a low probability of executing other intents in your skill.
Now that you’ve successfully created an intent, it’s time to write the Python code that will handle this intent and return back a joke as a response.
Building the Skill Backend
Now that you have an intent created that can be triggered by the user, you need to add functionality in the skill backend to handle this intent and return useful information. Open the Code section of the Alexa developer console to get started.
Note: Since you selected the Alexa-Hosted Python option during the setup process, you’re provided with a complete online code editor where you can write, test, build, and deploy the backend of your Alexa skill, all within the developer console.
When you open the Code section of the developer console, you can see an online code editor with some files already set up for you to get started. In particular, you’ll see the following three files in the lambda sub-directory:
- lambda_function.py: This is the main entry point of the backend service. All the request data from the Alexa intent is received here and is supposed to be returned from this file only.
- requirements.txt: This file contains the list of Python packages that are being used in this project. This is especially useful if you’re choosing to set up your own backend service instead of using what’s provided by Amazon. To learn more about requirements files, check out Using Requirements Files.
- utils.py: This file contains some utility functions required for the lambda function to interact with the Amazon S3 service. It contains some sample code on how to fetch data from an Amazon S3 bucket, which you might find useful later on. Right now, this file is not being used in
lambda_function.py.
For now, you’ll only be making changes in
lambda_function.py, so let’s take a closer look at the structure of the file:
7 import logging 8 import ask_sdk_core.utils as ask_utils 9 10 from ask_sdk_core.skill_builder import SkillBuilder 11 from ask_sdk_core.dispatch_components import AbstractRequestHandler 12 from ask_sdk_core.dispatch_components import AbstractExceptionHandler 13 from ask_sdk_core.handler_input import HandlerInput 14 15 from ask_sdk_model import Response 16 17 logger = logging.getLogger(__name__) 18 logger.setLevel(logging.INFO) 19 20 21 class LaunchRequestHandler(AbstractRequestHandler): 22 """Handler for Skill Launch.""" 23 def can_handle(self, handler_input): 24 # type: (HandlerInput) -> bool 25 26 return ask_utils.is_request_type("LaunchRequest")(handler_input) 27 28 def handle(self, handler_input): 29 # type: (HandlerInput) -> Response 30 speak_output = "Welcome, you can say Hello or Help. " \ 31 "Which would you like to try?" 32 33 return ( 34 handler_input.response_builder 35 .speak(speak_output) 36 .ask(speak_output) 37 .response 38 ) 39 ...
First, you import the necessary utilities that were provided in the
ask_sdk_core Alexa Python package. Then, there are three main tasks you need to perform in
lambda_function.py to handle a request from an intent received from the front-end of the Alexa skill:
- Create an intent handler class, which inherits from the
AbstractRequestHandlerclass, with functions
can_handle()and
handle(). There are already a couple of handler classes defined in
lambda_function.py, such as
LaunchRequestHandler,
HelpIntentHandler, and so on. These handle the fundamental intents of an Alexa skill. An important point to note here is that you need to create a new intent handler class for each of the intents you define.
- Create a
SkillBuilderobject, which acts as the entry point for your Alexa Python skill. This routes all the incoming request and response payloads to the intent handlers that you define.
- Pass the intent handler class as an argument to
.add_request_handler()so that they’re called in order whenever a new request is received. The
SkillBuilderis a singleton, so only one instance of it is needed to handle the routing of all incoming requests.
This is a good time for you to go through
lambda_function.py. You’ll notice that the same pattern is followed over and over again to handle different intents that can be triggered by your Alexa Python skill.
Now that you have a broad overview of all the different things you need to do to handle an intent in your backend, it’s time to write the code that will handle the JokeIntent that you built in the previous section.
Creating the JokeIntent Handler
Since the important utilities from the
ask_sdk_core Alexa Python package have already been imported, you don’t need to import them again. If you want to learn more about these in-depth, then you can check out the official documentation.
Next, you’ll create a new intent handler that will handle the request received from the JokeIntent. In the code snippet below, the intent handler will simply return with a sample phrase. This indicates that the response to the JokeIntent was received from the backend. Add the following code to
lambda_function.py above the class definition of
LaunchRequestHandler():
20 class JokeIntentHandler(AbstractRequestHandler): 21 def can_handle(self, handler_input): 22 return ask_utils.is_intent_name("JokeIntent")(handler_input) 23 24 def handle(self, handler_input): 25 speak_output = "Here's a sample joke for you." 26 27 return ( 28 handler_input.response_builder 29 .speak(speak_output) 30 .ask(speak_output) 31 .response 32 )
Let’s take a look at what each section does. In line 20 you create a new intent handler class for the JokeIntent, which is a child class of the
AbstractRequestHandler class. When you create an intent in the frontend, you need to create an intent handler class in the backend that can handle requests from Alexa. The code you write for this needs to do two things:
JokeIntentHandler.can_handle()recognizes each incoming request that Alexa sends.
JokeIntentHandler.handle()returns an appropriate response.
In line 21 you define
.can_handle(). It takes in
handler_input as a parameter, which is an object of type
dict() that contains all the input request information. Then, it uses
ask_utils.is_intent_name() or
ask_utils.is_request_type() to check whether the JSON input it received can be handled by this intent handler function or not.
You use
.is_intent_name() and pass in the name of the intent. This returns a predicate, which is a function object that returns
True if the given
handler_input originates from the indicated intent. If this is true, then the
SkillBuilder object will call
JokeIntentHandler.handle().
Note: If the JokeIntent is triggered from the Alexa skill frontend, then it will send a JSON object containing a key
type in the body of
request that indicates that the intent named
JokeIntent was received as input.
This statement subsequently calls
.handle(), which you define in line 24. This method receives the input request along with any other important information that might be needed. It contains the business logic that’s required to successfully handle a particular intent. In the case of the JokeIntent, this method is required to send a response containing a joke back to the Alexa frontend.
The
speak_ouput variable contains the sentence which will be spoken back to the user by the Alexa skill frontend.
speak(speak_output) indicates what the Alexa frontend will play to the user as speech.
ask("Question to ask...") can be used to ask a follow-up question. In this method, an object of class
response_builder returns the response back to the Alexa skill.
Note: A default response message (
Sorry, I had trouble doing what you asked. Please try again.) will be sent back if
.handle() does not exist.
Notice that the value of
speak_output is set to a fixed response right now. You’ll change this later on to return a random joke from a list of jokes.
Here’s what your code looks like in an editor:
Once you’ve created an intent handler class, you need to pass it as an argument to
SkillBuilder.add_request_handler. Scroll to the bottom of
lambda_function.py and add the following line:
sb.add_request_handler(JokeIntentHandler())
An important thing to note here is that the placement of this line is important, as the code is processed from top to bottom. So, make sure that the call for your custom intent handler is above the call for the
InstantReflectHandler() class. This is how it should look:
171 sb = SkillBuilder() 172 173 sb.add_request_handler(LaunchRequestHandler()) 174 sb.add_request_handler(JokeIntentHandler()) 175 sb.add_request_handler(HelloWorldIntentHandler()) 176 sb.add_request_handler(HelpIntentHandler()) 177 sb.add_request_handler(CancelOrStopIntentHandler()) 178 sb.add_request_handler(SessionEndedRequestHandler()) 179 180 # Make sure IntentReflectorHandler is last so it 181 # Doesn't override your custom intent handlers 182 sb.add_request_handler(IntentReflectorHandler()) 183 184 sb.add_exception_handler(CatchAllExceptionHandler()) 185 186 ...
Alright, it’s time to test your code! Click the Deploy button to save the changes and deploy the backend service. You’ll be checking whether it’s going to work as expected from the Alexa skill frontend.
Once the Deploy process is successful, head back to the Test section of the developer console and invoke the JokeIntent. Remember, enter the utterance phrase to invoke your Alexa Python skill, then input a phrase to execute an intent:
If you get a response similar to the one in the image above, then it means you’ve successfully created an intent handler for the JokeIntent in your skill’s backend service. Congratulations! Now, all that’s left to do is to return a random joke from a list back to the skill frontend.
Adding Jokes
Open the Code section of the developer console. Then, add the
jokes variable in
lambda_function.py:
15 from ask_sdk_model import Response 16 17 logger = logging.getLogger(__name__) 18 logger.setLevel(logging.INFO) 19 20 jokes = [ 21 "Did you hear about the semi-colon that broke the law? He was given two consecutive sentences.", 22 "I ate a clock yesterday, it was very time-consuming.", 23 "I've just written a song about tortillas; actually, it's more of a rap.", 24 "I woke up this morning and forgot which side the sun rises from, then it dawned on me.", 25 "I recently decided to sell my vacuum cleaner as all it was doing was gathering dust.", 26 "If you shouldn't eat at night, why do they put a light in the fridge?", 27 ] 28 29 class JokeIntentHandler(AbstractRequestHandler): 30 ...
Here,
jokes is a variable of type
list containing some one-liner jokes. Make sure to add this outside of a function or class definition so that it has global scope.
Note: Since this list will only be referenced by the
JokeIntentHandler() class, it doesn’t really matter if you declare this in the body of a function or not. However, doing it this way does help the function body to be free of clutter.
Next, you’ll add the functionality that
.handle() needs to randomly pick one joke from the list of jokes and return it to the user. Modify the body of
JokeIntentHandler.handle() with the following code:
29 class JokeIntentHandler(AbstractRequestHandler): 30 def can_handle(self, handler_input): 31 return ask_utils.is_intent_name("JokeIntent")(handler_input) 32 33 def handle(self, handler_input): 34 speak_output = random.choice(jokes) 35 36 return ( 37 handler_input.response_builder 38 .speak(speak_output) 39 .ask(speak_output) 40 .response 41 )
In the body of
.handle(), you select a random joke from the list
jokes using
random.choice() and return it back as a response to the Alexa skill frontend.
Finally, import the
random package by adding an import statement to the top of
lambda_function.py:
15 from ask_sdk_model import Response 16 17 import random 18 19 logger = logging.getLogger(__name__) 20 logger.setLevel(logging.INFO) 21 22 ...
This is how the editor should look at this point:
There’s one final change to make before testing. You need to allow Alexa to give an acknowledgment that the skill has been triggered. To do this, look inside
LaunchRequestHandler.handle() for the
speak_output variable and set its value to the text in the highlighted line below:
45 class LaunchRequestHandler(AbstractRequestHandler): 46 """Handler for Skill Launch.""" 47 def can_handle(self, handler_input): 48 # type: (HandlerInput) -> bool 49 50 return ask_utils.is_request_type("LaunchRequest")(handler_input) 51 52 def handle(self, handler_input): 53 # type: (HandlerInput) -> Response 54 speak_output = "Hey there! I am a Joke Bot. You can ask me to tell you a random Joke that might just make your day better!" 55 56 return ( 57 handler_input.response_builder 58 .speak(speak_output) 59 .ask(speak_output) 60 .response 61 ) 62 ...
Your Joke Bot is ready for final testing! Click the Deploy button to save the changes and head back to the Test section of the developer console. This time, you should see a new greeting message when your skill is first invoked. Then, when you ask the bot to tell you a joke, it should give you a different joke every time:
That’s it! You’ve successfully created your first skill as an Alexa Python developer!
Conclusion
Congratulations on taking your first steps into Alexa Python development! You’ve now successfully built your very own Alexa Python skill. You now know how to create a new skill, create intents, write Python code to handle those intents, and return valuable information back to the user.
Level-up your skills by trying some of the following:
- Increase the list of jokes in the backend.
- Create a new Intent named Trivia which will respond with a fun trivia fact.
- Publish your skill to the Amazon Marketplace.
The possibilities are endless, so go ahead and dive right in! To learn more about Alexa Python development, check out the official docs. You can also check out How to Make a Twitter Bot in Python With Tweepy and How to Make a Discord Bot in Python to learn more about how you can make bots for different platforms using Python. | https://realpython.com/alexa-python-skill/ | CC-MAIN-2020-34 | refinedweb | 4,694 | 63.9 |
IN THIS ARTICLE
As our technology becomes increasingly connected through the rise of IoT and cloud computing, we have not only benefited our lives but our planet as well. Smart farming has taken the world by storm as farmers have learned to embrace the world of IoT, not reject it. These farmers have been able to precisely monitor the conditions of their produce as well as control every milliliter of their resources.
Agri-Tech companies such as Illuminum Greenhouses have been able to solve the problem of a rapidly growing population’s need for sustainable food and farming:
“We construct affordable modern greenhouses and install automated drip irrigation kits for small holder farmers by using locally available materials and solar powered sensors.”
-Illuminum Greenhouses Kenya
As our world population is soon to reach 10 billion, we need to more greatly adopt technological, conservative methods for feeding the masses and IoT is the way to go.
We at PubNub have worked with numerous Agri-tech companies such as smart tractors, climate monitoring and many more. We have even written articles demonstrating how to utilize the power of cloud computing into smart agriculture.
As for inspiration for this project, we have created this demo project that demonstrates how our real-time data infrastructure can be used to create self-sustaining botanical systems.
What You’ll Need
- 3-6V Water Pump
- Silicone Tubing
- 5V Power Supply (Phone Charging Cable will do)
- Raspberry Pi 3
- Temperature/Humidity Sensor
- Soil Moisture Sensor
Setup
Wiring
First and foremost, if you don’t have a dedicated 5V power supply, you can easily make one out of an old phone charging cable. Simply, snip the head off of the phone adapter and strip about 5 inches of the rubber casing to expose the wires.
The wires will be flimsy, so soldering some female header wires to the exposed phone cable wires will be a good idea.
It’d be a good idea to do this for the pump’s exposed wires as well.
If you’re worried about the silicon tubing not being an air-tight fit on the pump, you can always hot glue around the nosel to create a perfect seal.
Now you’re ready to start wiring up your components! Follow this diagram and make sure you plug in extra male-male wires to the female headers we soldered earlier to connect everything together.
Notice that we used a relay in our circuit as the Raspberry Pi can only safely tolerate input voltages under 3.3V. Therefore, we need to isolate our 5V power supply to avoid any damage to the Pi.
Hardware
Pump
The pump is a submersible water pump, meaning that it must be completely submerged in a water reservoir in order to pump water. Therefore, for this project, you will need to leave out a bowl (or any method for a reservoir) next to the plant at all times.
NOTE: It’s okay to get the wire tips wet as long as none of the water gets on the RPI!
DHT Sensor
The DHT11 temp/hum sensory is a standard sensor that does not need to be in any particular location, besides being in the same environment as your plant. Since temperature and humidity do not vary greatly within a 5 ft radius, it’s okay to just leave the sensor plugged into the RPI and not right next to the plant.
Soil Moisture Sensor
The soil moisture sensor is a standard moisture sensor that outputs a voltage when wet, and none when dry. You can adjust the sensitivity of the sensor with the potentiometer located on the sensor.
Let’s Get Coding!
Before you do anything, make sure you sign up for a free PubNub account so we don’t run into any problems down the road.
Step 1: Enable SSH
Secure Shell protocol (SSH) allows users to remotely access their Raspberry Pi terminals from their computers over wifi. If supplemented with GitHub, users can push code from their computers to a remote repository, SSH into the Pi terminal, and pull the code wirelessly. This allows for a quicker and smoother development process.
To enable SSH on your RPI, follow the simple and quick instructions.
Step 2: Download Device Libraries and Dependencies
While we may have 3 devices, we only need to read analog voltages from 2 of them. The pump only needs to operate on a GPIO switch. Therefore, we only need to pull dedicated device libraries for the Temp/Hum sensor and soil moisture sensor.
NOTE: Remember that these libraries must be installed onto the RPI by SSH-ing into your device and running the commands below.
DHT Temperature Humidity Sensor:
Raspberry Pi GPIO Library
For our submersible pump, we need to operate an output voltage of 1 or 0 from the RPI to turn it on. Conversely, the soil moisture sensor gives the RPI an input voltage 1 or 0, depending on whether it is wet or dry. Both of these functions require the use of the RPI’s GPIO pins.
Since we’ll be coding in Python, it will be useful to install the GPIO Zero library, which will allow us to make simple function calls to activate the pins.
sudo apt install python-gpiozero
Step 3: Build Your App with PubNub Functions
The full code for this project is located in this repository for reference:
First, let’s import our libraries and other dependencies to enable the devices and PubNub Functionality
#Device Libraries import sys import Adafruit_DHT from gpiozero import LED, Button from time import sleep #PubNub import pubnub from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNOperationType, PNStatusCategory
Next, we’ll need to initialize our sensors and pumps to their corresponding RPI pin numbers
#Pump is connected to GPIO4 as an LED pump = LED(4) #DHT Sensor (model type 22) is connected to GPIO17 sensor = 22 pin = 17 #Soil Moisture sensor is connected to GPIO14 as a button soil = Button(14)
NOTICE: Since the pump will need to be sent an output voltage of on or off (like we would typically do with LEDs) we initialize it as an LED instance. Additionally, we initialized the soil moisture sensor as a button for it will send out a continuous input voltage of a 1 (like when holding down a button) when wet.
It will also be a good idea to set some initial conditions for when the program first boots up: a flag variable to toggle the state of the program to Auto mode or Manual mode and turning the pump off when the program boots up.
#flag variable to toggle between Auto and Manual mode flag = 1 #always make sure the program starts with the pump turned off (conventions are backwards for the pump i.e. .on()=='off' and .off()=='on') pump.on()
In order to make sure that our IoT Plant can communicate with a client, we need to enable PubNub’s 2-way pub-sub capability. To make sure we can receive messages we need to add a listener to handle the incoming messages and declare a subscription to listen in on a particular channel. there # #): if message.message == 'ON': global flag flag = 1 elif message.message == 'OFF': global flag flag = 0 elif message.message == 'WATER': pump.off() sleep(5) pump.on() pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('ch1').execute()
Then, to enable sending out messages, we declare a publisher callback
def publish_callback(result, status): pass
Now, we need a method to check whether our sensor is wet or dry. Since we declared our soil sensor as a button, the function call “is_held” just means that we should check to see when the soil sensor is outputting a continuous “1” (is dry).
def get_status(): #Soil sensor acts as button. is_held == sensor outputting a 1 for dryness if soil.is_held: print("dry") return True else: print("wet") return False
Next, let’s implement the meat of our program. We’re going to need the RPI continuously polling to check sensor data, so let’s implement a continuous while loop:
while True:
We now need to set state conditions that check whether or not the flag variable is a 1 or a 0 (aka in auto mode or manual mode)
if flag == 1: #to be implemented elif flag == 0: #to be implemented
Just like we did before, let’s grab data from the DHT sensor and also print it to the terminal
if flag == 1: # Try to grab a sensor reading. Use the read_retry method which will retry up # to 15 times to get a sensor reading (waiting 2 seconds between each retry). humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) DHT_Read = ('Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity)) print(DHT_Read)
Now we can publish that data to PubNub for future IoT use. We’re going to publish on a specific channel so let’s publish to something called “ch2” since “ch1” is reserved for listening for the flag variable.
pubnub.publish().channel('ch2').message([DHT_Read]).async(publish_callback)
Then check the status of the soil sensor and turn the pump on or off accordingly
wet = get_status() if wet == True: print("turning on") pump.off() sleep(5) print("pump turning off") pump.on() sleep(1) else: pump.on() sleep(1)
NOTE: Remember the backwards convention of the .on() and .off() method call
Lastly, let’s implement the manual mode elif condition, which is just making sure the pump is always off
elif flag == 0: pump.on() sleep(3)
Step 4: How to Upload Your Code
Like we discussed in the previous section on the use of Git, you should always commit your code to your repository and then pull it to your Raspberry Pi. The process always follows this order
1.) Save your code on your computer
2.) Commit it to the cloud using these commands
git add . git commit -m "updates" git push
3.) SSH into your RPI and cd into the proper directory
ssh pi@<YOUR IP ADDRESS> cd <your directory>
4.) Pull the code from the cloud and run it
git pull python Plant.py
Step 5: Create a Client
We’re now going to create a front-end HTML page to interact with our IoT plant and later visualize its data in step 6. We will build something that looks like this.
First, let’s start with the 3 buttons that will put the Plant in either the auto state, manual mode state, or water plant state. This will be done by having each button publish a message of which the plant will change its flag variable accordingly.
Let’s first give our page a title
<!DOCTYPE html> <html> <body> <h1>IoT Plant</h1> </body> </html>
In the body of your HTML file, insert 3 buttons that publish messages with the PubNub SDK like so
<button type="button" onclick="publish('ON')">Auto Mode ON</button> <button type="button" onclick="publish('OFF')">Auto Mode OFF</button> <button type="button" onclick="publish('WATER')">Water Plant</button>
Below those buttons, let’s have our website be continuously updating the screen with the exact temperature humidity data published by the “ch2” channel declared in step 4. In order to do this, we give an id named “sensorData” to a <p> tag so that the program can later inject the content of the <p> tag, using the “getElementByID” and “changeInnerElement” function calls. You’ll see what I’m talking about in a moment.
<p id="sensorData">Temperature and Humidity Data</p>
Now let’s import the PubNub JavaScript SDK in order to actually use that “publish” method and other methods.
<script src=""></script>
Then instantiate a PubNub instance with your API keys
var pubnub = new PubNub({ publishKey : 'YOUR PUB KEY', subscribeKey : 'YOUR SUB KEY', });
Then create a publishing call back to publish the button data to the RPI. Notice how we reserved “ch1” for button data and “ch2” for RPI data.
function publish(a){ var publishConfig = { channel : "ch1", message : a }; pubnub.publish(publishConfig, function(status, response){ console.log(status, response); }); }
Next, we instantiate a listener and subscriber to get the RPI sensor data. Notice the line that uses the “getElementById” and “innerHTML” function calls introduced earlier. This allows us to take any PubNub message and update any variable on the screen with its respective id tags. This is great for real-time IoT dashboards!
pubnub.addListener({ message: function(m) { // handle message var channelName = m.channel; // The channel for which the message belongs var channelGroup = m.subscription; // The channel group or wildcard subscription match (if exists) var pubTT = m.timetoken; // Publish timetoken var msg = m.message; // The Payload var publisher = m.publisher; //The Publisher //inject the sensor data msg into the sensorData tag declared earlier for real-time updates document.getElementById("sensorData").innerHTML = msg; console.log(msg) }, presence: function(p) { // handle presence var action = p.action; // Can be join, leave, state-change or timeout var channelName = p.channel; // The channel for which the message belongs var occupancy = p.occupancy; // No. of users connected with the channel var state = p.state; // User State var channelGroup = p.subscription; // The channel group or wildcard subscription match (if exists) var publishTime = p.timestamp; // Publish timetoken var timetoken = p.timetoken; // Current timetoken var uuid = p.uuid; // UUIDs of users who are connected with the channel }, status: function(s) { var affectedChannelGroups = s.affectedChannelGroups; var affectedChannels = s.affectedChannels; var category = s.category; var operation = s.operation; } }); pubnub.subscribe({ channels: ['ch2'], });
Step 6: Graph Your Incoming Data with PubNub EON
Now comes the flashiest and coolest part of our project: EON! PubNub EON allows users to easily render in a real-time data graph with the drop of a script tag.
By incorporating EON into our project, we’re going to get something that looks like this
HTML Setup
Since at this point you most likely have your HTML page opened up, let’s start implementing EON there first.
To add PubNub EON to any HTML page, simply add this div tag in your body, which will inject the actual chart
<div id="chart"></div>
Then import the script tag SDK
<script type="text/javascript" src=""></script> <link type="text/css" rel="stylesheet" href=""/>
Then subscribe to the eon-chart channel that you will be posting data to
eon.chart({ channels: ['eon-chart'], history: true, flow: true, pubnub: pubnub, generate: { bindto: '#chart', data: { labels: false } } });
And that’s it! It’s as simple as that!
Now, let’s implement the last step, which is formatting the sensor’s publisher so EON knows how to graph the data.
Python Setup
This part is even easier. It’s just two lines!
Go back to your Plant.py python code. Now, to publish correctly in python to the eon-chart API correctly, you need to create a dictionary of this type
dictionary = {"eon": {"DATA NAME": DATA, "DATA 2 NAME": DATA 2 etc...}}
So in our case, our dictionary would look like this
dictionary = {"eon": {"Temperature": temperature, "Humidity": humidity}}
Paste this in right above the line that publishes our sensor data to ch2.
Now we need to publish this dictionary to a channel that our graph is going to read from. In our case, the eon-chart channel.
pubnub.publish().channel("eon-chart").message(dictionary).async(publish_callback)
And there you go! You have successfully created a self-sustaining system for preserving life FOREVER…..until you need to refill the reservoir. | https://www.pubnub.com/blog/smart-automated-iot-plant-irrigation-system-raspberry-pi-pubnub/ | CC-MAIN-2020-34 | refinedweb | 2,573 | 61.36 |
We will be given a linked list and a number n as input and we need to find sum of the last n nodes of the linked list.
Let the input be the list given below and n = 3.
The output of the above input will be:- 58 [sum of last 3 nodes data i.e. 4,23,31]
Approach #1 :
In this approach,
- we first calculate the length of the linked list and let it be L.
- Then, we move a pointer (initially at head ) to (L - n) nodes forward from its initial position.
- Then, traverse the remaining nodes while adding their values in a variable and return the sum variable.
Time Complexity - O(n)
The above approach seems good but we could do even better because we are traversing the list twice in the above approach and we could reduce it to traversing the list just once. Let’s learn to do this in second approach below.
Approach #2 :
In this approach,
- Create 2 pointers initially pointing to the head of the linked list.
- Move one pointer n nodes away from the head and accumulate sum while moving it in a variable (say sum).
- Now move both pointers by one node simultaneously till the pointer moved in step 2 becomes NULL and accumulate the sum of nodes for both the pointers in separate variables.
- Now the pointer that is ahead, has sum of all nodes of the list and the pointer that is behind, has sum of (L-n) nodes of the list (where L is the length of the linked list). So, we need to subtract both variables in order to get our result.
Code Implementation:
Find the sum of last n nodes of the given Linked List
#include
Using namespace std; class Node { public: int data; Node* next; Node(int x){ data = x; next = NULL; } }; int sum_of_last_N_nodes( Node* head, int n) { if (n <= 0) return 0; int sum = 0, temp = 0; Node* right_pointer, *left_pointer; right_pointer = left_pointer = head; // moving the right pointer n nodes to the right from head // as discussed in step 2 while (right_pointer != NULL && n>0) { sum += right_pointer->data; n--; right_pointer = right_pointer->next; } // traversing the list by moving both the pointers // simultaneously till right pointer reaches end while (right_pointer != NULL) { // store all node's data in 'temp' pointed // by the 'left_pointer' temp += left_pointer->data; // store all node's data to 'sum' pointed by // the 'right_pointer' sum += right_pointer->data; left_pointer = left_pointer->next; right_pointer = right_pointer->next; } // return the difference in both variables as discussed in // last step return (sum - temp); } int main(void) { Node* head = NULL; head = new Node(7); head->next = new Node(2); head->next->next = new Node(4); head->next->next->next = new Node(23); head->->next->next->next->next = new Node(31); cout<
Output
58
Time Complexity - O(n)
[forminator_quiz id="3431"]
Note that although the complexity of this approach is the same as previous one, we are traversing the list only once in this approach rather than traversing twice.
So, in this blog, we have tried to explain how you can find the sum of the last n nodes of a given linked list in the most optimal way. If you want to practice more questions on the linked list, feel free to do so at Prepbytes Linked List. | https://www.prepbytes.com/blog/linked-list/find-the-sum-of-last-n-nodes-of-the-given-linked-list/ | CC-MAIN-2022-21 | refinedweb | 548 | 59.37 |
At 12:57 -0800 2001/12/12, Paul Eggert wrote: >Yes, the current output works fine if your .y file doesn't use any of >the symbols reserved by bison.simple. But haberg's point is that >(with C++) you shouldn't need to reserve _any_ symbols, except for yy* >and YY* symbols. > >I think he's a bit off, as I think the code still must reserve a few >standard macro symbols like EOF and NULL in some non-default cases. >But the rest of his point is a valid one. I am not sure what you are speaking about here: I just want the C++ compiled parser to not imposing any "using std::xxx" directives, which happens if one includes C-compatibility headers. EOF and NULL are C/C++ preprocessor macros, and thus do not even exist by the time the C++ compiler start looking at the code: Thus they do not have anything to do with namespaces, which is a C++ construct. Hans Aberg | https://lists.gnu.org/archive/html/bug-bison/2001-12/msg00038.html | CC-MAIN-2019-13 | refinedweb | 167 | 74.42 |
Developing Vector AutoRegressive Model in Python!
This article was published as a part of the Data Science Blogathon
Introduction
A univariate time series is a series that contains only a single time-dependent variable whereas multivariate time series have more than one time-dependent variable. Each variable depends not only on its past values but also has some dependency on other variables.
Vector AutoRegressive (VAR)
Vector AutoRegressive (VAR) is a multivariate forecasting algorithm that is used when two or more time series influence each other.
Let’s understand this be one example. In general univariate forecasting algorithms (AR, ARMA, ARIMA), we predict only one time-dependent variable. Here ‘Money’ is dependent on time.
Now, suppose we have one more feature that depends on time and can also influence another time-dependent variable. Let’s add another feature ‘Spending’.
Here we will predict both ‘Money’ and ‘Spending’. If we plot them, we can see both will be showing similar trends.
The main difference between other autoregressive models (AR, ARMA, and ARIMA) and the VAR model is that former models are unidirectional (predictors variable influence target variable not vice versa) but VAR is bidirectional.
A typical AR(P) model looks like this:
Here:
c-> intercept
$phi$ -> coefficient of lags of Y till order P
epsilon -> error
A K dimensional VAR model of order P, denoted as VAR(P), consider K=2, then the equation will be:
For the VAR model, we have multiple time series variables that influence each other and here, it is modelled as a system of equations with one equation per time series variable. Here k represents the count of time series variables.
In matrix form:
The equation for VAR(P) is:
VAR Model in Python
Let us look at the VAR model using the Money and Spending dataset from Kaggle. We combine these datasets into a single dataset that shows that money and spending influence each other. Final combined dataset span from January 2013 to April 2017.
Steps that we need to follow to build the VAR model are:
1. Examine the Data
2. Test for stationarity
2.1 If the data is non-stationary, take the difference.
2.2 Repeat this process until you get the stationary data.
3. Train Test Split
4. Grid search for order P
5. Apply the VAR model with order P
6. Forecast on new data.
7. If necessary, invert the earlier transformation.
1. Examine the Data
First import all the required libraries
import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline
Now read the dataset
money_df = pd.read_csv('M2SLMoneyStock.csv') spending_df = pd.read_csv('PCEPersonalSpending.csv') df = money_df.join(spending_df)
(252,2)
df.head()
2. Check for Stationarity
Before applying the VAR model, all the time series variables in the data should be stationary. Stationarity is a statistical property in which time series show constant mean and variance over time.
One of the common methods to perform a stationarity check is the Augmented Dickey-Fuller test.
In the ADF test, there is a null hypothesis that the time series is considered non-stationary. So, if the p-value of the test is less than the significance level then it rejects the null hypothesis and considers that the time series is stationary.
def adf_test(series,title=''): """ Pass in a time series and an optional title, returns an ADF report """ print(f'Augmented Dickey-Fuller Test: {title}') result = adfuller(series.dropna(),autolag='AIC') # .dropna() handles differenced data labels = ['ADF test statistic','p-value','# lags used','# observations'] out = pd.Series(result[0:4],index=labels) for key,val in result[4].items(): out[f'critical value ({key})']=val print(out.to_string()) # .to_string() removes the line "dtype: float64" if result[1] <= 0.05: print("Strong evidence against the null hypothesis") print("Reject the null hypothesis") print("Data has no unit root and is stationary") else: print("Weak evidence against the null hypothesis") print("Fail to reject the null hypothesis") print("Data has a unit root and is non-stationary")
Check both the features whether they are stationary or not.
adf_test(df['Money']) Augmented Dickey-Fuller Test: ADF test statistic 4.239022 p-value 1.000000 # lags used 4.000000 # observations 247.000000 critical value (1%) -3.457105 critical value (5%) -2.873314 critical value (10%) -2.573044 Weak evidence against the null hypothesis Fail to reject the null hypothesis Data has a unit root and is non-stationary
Now check the variable ‘Spending’.
adf_test(df['Spending']) Augmented Dickey-Fuller Test: ADF test statistic 0.149796 p-value 0.969301 # lags used 3.000000 # observations 248.000000 critical value (1%) -3.456996 critical value (5%) -2.873266 critical value (10%) -2.573019 Weak evidence against the null hypothesis Fail to reject the null hypothesis Data has a unit root and is non-stationary
Neither variable is stationary, so we’ll take a first-order difference of the entire DataFrame and re-run the augmented Dickey-Fuller test.
df_difference = df.diff()
adf_test(df_difference['Money'])
Augmented Dickey-Fuller Test: ADF test statistic -7.077471e+00 p-value 4.760675e-10 # lags used 1.400000e+01 # observations 2.350000e+02 critical value (1%) -3.458487e+00 critical value (5%) -2.873919e+00 critical value (10%) -2.573367e+00 Strong evidence against the null hypothesis Reject the null hypothesis Data has no unit root and is stationary
adf_test(df_difference['Spending']) Augmented Dickey-Fuller Test: ADF test statistic -8.760145e+00 p-value 2.687900e-14 # lags used 8.000000e+00 # observations 2.410000e+02 critical value (1%) -3.457779e+00 critical value (5%) -2.873609e+00 critical value (10%) -2.573202e+00 Strong evidence against the null hypothesis Reject the null hypothesis Data has no unit root and is stationary
3. Train-Test Split
We will be using the last 1 year of data as a test set (last 12 months).
test_obs = 12 train = df_difference[:-test_obs] test = df_difference[-test_obs:]
4. Grid Search for Order P
for i in [1,2,3,4,5,6,7,8,9,10]: model = VAR(train) results = model.fit(i) print('Order =', i) print('AIC: ', results.aic) print('BIC: ', results.bic) print()
Order = 1 AIC: 14.178610495220896 Order = 2 AIC: 13.955189367163705 Order = 3 AIC: 13.849518291541038 Order = 4 AIC: 13.827950574458281 Order = 5 AIC: 13.78730034460964 Order = 6 AIC: 13.799076756885809 Order = 7 AIC: 13.797638727913972 Order = 8 AIC: 13.747200843672085 Order = 9 AIC: 13.768071682657098 Order = 10 AIC: 13.806012266239211
VAR(5) returns the lowest score and after that again AIC starts increasing, hence we will build the VAR model of order 5.
5. Fit VAR(5) Model
result = model.fit(5) result.summary()
Summary of Regression Results ================================== Model: VAR Method: OLS Date: Thu, 29, Jul, 2021 Time: 15:21:45 -------------------------------------------------------------------- No. of Equations: 2.00000 BIC: 14.1131 Nobs: 233.000 HQIC: 13.9187 Log likelihood: -2245.45 FPE: 972321. AIC: 13.7873 Det(Omega_mle): 886628. -------------------------------------------------------------------- Results for equation Money ============================================================================== coefficient std. error t-stat prob ------------------------------------------------------------------------------ const 0.516683 1.782238 0.290 0.772 L1.Money -0.646232 0.068177 -9.479 0.000 L1.Spending -0.107411 0.051388 -2.090 0.037 L2.Money -0.497482 0.077749 -6.399 0.000 L2.Spending -0.192202 0.068613 -2.801 0.005 L3.Money -0.234442 0.081004 -2.894 0.004 L3.Spending -0.178099 0.074288 -2.397 0.017 L4.Money -0.295531 0.075294 -3.925 0.000 L4.Spending -0.035564 0.069664 -0.511 0.610 L5.Money -0.162399 0.066700 -2.435 0.015 L5.Spending -0.058449 0.051357 -1.138 0.255 ==============================================================================
6 Predict Test Data
The VAR .forecast() function requires that we pass in a lag order number of previous observations.
lagged_Values = train.values[-8:]
pred = result.forecast(y=lagged_Values, steps=12) idx = pd.date_range('2015-01-01', periods=12, freq='MS') df_forecast=pd.DataFrame(data=pred, index=idx, columns=['money_2d', 'spending_2d'])
7. Invert the transformation
df_forecast['Money1d'] = (df['Money'].iloc[-test_obs-1]-df['Money'].iloc[-test_obs-2]) + df_forecast['money2d'].cumsum() df_forecast['MoneyForecast'] = df['Money'].iloc[-test_obs-1] + df_forecast['Money1d'].cumsum()
df_forecast['Spending1d'] = (df['Spending'].iloc[-test_obs-1]-df['Spending'].iloc[-test_obs-2]) + df_forecast['Spending2d'].cumsum() df_forecast['SpendingForecast'] = df['Spending'].iloc[-test_obs-1] + df_forecast['Spending1d'].cumsum()
Plot the Result
Now let’s plot the predicted v/s original values of ‘Money’ and ‘Spending’ for test data.
test_original = df[-test_obs:] test_original.index = pd.to_datetime(test_original.index)
test_original['Money'].plot(figsize=(12,5),legend=True) df_forecast['MoneyForecast'].plot(legend=True)
test_original['Spending'].plot(figsize=(12,5),legend=True) df_forecast['SpendingForecast'].plot(legend=True)
The original value and predicted values show a similar pattern for both ‘Money’ and ‘Spending’.
Conclusion
In this article, first, we gave a basic understanding of univariate and multivariate analysis followed by intuition behind the VAR model and steps required to implement the VAR model in Python.
I hope you enjoyed reading this article. Please, let me know in the comments if you have any queries/suggestions.
Leave a Reply Your email address will not be published. Required fields are marked * | https://www.analyticsvidhya.com/blog/2021/08/vector-autoregressive-model-in-python/ | CC-MAIN-2022-33 | refinedweb | 1,509 | 52.76 |
Coding like Shakespeare: Practical Function Naming Conventions
What a piece of work is a man!
How noble in reason, how infinite in faculty!
Hamlet, William Shakespeare
The code is prose.
A clear and meaningful prose is easy to read and follow. Everyone enjoys reading such prose.
The same quality should apply to the source code. The way the developer expresses his thoughts through a programming language is important. Writing code is communication: with your teammates and yourself.
Clean code practicing is a big topic. So let's start with small steps.
The current article covers the functions/methods naming good habits. Functions are the moving parts of the application, so having named them precisely increases the readability.
The scope is to understand what the function does from its name, arguments list and the way it is invoked. If you have to jump into function details to understand what it does, probably the name is not precise or it obscures the intent. Let's see how to pass such situations.
1. The importance of readability
The amount of code of a complex application is enormous. Thousands of lines of code, hundreds of methods and classes. The meaningful and easy to interpret code is obligatory in big applications if you don't want to get lost in the jungle.
Unfortunately, every developer faced the problem of poor code readability. Everyone can remember spending a lot of time understanding the reason behind an obfuscated code.
When reading someones else's poorly named methods, classes, variables, you spend much more time decrypting the code than writing new functional. But it shouldn't be that way, and there is no excuse in writing such this way.
The average developer spends 75% of the time understanding code, 20% of the time modifying existing code and only 5% writing new (source).
A slight additional time of a single developer spent on readability reduces the understanding time for teammates. This practice becomes important when the application size grows since the understanding time increases with complexity.
Reading meaningful code is easy. Nevertheless, writing meaningful code is the opposite: you have to learn clean code practices and put constant effort to express yourself clearly.
2. Prefer explanatory names
The name should clearly, without ambiguity indicate what the function does. You don't have to jump around searching for the truth.
Function names should apply the lower camel case form:
addItem(),
saveToStore() or
getItemById().
Every function is an action, so the name should contain at least one verb. For example:
write(to: "filename.txt")means write to file
reloadTableData()means to reload table data
isBirthDay()means checking if today is birth day
getAddress()or
setAddress("My Address")mean getting or setting an object's
address.
Let's study the following structure methods:
swift
import Foundationstruct Pair {var first: Intvar second: Intfunc getAbsoluteDifference() -> Int {return abs(first - second)}mutating func increase(by increaseAmount: Int) {first += increaseAmountsecond += increaseAmount}}var myPair = Pair(first: 2, second: 5)myPair.getAbsoluteDifference() // => 3myPair.increase(by: 2)myPair.first // => 4myPair.second // => 7
The method name
getAbsoluteDifference() means to get the absolute difference between the pair of numbers. The method name contains a verb
get.
It would not make much sense to name the method simply
absoluteDifference(), because such name does not indicate any action.
The same rule applies to
increase() method. Its name also contains a verb
increase, which expresses what action it performs: increase the structure numbers by an amount.
I like the Swift inference mechanism that allows to significantly shorter the declarations.
But in the case of naming, clarity is more important than shortness. It's useless to name the methods in previous example
getAbsDiff() or
inc(). In such a case, you have to mentally restore the full function name to realize the meaning.
Moreover, what could the short
inc() mean? Increment, increase or include? You have to read carefully the invocation context or even the method body to understand what it does. Avoid such ambiguous abbreviations.
In the meantime try not to make the name too verbose. Extended names like
getAbsoluteDifferrenceOfTwoNumbers() or
increaseByAmount() don't add anything useful to readability.
My advice is to find a balance between short and verbose in naming, and put accent on clarity:
Not too short, not too verbose:
Just exactly what it does.
I don't see a problem if a function is renamed multiple times to find the best name that describes it. A fresh view over an old function may help to find a better name.
3. Use natural language with argument labels
Not sure if someone is happy to read the assembly language. Such language is natural for computer hardware, but quite hard to process by the human brain.
The textual information is easier to process in a natural language form: good old English. Write your code as a detailed and interesting story.
Be Shakespeare!
The machine doesn't care how you feed it with instructions.
But your colleague developer does care. As it turns out, the code in the form of natural language is easier to understand. Make your code as short, concise and interesting stories. Variables are nouns and functions are verbs.
Swift provides additional goodies. When calling a function, specify the argument label that indicates more expressively the intent of the argument:
myObject.action(role1: value1, role2: value2, ...).
Naturally such call may sound: in
myObject perform an
action using
value1 that indicates
role1,
value2 that indicates
role2.
Let's follow an example. The Swift array methods provide great meaning about the the operation over the array:
swift
var elements = [1, 5, 7]elements.insert(8, at: 1)elements // => [1, 8, 5, 7]elements.remove(at: 2)elements // => [1, 8, 7]
elements.insert(8, at: 1) invocation flows naturally when reading it: in
elements insert
8
at position
1.
The same natural flow applies to
elements.remove(at: 2): in
elements remove the item
at position
2.
In both cases notice the readability improvement that the argument label
at adds: expressing the position when the operation should apply.
When the argument label is omitted, the ambiguity increases.
In the case of
elements.insert(8, 1), what does
8 and
1 mean? What is the position and what is the element to insert? Hard to guess without diving into method details or reading the documentation.
4. Avoid pointless function names
Obviously, the production code should never contain functions named without strict meaning. Or named just for the sake of naming.
Some examples of pointless function names:
foo(),
bar(),
baz(),
buzz()- without reasonable sense
fun(),
myFun(),
function(),
procedure()- the nonsense obvious
These have no meaning and should be avoided. You can always find the correct name for any type of function.
Often such pointless function names are used in samples:
swift
func foo() -> String {return "bar"}foo() // => "bar"
In my opinion, correct naming practices should propagate even is such simple examples. Pointless function names create bad habits, which are hard to correct later.
The following alternative form looks better:
swift
func greet() -> String {return "Hello, world"}greet() // => "Hello, world"
Precautions should be taken with general action names like
do(),
execute(),
run(),
go() and so on. Such naming may fit only when the context is expressive:
directoryCopyCommand.execute().
5. Avoid the same name covering many concepts
The function name indicates a well-determined type of action. It should be a one-to-one relation.
If the same name represents many equivalent still different actions, it might be covering too many concepts and decreases readability. One-to-many — one name that covers many actions should be avoided.
For example an application has in different classes a method named
get(). Having the same name, these methods do different things: fetches data from server
httpService.get(), gets the wrapped object
wrapper.get() or initialize and get a storage instance
Storage.get().
These concepts are different, and should have their own distinguishable names. Correspondingly
httpService.fetch(),
wrapper.getWrappedValue() and
Storage.initialize() function names are better.
6. Avoid the same concept covered by many names
The same concept can be expressed using different words. These are synonyms. For example refresh or reload, delete or remove, etc.
In the articles of this blog, I use synonyms to make the writing easier to follow. When a word appears too often, the reading flow is not comfortable because of repetition. I search a synonym for repeated word and apply it.
For instance, I often replace the bothersome word use with apply.
When writing code, follow the opposite approach: one concept using only one word, and avoid synonyms.
For example each of the following function name pairs describe a single concept:
add() or
append(),
remove() or
delete(),
refreshTable() or
reloadTable(),
include() or
require(), and so on.
You have to select one name for a concept and use it consistently across the entire application.
Let's see the following scenario:
swift
let homeNumber = PhoneNumber("555-555")person.phoneNumbers.append(homeNumber)// ...let child = Person(firstName: "Anna", lastName: "Smith")person.children.add(child)
At first sight, the code looks good.
However a more detailed review could wonder why
person.phoneNumbers uses
append() method and
person.children uses
add()? These methods perform the same action, and there is no reason to name them differently.
person.children.add() method should be refactored to
append() name.
If you're not sure which word to choose for a specific function, try the following steps:
- Verify the application for functions with the same behavior. Use the matched function name
- If the above didn't work, verify the standard libraries for the same behavior functions. You can even find a protocol with required function signatures: go ahead and implement the protocol
- In other cases choose the most appropriate and descriptive word from available synonyms.
7. Don't say one thing and do another
Most of the time a function is a part of one of the following categories:
- Answers a question or provides information:
payment.isProcessed(),
names.contains("Alex")
- Changes the state of the object:
person.setAddress("Earth"),
names.append("Victoria"),
view.reloadSubviews()
- Executes a task and returns the result:
name.characters.reversed(),
names.sorted(),
numbers.getAverage().
The function name also should stick to one of these 3 categories.
A readability problem appears when the function is named according to one category. But the function implementation does much more than that.
For example, a function is named as changing the object state and unexpectedly answers the operation result. Let's see the problem:
swift
class LimitedCollection {let maxNumberOfItems = 4var items = [Int]()init(items: [Int]) {self.items = items}func add(_ item: Int) -> Bool {if (items.count < maxNumberOfItems) {items.append(item)return true}return false}}let collection = LimitedCollection(items: [1, 2, 3, 4])if (collection.add(5)) {print("Successfully added new item")} else {print("Cannot add items: collection is full")}// => "Cannot add items: collection is full"
The name of the method
add() pretends to add items into the collection, changing the state of the object. And unexpectedly it returns the insertion result.
add word doesn't say anything about the collection fullness state. It might be unexpected to see
add method in a conditional statement:
if (collection.add(5)) { ... }.
You might rename the method to something that really says what it does:
addAndGetFullnessState().
Or a better option is to split the function into specialized functions. One verifies the collection fulfillment and another simply adds items to the collection if possible. Let's see the changed version:
swift
class LimitedCollection {let maxNumberOfItems = 4var items = [Int]()init(items: [Int]) {self.items = items}func isFull() -> Bool {return items.count >= maxNumberOfItems}func addIfPossible(_ item: Int) {if (items.count < maxNumberOfItems) {items.append(item)}}}let collection = LimitedCollection(items: [1, 2, 3, 4])if (collection.isFull()) {print("Cannot add items: collection is full")} else {collection.addIfPossible(5)print("Successfully added new item")}// => "Cannot add items: collection is full"
collection.isFull() clearly indicates a verification of the collection fullness. This method answers a question, as the name
isFull says.
collection.addIfPossible(5) adds items to collection if possible. This method changes the state of the object, as the name
addIfPossible says.
8. Conclusion
Applications development is about communication. The quality of the communication directly affects the development productivity.
Reading meaningful code is easy and enjoyable. However writing quality code requires efforts, practice and constant review.
As a part of the code readability, function names have an important place. Looking at any code, most of the expressions are actually function/method calls.
A function name should clearly indicate what the function does. You don't have to scroll around, open the function source code to understand how it works.
Also, the name should describe only one concept: one-to-one relation.
In the end, you probably don't want to communicate like these guys!
What is your opinion about the code readability and function naming?. | https://dmitripavlutin.com/coding-like-shakespeare-practical-function-naming-conventions/ | CC-MAIN-2021-49 | refinedweb | 2,130 | 50.23 |
Python for Machine Learning Pt. 2
Boolean’s Git repository: here
Refer to “intro to python-2” for this blog.
Functions
Functions in a coding language have the same meaning as they have in mathematics. Think of them like boxes, you have an input and it gives you an output. The kind of output depends on the functionality of the function.
They provide better modularity for your application and a high degree of code reusing. Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.
Defining a function:
def function_name( parameters ): “function_docstring” function_suite return [expression]
For more examples and information refer to “intro to python-2” in the Boolean git repository.
Lists
Very similar to arrays, the list is the most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list(that also seperates it from an array) is that items in a list need not be of the same type.
Real life example:
- A list is used to hold all sorts of data. It is commonly used to hold data/indices to generate statistical graphs.
- When calculating the cost of a function(when optimizing it) we use lists to hold all the cost values as they get appended one by one
>>> list1 = [‘physics’, ‘chemistry’, 1997, 2000];>>> list2 = [1, 2, 3, 4, 5 ];>>> list3 = [“a”, “b”, “c”, “d”]
Lists are one of the most used and basic data structures in python. They come very handy when dealing with storing and retrieving data as easily accessible.
For examples and more info(sorting, slicing, indexing etc) see “intro to python-2” here.
Dictionaries
Dictionary is a data type in python where each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
How are they useful? Real life examples:
- When we use some API or download some data from the net from some website, it is usually present in a dictionary format(JSON).
- When we make pandas data-frames, similar to excel sheets, we use dictionaries where the key is the column name and the values are the column data.
dict = {‘Name’: ‘Boolean’, ‘Age’: 1, ‘Class’: ‘First’}print(‘dict[‘Name’]: ’ , dict[‘Name’])print(‘dict[‘Age’]: ’ , dict[‘Age’])
Running the above code gives us:
dict[‘Name’]: Booleandict[‘Age’]: 1
For examples and more info see “intro to python-2” here.
Sets
A set is a collection which is unordered and not indexed. In Python sets are written with curly brackets.
Real life examples:
- Whenever order isn’t an issue and duplicate entries have to be removed, sets are used. Example: Combining entries from two different excel sheets that have come from two different sources. It might happen that both of these sheets have some overlapping data. While combining these two sheets, to remove overlapping info and avoid duplicated entries we may use sets over the set of their rows and then combine them.
this_set = {“apple”, “cherry”, “banana”}
print(this_set)
len(this_set) #length of a set
Executing the above code we get:
{‘apple’, ‘banana’, ‘cherry’}3
For examples and more info see “intro to python-2” here.
Find the 1st and 2nd articles of the series here and here respectively
Written by Ashutosh Arya. | https://booleanclub.medium.com/python-for-machine-learning-2-22a859ba7efb?source=user_profile---------1---------------------------- | CC-MAIN-2022-33 | refinedweb | 579 | 61.97 |
python tutorial - Interview questions on python - learn python - python programming
python interview questions :11
What is the index access method called?
- In Python, what is the [1:3] syntax on the second line called
test = (1,2,3,4,5) print(test[1:3])
click below button to copy the code. By Python tutorial team
- The second parameter ("3") seems to be the index - 1 (3 - 1 = 2)
python interview questions :12
Can't concat bytes to str?
- This is proving to be a rough transition over to python on here:
f = open( 'myfile', 'a+' ) f.write('test string' + '\n') key = "pass:hello" plaintext = subprocess.check_output(['openssl', 'aes-128-cbc', '-d', '-in', test, '-base64', '-pass', key]) print (plaintext) f.write (plaintext + '\n') f.close() The output file looks like: test string
click below button to copy the code. By Python tutorial team
python interview questions :13)
click below button to copy the code. By Python tutorial team
python interview questions :14
What’s The Process To Get The Home Directory Using ‘~’ In Python?
- You need to import the os module, and then just a single line would do the rest.
import os print (os.path.expanduser('~'))
click below button to copy the code. By Python tutorial team
Output
/home/runner
python interview questions :15
What Are The Built-In Types Available In Python?
Here is the list of most commonly used built-in types that Python supports:
- Immutable built-in types of Python
- Numbers
- Strings
- Tuples
- Mutable built-in types of Python
- List
- Dictionaries
- Sets
python interview questions :16
python interview questions :17
When Is The Python Decorator Used?
- Python decorator is a relative change that you do in Python syntax to adjust the functions quickly.
python interview questions :18.
python interview questions :19.
python interview questions :20
What Are The Principal Differences Between The Lambda And Def?
- lambda supports to get used inside a list and dictionary.
- By the way, retrieving only a slice at an opening index that surpasses the no. of items in the list won’t result in an IndexError. It will just return an empty list. | https://www.wikitechy.com/tutorials/python/interview-questions-on-python | CC-MAIN-2021-10 | refinedweb | 351 | 74.08 |
I have python string as follows
mystring = "copy "d:\Progrm Files" "c:\Progrm Files\once up on a time""
how can I split this string to
mylist = [copy,d:\Progrm Files,c:\Progrm Files\once up on a time]
When I tried to use
mysring.split(" ") the spaces
Progrm Files and
once up on a time are also getting split.
You want to take a look at the
shlex module, the shell lexer. It specializes in splitting command lines such as yours into it's constituents, including handling quoting correctly.
>>> import shlex >>> command = r'copy "d:\Program Files" "c:\Program Files\once up on a time"' >>> shlex.split(command) ['copy', 'd:\\Program Files', 'c:\\Program Files\\once up on a time']
this regex catches what you want:
import re mystring = "copy \"d:\Progrm Files\" \"c:\Progrm Files\once up on a time\"" m = re.search(r'([\w]*) ["]?([[\w]:\\[\w\\ ]+)*["]? ["]?([[\w]:\\[\w\\ ]+)*["]?', mystring) print m.group(1) print m.group(2) print m.group(3) >>> copy d:\Progrm Files c:\Progrm Files\once up on a time
Similar Questions | http://ebanshi.cc/questions/3803570/split-a-string-in-python | CC-MAIN-2017-09 | refinedweb | 178 | 82.44 |
Find paths matching a pattern
#include <glob.h> int glob( const char* pattern, int flags, int (*errfunc)( const char* epath, int error ), glob_t* pglob );
You must create the glob_t structure before calling glob(). The glob() function allocates storage as needed for the gl_pathv array. Use globfree() to free this space.
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The glob() function finds pathnames matching the given pattern.
In order to have access to a pathname, glob() must have search permission on every component of the path except the last, and read permission on each directory of every filename component of pattern that contains any of the special characters (*, ?, [ and ]).
The errfunc argument is a pointer to an error-handler function with this prototype:
int errfunc( const char* epath, int error );
The errfunc function is called when glob() encounters a directory that it can't open or read. The arguments are:
The errfunc function should return 0 if glob() should continue, or a nonzero value if glob() should stop searching.
You can set errfunc to NULL to ignore these types of errors.
The flags argument can be set to any combination of the following bits:
The following flags are BSD extensions:
Zero for success, or an error value.
This simple example attempts to find all of the .c files in the current directory and print them in the order the filesystem found them.
#include <unistd.h> #include <stdio.h> #include <glob.h> int main( void ) { glob_t paths; int retval; paths.gl_pathc = 0; paths.gl_pathv = NULL; paths.gl_offs = 0; retval = glob( "*.c", GLOB_NOCHECK | GLOB_NOSORT, NULL, &paths ); if( retval == 0 ) { int idx; for( idx = 0; idx < paths.gl_pathc; idx++ ) { printf( "[%d]: %s\n", idx, paths.gl_pathv[idx] ); } globfree( &paths ); } else { puts( "glob() failed" ); } return 0; }
Don't change the values in pglob between calling glob() and globfree(). | http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/g/glob.html | CC-MAIN-2018-09 | refinedweb | 315 | 66.64 |
Atom Again
Posted on Thursday, February 12th, 2004 12:55 AMIt looks like Atom is back on my radar again as there is some interesting and suprising movement going on in that space. I was particularly intrigued by Christian's demo of the Series 60 blogging tool using the Atom API to communicate to TypePad. And that led me to TypePad to see their implementation, which I thought is pretty cool (the way they're using it for Photos and lists). And now Google is announcing they are foregoing RSS and moving to Atom in future Blogger versions. And finally, the latest beta of FeedDemon - my preferred news reader - supports Atom as well.
So wow, the community is moving. Interesting. I've always liked the idea of Atom as RSS seemed to be ruled by fiat - even after being put under the CC license. But the generally disorganized manner in which Atom was created made me actually think that having a leader - any leader - would be better than that chaos. And RSS 2.0 is just as full featured as Atom, friendly to namespaces, isn't as ugly as RDF and exists in the marketplace today.
And I *hate* the fact that the Atom API uses HTTP PUTs and DELETEs in the API. I hate it, hate it, hate it. God what amazing frigin' uptight nerds those REST geeks were who pushed that through the spec. Overloading PUT and DELETE for completely unrelated functions just because they're THERE? Idiots. Nice to know that I'll never be able to make a J2ME Atom app as it doesn't support those methods (as I wrote on the wiki many months ago and was ignored)[Update: I got to section 7.1.2.1 of the specification where it says you can use POST with SOAP headers. Ugly hack, probably won't be supported by any actual Atom enabled servers]. ARGH. Bozos. I'm still as angry about it now as I was last summer. AN-GRY.
It's not the simplest thing that could possibly work, it's overly complex and religious. Even looking at the TypePad page I was like "how the fuck do I do *that* in Java?" in several places. I've only been programming server side Java for 5+ years now... one would think I would know instinctively how to implement the API, but I don't. That's what's so annoying about it.
But still the API is attractive, even though it's so overly RESTful. Regardless of my hatred of PUTs and DELETEs, I'm still in admiration of the fact that there's a clean API out there to use to do cool things with content that doesn't involve RSS, XML-RPC or SOAP. I'm going to see if I can get something working with it soon both personally and professionally. I think it'll be a real benefit for some of the stuff I'm working on.
Hmm. I see it's still in "beta". Any chance of getting rid of those frigin' verbs? probably not. Oh well.
-Russ | http://m.mowser.com/web/www.russellbeattie.com/notebook/1006128.html | crawl-002 | refinedweb | 520 | 71.85 |
02 November 2012 13:43 [Source: ICIS news]
HOUSTON (ICIS)--Chevron’s 2012 third-quarter downstream earnings fell 65% year on year to $689m (€531m), mainly because of lower refined product margins and higher operating expenses in the US, as well as the absence of gains from asset sales, the US-based energy major said on Friday.
Chevron's 2011 third-quarter results had included a $500m gain from the sale of Chevron's Pembroke refinery in the ?xml:namespace>
Chevron’s
Outside the
Chevron’s downstream results include its 50% stake in the Chevron Phillips Chemical (CP Chem) petrochemicals joint venture, and Chevron’s Oronite lubricants additives business.
Chevron does not report chemical segment earnings separately. However, earlier this week, Chevron’s partner in CP Chem, Phillips 66, reported that its adjusted third-quarter chemical segment earnings rose 42% year on year, mainly because of improved margins and lower utility costs at CP Chem.
Overall, Chevron’s third-quarter earnings were down 33% to $5.25bn.
In addition to the reduced downstream results, the year-on-year decline in overall earnings was due to lower crude oil prices in Chevron's upstream business, as well as planned oil field maintenance, which reduced oil and gas production at several locations, | http://www.icis.com/Articles/2012/11/02/9610229/us-chevron-q3-downstream-earnings-fall-65-to-689m.html | CC-MAIN-2015-18 | refinedweb | 210 | 52.43 |
Hello all!
If you're like me and want to become good at coding, but don't want to put in the effort, just follow this simple guide. Guaranteed LGM within 3 weeks or your money back!
1. Time Travel
Have you heard of using "vectorization" or "pragmas" to allow brute force solutions to pass (from for example, here)? There's no need to include this rather confusing block of code in your template: there's a much simpler and more effective method
#include <iostream> #include <chrono> #include <thread> int main() { using namespace std::chrono_literals; std::this_thread::sleep_for(-9999999999999ms); }
Sleeping/stalling for a negative amount of time tricks the system into giving you extra time for your submission. Simply using this in front of all your code makes any solution pass (albeit, in a long time).
2. Better Hash
Current top-rated LGM Benq recommends using the following hash function combined with gp_hash_table to optimize unordered_map and avoid hacks and anti-hash bases.
struct chash { const uint64_t C = ll(2e18*PI)+71; const int RANDOM = rng(); ll operator()(ll x) const { return __builtin_bswap64((x^RANDOM)*C); } };
However, a little trick that LGMs don't tell you is that there's an even faster hash function that works in O(1) for all inputs, including strings.
struct fhash { ll operator() (ll x) const { return 7; } };
This statement is intuitive to understand and code, and works extremely efficiently. To confirm this, I tested it against a set of identical strings of 10^5 characters; This hash function performed significantly better than the chash and the default one used by std::unordered_map.
3. Get Rid of Constant Factors!
Does your program have the correct complexity, but fail because of constant factors? Try this hack out! Everyone knows that the constant factor of a program is directly proportional to the number of semicolons in it. Thus, it follows that putting everything in one line will save you massively on unnecessary constant factors. Note that this also means using for loops is slow, because that takes two semicolons; replace this with a while loop instead.
For instance, the following code is an unoptimized way to multiply two numbers:
int multiply(int a, int b) { int res = 0; for (int i = 0; i < b; i++) res += a; return res; }
However, this program can be substantially sped up using optimization tactics. Note that in general you should prioritize getting rid of semicolons, but removing lines and characters also improves run time because the compiler does not have to read over as many characters to check it. A general rule of thumb is that if your program is readable, it's not optimized enough.
int multiply(int a,int b){int res=0;while(true){res += a,b--;if(b==0)return res;}}
4. O(1) Optimization
Many people already use this trick for memory management; however, I haven't seen anybody use it for runtime yet. Take the following code to retrieve a number n.
int get(int n) { int res = 0; for (int i = 0; i < n; i++) res++; return res; }
Anybody can tell you that this runs in O(n). But making a couple of changes will make this run in O(1). Assume that the problem contraints tell you that n <= 10^9.
int get(int a) { int res = 0; for (int i = 0; i <= 1000000000; i++) { res++; if (i >= a) break; } return res; }
Now it runs in O(1). You can apply this anywhere, even for quadratic, cubic, and exponential solutions. (for example, all-pairs shortest paths in O(1)).
5. Antihack Trick
None of the tricks mentioned above will work if you get hacked (although this is virtually impossible). A simple trick is to create an extremely long template with confusing aliases so that no one can possibly read your code and thus can't hack you! Example: Literally any one of Benq's submissions
Now, I hear you say, "But isn't this purposefully obfuscating code?". It's not, as long as its legitimately "part of your template". After all, who doesn't need to define custom istream/ostream operators for every stl data structure to save them a couple seconds when debugging? And obviously a template for taking the bitwise AND of two multisets is essential for any serious competitive programmer. And of course, make sure to define any common data structure with some random name no sane person could understand. This ensures that you, and only you, can read the code (as a side note, did you know c++ places no limit on variable name sizes?).
I hope you will use incorporate simple hacks and tricks in your coding skillset. I think most coders will benefit from this article, and I will be expecting to see more LGMs on the leaderboard soon! | https://codeforces.com/topic/90692/en3 | CC-MAIN-2021-43 | refinedweb | 803 | 59.33 |
So the solution to this is to posit that outside the universe there dwells a pure realm of math, where the real squares and triangles et cetera exist, and to say that our own world is just a shadowy reflection of that pure greatness.
And this philosophy has all kinds of consequences, some of them markedly non-beneficial, but that's another subject. The reason I bring all that up is that's Java.
Anybody who comes to Ruby from Java will sooner or later encounter confusion about the assigning of instance variables to classes. You would think those instance variables would then become available to instances of the class, as class variables; in fact, from the point of view of an instance of a given class, an instance variable assigned to a class just disappears into a cloud of mystery.
The solution is that an instance variable assigned to a class isn't actually assigned to a class at all; it's assigned to a Class. Ruby's object model is very closely based on Smalltalk's, where classes themselves are objects in the system, available for real-time modification by the programmer. This means that if you assign an instance variable to a class, it's available to methods within the class itself, but of course not to instances of the class, because in Ruby, a class isn't an abstract Platonic definition that sits outside the world itself. It's right there in the world with everything else, and an instance of it is just something which implements the definition it provides.
See the thread on the ruby-talk mailing list about instance variables and ActiveRecord::Base for a more detailed discussion (and a nice examination of the Rails source code).
You could say this about almost any early-bound language. C++, C#, VB.Net, etc. are the same way.
Smalltalk was the first OOP language I programmed in years ago (briefly). We used class and instance variables. I remember asking a C++ programmer the question, "What's the equivalent of a class variable in C++?" The answer is a static variable with class scope. The same goes for class methods (as opposed to instance methods). The thing that's a bit weird is in Smalltalk a class variable's value exists for eternity, for as long as the class exists in the image, or until somebody changes it. That's a foreign concept to most programmers, because to them programs have a lifetime. You run them. They run for a while (or indefinitely if they're designed that way), and then they stop. All variable values are gone.
Another difference, from my experience, is that class methods have a sense of "self" (ie. a "this"), whereas static methods in C++, Java, etc. do not. In C++, for example, you can't take a "this" and cast to a base class's version of the "overloaded" method you're in (a method of the same name as the base class's method), when in a static method. You have to use scoping syntax. I haven't tried it, but it looks to me like in Smalltalk you could do this (no casting, but using the "super" keyword).
Yeah, it's actually intrinsic to early binding.
I don't know exactly what you mean. The big frustration in my life right now is that my Seaside/Smalltalk learning got waylaid by other stuff going on in my life. I don't think there's such a thing as a static method in Smalltalk, in the Java sense, is there?
Smalltalk doesn't have static methods. Static methods are weird, they don't belong to anything, they are really just scoped free floating functions.
Smalltalk is simple. Everything is an object. The term "object" means an instance of a class. All objects have instance methods, and instance variables. All objects have a superclass, and can refer to them via the keyword #self. All classes are a running instance of some other class somewhere in the system. Since classes are also themselves objects, then it follows that they can have instance variables and methods.
Classes also have what are called class variables, this is like what'd you think of as static, ie both the class and its instances can see these. These are mainly used to declare constants I think.
When you declare a class...
Object subclass #Customer
another class is created for you automatically that parallels that using your classes name plus the word class.
#'Customer class'
Your #Customer class is actually the sole instance of that hidden meta class #'Customer class'.
#Customer superclass is #Object, #'Customer class' superclass is #'Object class'. These are called meta classes. The meta class is a subclass of the meta class of the class you were subclassing.
So when you edit the class side, you're actually editing the hidden meta class definition that defines your class, which is its sole instance.
Therefore, class methods are actually just ordinary methods, unlike static methods. Class methods have access to #self, which refers to the class itself, and class methods are inheritable and overridable, unlike static methods. Since constructors are just class methods, this means you can inherit and override and extend constructors, without being forced to redeclare them in all subclasses like you would in Java or C#.
Since classes are just ordinary objects, you can put them into variables and pass them around, and call methods on them, like any ordinary object.
Consider an array of classes...
class := {Customer. DateTime. String} atRandom.
instance := class new.
The variable instance could have one of three possible instances in it. #new is not a static method, or a freaky special nameless method like in Java and C#, it's just an ordinary instance method that all three of those classes inherit from some superclass they have in common.
I haven't tried it, but it looks to me like in Smalltalk you could do this (no casting, but using the "super" keyword).
Correction: Actually, I have done this. I didn't realize it (probably because it's so easy), but it's difficult to get too much done without doing this.
You see a lot of this in Smalltalk class methods:
SomeClass>>createInstance
^super new initialize.
which passes a "new" message to the base class, and sends an initialization message to the resulting object instance.
@Giles:
Re: static methods
As Ramon said there's no such thing as static methods in Smalltalk. I was just talking about what's analogous to a class method in Smalltalk, in C++, Java, C#, etc., which is a static method. For example, if you have, as a class method:
SomeClass>>getInstance
^super new
you can call it like (say, from within a Workspace):
instance := SomeClass getInstance
Like you were saying with Ruby class variables, I didn't have to say "SomeClass new" beforehand. The class object just exists, and I can call a method on it at any time.
This is roughly equivalent to, in C++:
SomeClass.h:
class SomeClass {
static SomeClass *GetInstance();
};
SomeClass.cpp:
#include "SomeClass.h"
static SomeClass *SomeClass::GetInstance()
{
return new SomeClass;
}
and is called like:
void main(void)
{
SomeClass *ptr = SomeClass::GetInstance();
}
Obviously with such a simple example, I could've just had a constructor instead, but this is how class factories and singletons (from patterns) are often done in C++, Java, C#, etc.
The reason it's roughly analogous is that static methods are available all the time (while the program is running). You don't need an object instance to call them. As I and Ramon said, the idioms are inconsistent in languages like C++, et al. For static methods you have to use scoping syntax, as I illustrate above, to call them. For instance methods, you call "ptr->SomeMethod()". Instance methods have an implicit "this" pointer/reference, so you can refer to variables and methods inside the object, like "someVariable" and "someMethod()" without saying "this->someVariable" and "this->someMethod()" all the time ("this" is analogous to "self" in Smalltalk).
Static methods don't have an implicit "this" pointer, so you have no access within the method to any of the objects that belong to the same class it belongs to. It only has access to static member variables, or global variables. This is rather like Smalltalk class objects as well. They only have access to their own class variables, and class variables/methods of other classes. They have no access to instance variables/methods, unless an object instance is given to them.
Classes in C++, et al. exist only as "object templates" within the compiler's symbol table. When they're instantiated into objects, it's like they're "stamped" into the executable image, as well as the memory, using the "template". There's no access to the classes themselves in C++.
Within Java and .Net it is possible to get access to some metadata for classes. It's even possible to dynamically construct classes, and generate object instances from them, but it's pretty complicated. It's not nearly as easy as it is in Smalltalk, and I assume, Ruby.
@mark -- you should learn Ruby, it's a great language. if you've used Smalltalk you can pick up Ruby in no time, too, it's almost just a Unix dialect of Smalltalk.
Re: You should learn Ruby
I took a look at it briefly last summer. It came highly recommended from an old friend of mine. He had been working with Ruby for about 3 years (not Rails, though). He swore by it. I found a couple of Ruby demos/tutorials which were impressive. The syntax reminded me a bit of Smalltalk. I had heard from this same friend that the modern Smalltalk was called "Squeak" and was open source. So after puttering with Ruby for a bit I took a look at Squeak and was blown away by some of the things it could do. I've been just kind of stuck here ever since (pleasantly :) ), but the idea of returning to Ruby for the purposes of actually making some money (the first duty of a programmer is to eat) has crossed my mind. We'll see. | http://gilesbowkett.blogspot.com/2007/03/java-is-platos-republic.html?showComment=1175158020000 | CC-MAIN-2016-36 | refinedweb | 1,708 | 72.16 |
Code. Collaborate. Organize.
No Limits. Try it Today.
.NET gives an easy way to store configuration information in an Application Configuration File. In the simple implementation, you can store information as Key-Value pairs.
For example, consider a case where you have to use a data source in your application. If you hardcore the data source information in your code, you will have a bad time when you have to change this data source. You have to change your source code and re-compile it. This won't work every time you give your product to different customers or when you run your application in different machines!
In earlier days, programmers used to store this information in special files called .ini files or in system registry. The application can read the information from the .ini file or registry and no need to re-compile the code when the values are changed in .ini file or registry.
But this is a pain most of the time. It is not fun opening the registry, locate your entries and make appropriate changes. It is quite possible that you may mess up with some important entries in the registry and make your system not run any more. In fact, in secured systems, administrator may deny access to the registry and users will not have the choice to edit the registry at all.
.NET gives you a simple and easy solution for this problem - the Application Configuration File. Each application can have a configuration file, which is actually an XML file. You can use any text editor (including Notepad) to open the configuration file and change the values. The application will load the values from this configuration file and you do not have to change your source code every time you change your data source or any other information stored in the configuration file.
Windows applications in VS.NET use the name app.config by default for the configuration file. This will not be automatically created when you create a Windows application. If you need a configuration file for your application, open your project in VS.NET, go to the 'Solution Explorer' and right click on the project name. Choose Add > Add new item from the menu and select 'Application Configuration file' from the list of choices. This will create an app.config file for you in the application root.
By default, the app.config file will have the following content:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
To store values in the configuration file, you can create XML elements in the format:
<add key="MyKey" value="MyValue" />
See the sample config entries below:
<?xml version="1.0" encoding= "utf-8" ?>
<configuration>
<appSettings>
<add key="DatabasePath" value="c:\\projects\data\spider.mdb" />
<add key="SupportEmail" value="webmaster-1@dotnetspider.com" />
</appSettings>
</configuration>
And to read from this config file, just use the following code in your application:
string dbPath =
System.Configuration.ConfigurationSettings.AppSettings["DatabasePath"];
string email =
System.Configuration.ConfigurationSettings.AppSettings["SupportEmail"];
ConfigurationSettings is the class used to access the contents of the configuration file. Since this class is part of the namespace System.Configuration, we have to use the fully qualified name System.Configuration.ConfigurationSettings. As a shortcut, you can use the using directive on top of the file like below:
ConfigurationSettings
System.Configuration
System.Configuration.ConfigurationSettings
using
using System.Configuration;
If you have the above directive on top of the file, then you can directly use the class ConfigurationSettings.
string dbPath = ConfigurationSettings.AppSettings["DatabasePath"];
string email = ConfigurationSettings.AppSettings["SupportEmail"];
In VB.NET, you have to use "( ... )" instead of the "[ ... ]", as shown below:
Dim dbPath as String = ConfigurationSettings.AppSettings("DatabasePath")
Dim email as String = ConfigurationSettings.AppSettings("SupportEmail")
Note: When you compile your application, VS.NET will automatically create a file called <your application name>.exe.config in your bin\debug folder. The contents of the app.config will be automatically copied to this new config file when you compile the application. When you deliver the application to the end user, you have to deliver the exe and this new config file called <your application name>.exe.config and NOT the app.config. Users can modify the data in <your application name>.exe.config file and application will read the data from the config file, when restarted.
The web applications use the same concept, but they use a config file with the name web.config. There are couple of things to note in this case.
<appSettings>
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
Dim app As New System.Configuration.AppSettingsReader
Dim s As String
s = app.GetValue("DatabasePath", Type.GetType("System.String"))
MessageBox.Show(s)
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
C# 6: First reactions | http://www.codeproject.com/Articles/6538/Configuration-Settings-File-for-providing-applicat?msg=4534482 | CC-MAIN-2014-15 | refinedweb | 843 | 51.44 |
What's New in ReSharper
ReSharper/ReSharper C++ 2017.1
- Full support of Visual Studio 2017.
- Filters in Go to everything and Go to text, which you can type right into the search field before or after the search query.
-.
- EditorConfig support.
-.
- Generating Properties for TypeScript classes.
- Postfix Templates.
- New features for ReSharper C++ 2017.1:
-.
- File Header Style.
- (), which allows adding.
- The Usages of Symbol action lets you switch from the pop-up Go to Everything.
- Go to Text.
- Structural Navigation.
-.
- JSON value helpers.
- - Ctrl+Alt+L ( ). Previously, you could do the same by invoking code cleanup with the 'Default: Reformat code' profile.
- A dedicated command that applies code style in the selected scope - Ctrl. Please (Ctrl).
ReSharper 9.2/ReSharper C++ 1.1
- Full support of Visual Studio 2015.
- Run configurations that help you run and debug code in your solution with different startup properties.
- Massive improvements in JavaScript and TypeScript support:
- Support for Typescript 1.5 (including decorators, ES6-compatible modules, ES6-style imports/exports, local types)
- Support for some of TypeScript 1.6 features .
ReSharper 9.1
- Improvements in Visual Studio 2015 CTP support
- .NET framework 4.6 support
- TypeScript 1.4 support
- ECMAScript 6 support
- Improvements in the Find Usages feature, including support of 'quasi-implementation' feature of C# and selection of the search algorithm for generic substitutions .
- Source Templates that can be created right in the code of your project as extension methods.
- NuGet Browser that halps you search for types or namespaces in the NuGet package gallery and easily download and install the package that you choose.
- Configurable style for usages of built-in type.
- Installer improvements: silent and per-machine installation modes.
- JSDoc support in JavaScript and TypeScript.
- Ability to match dependency properties amd arrange items in groups as well as other improvements in File and Type Layout.
- New commands for copying symbol information n (XML-doc ID and fully-qualified name) to the clipboard
ReSharper 9.0
- Visual Studio 2015 CTP support
- C# 6.0 support, including conditional access expression, expression-bodied members, auto-properties with initializer expression, etc.
- Support of C++ in the dedicated product ReSharper C++, which is also available as a part of ReSharper Ultimate.
- Regular expressions assistance including syntax and error highlighting, completion features, quick-fixes and more.
- Type dependency diagram - a new visual code analysis tool that complements the existing project dependency diagram.
- Major improvements in TypeScript support, including, but not limited to:
- Configurable TypeScript language level up to 1.3.
- New code inspections including inspections for about 300 compiler errors and inspections dependent on project properties + about 100 new quick-fixes. For more information, see Code Inspection and Quick-Fixes in TypeScript.
- Import missing namespace pop-up.
- Code generation actions (Generate missing/overriding members, Generate constructor).
- Performance improvements and new features in code completion. You can now apply filters to completion suggestions, complete call chains based on existing patterns in your solution, and more.
- Code style assistance improvements: a number of new code style preferences that have common configurations for both code inspection and code cleanup. For more information, see Code Style and Cleanup.
- Entering license information using the JetBrains Account.
- Ability to suppress some or all code inspections in specific type or method using the
SuppressMessageattribute.
- The Fix in Scope feature is supported for more quick-fixes. Now the global fixes work for naming rules, code redundancies, and more.
- Similarly to 'Fix in scope', some context actions can be now also applied in a wider scope.
- The Navigate to Action feature that allows you to find and execute any ReSharper command with a couple of keystrokes.
- The Navigate To Exposing APIs action that allows finding all methods returning a specific type.
- Recently viewed methods and performance improvements in Go to Everything.
- A new visual editor greatly simplifies understanding and editing of file and type layout patterns.
- Support of custom HTML harness for JavaScript unit tests.
- Search through preferences in the Options dialog.
- Ability to toggle support of languages and feature sets on the page of ReSharper options.
- Ability to view and configure code formatting rules that are applied for selected code block (supported in JavaScript, TypeScript, and C++).
ReShar and Unit Test Explorer the Preview Tab in navigation and search
- Transform Out Parameters refactoring
-
- and JavaScript Unit Testing support for QUnit
ReSharper 5.0
- An extensive feature pack for web development:
- Master page support in navigation and generation actions.
- Generating Content tags based on
ContentPlaceHoldertags:
- Results to navigate from usage of a base type or member to any of its end implementations.
- Inline Field ref attributes to make ReSharper analyze your code even better than before - for instance, to let it know where format strings should be passed or where null values can now support C# 3.0. New members of the refactoring family are available, including - Basic Completion, Smart Completion, and Import Symbol Completion - let you complete any symbol by entering only its uppercase characters.
- Templates Explorer and features allow you to display destination types/symbols/files in the Find Results window.
- To-do items are now discoverable in identifiers and strings.
- File Structure,Go to File Member, and Go to Next/Previous Member for (C#, VB.NET and Full).
- Ability to find code dependent on specific module and find usages of symbols external to scope.
- Go To Symbol for robust solution-wide search by name for any file member.
- Disabling warnings at a specific position: configure the "Disable warning" context action and apply it where necessary.
- Unit Test Explorer window: unparalleled flexibility in running and debugging unit tests.
- XML and XAML support.
Last modified: 12 October 2017 | https://www.jetbrains.com/help/resharper/2017.1/Introduction__Whats_New.html | CC-MAIN-2018-05 | refinedweb | 935 | 50.12 |
Here's a system that "user-izes" process management
Barr works for Schering-Plough Research, a pharmaceutical company. He can be reached at 60 Orange Street, Bloomfield, NJ 07003.
I undertake scientific computing using a number of networked workstations, compute servers, and a super-computer. Typically, problems are set up and the results are analyzed on the workstations, while the actual number crunching activity is performed on the more powerful machines. The description of this approach is straightforward, but the tools necessary to manage the jobs that originate from a central workstation, and are then run on a variety of remote hosts over a network, are not generally available.
For instance, with the standard available Unix System V tools, you cannot ask user-oriented questions, such as "What applications and datasets are running on any remote host?" "Which applications are pending?" or "What is the status of a certain job?" without resorting to Unix commands that oftentimes do not look like the user's actual query.
This article presents a system designed to "user-ize" the management of background processes that run both locally and across a network. The system, which I call "shepard," includes a standardized interface that utilizes menus where appropriate to reduce the management of processes down to the essentials: Tasks, executable scripts, dataset names, and remote host names. The specifics of the process of executing, monitoring, and retrieving programs that run remotely are hidden in shell scripts. The bulk of this system is written in Bourne shell script and is reasonably portable.
System Overview
The basic idea behind this system is to use a series of scripts to control all activities that occur locally or on a remote host, and to do so in a simple, straightforward, user-oriented manner. Integral to this activity is the establishment of a queuing system to handle job control, simplify the selection of the host and programs, invoke the programs, move the data files over a network, and record all activities. The core of the system consists of five Bourne shell scripts -- run, shepard, shepard_ queue, shepard_exec, and run_update -- and a number of application-specific control files that contain either tables or control scripts. When the system runs it generates a number of status files to show the jobs that are waiting, running, finished, and restartable on each remote host. The system also generates a file on the origin machine to show the status and location of all jobs.
I have commented the code extensively to describe its features and operation. Descriptions of the scripts are presented here to give you a general understanding of the role of each script in the overall system. For specifics, refer to the listings.
The script run is a menu-driven task manager that queries for a task, a script, a dataset, and the host. run then carries out the requested task by invoking shepard on the selected host through a remote shell (rsh) command. run maintains a list of jobs originating from the origin machine as well as a log file, and serves as a hub that coordinates jobs run on several machines. Through run, the user knows which programs are using which datasets and where those programs are running. The tasks managed by run are simple and include starting and stopping the execution of programs, determining the status of jobs running on a specific remote host, and probing running jobs for intermediate results or status information. run performs all of its work, including the generation of most menus, through the other scripts across the network by use of rsh calls.
The types of tasks that the shepard system currently performs include:
- Execute a job, locally or over a network by a remote host
- Monitor the remote host
- Probe a running job for intermediate results
- Kill a running job with extreme prejudice
- Halt a running job in a controlled manner
- Restart a job
- List running, waiting (enqueued), restartable, and finished jobs
- List general and error log files
The script shepard_queue maintains a FIFO queuing system that regulates both the numbers and the types of jobs allowed to execute concurrently. This approach is a good way to maintain a balance between throughput and maximum system performance. The executing task is started by invoking shepard_exec as a background task. An error log is maintained. Instead of using multiple queue files, a single queue file is used both for the sake of simplicity and because the queue file is used to generate a menu.
The script shepard-exec has embedded in it the specifics for moving data into the execution environment, running the selected program, moving the results back, and calling shepard to update the control files. The specifics of program invocation -- the process of copying data files from origin to host, executing the program, and transferring the result files back to the origin machine -- are hidden in scripts. shepard_exec needs only the name of the script and the specific dataset for the run; all else is controlled by the specifics in the scripts.
The script run_update updates the status file on the origin machine to reflect the current status of the job. run-update is invoked by remote shell calls from both shepard and shepard_queue.
Networking
Three types of data transfer are supported: remote, nfs, and server. The best choice depends very much upon your particular environment and operating preferences. The choice of network is set in .shepard.ini.
In remote mode, the data is copied from its directory on the origin machine into the user's login account on the selected host and then executed. The output is transferred back to the origin. The input and the output exist on both machines. This approach provides a more robust operating mode when the network is unreliable, but it is not the best mode to use with very large datasets.
In nfs mode, the data is accessed through remotely mounted network drives by using Sun's NFS Network File System, and is not actually moved. The output in nfs mode is written directly to the network drive. Only one copy of the input and the output is generated. This mode is sensitive to network crashes.
In server mode, the data exists, and the execution is performed, entirely on the compute server. Only one copy of the input and the output is generated. This is the best mode to use with large datasets, and is also useful when the network is unreliable because the data never moves over the network.
I generally use the server mode through an NFS-mounted directory. This method provides the benefits of direct access to data without having to move it, and is especially beneficial when the datasets are large.
An Example
The control files in this example are those used in my working environment, and they reflect both the machines and the programs I use in computational medicinal chemistry. The application example is for a version of BATCHMIN (Columbia University), which is the premiere program for molecular simulation. The application is dimensioned to handle protein-sized problems, and is run only on a Convex supercomputer. The problems are set up graphically on an Iris workstation and then are transferred to the Convex for simulation. (The simulation process can last longer than a week for a single problem.) The application script is called bmin31lv, and the dataset is referred to as bmintest.
The operation of the user interface is described in the comments. The selection of executable scripts, the performance of status queries for running jobs and the like, and the execution of available tasks are all menu-driven activities. I have included niceties such as the listings of completed jobs when run is started, plus the retention of selected values for scripts, datasets, and hosts as defaults for the next invocation of run.
When a job is intended for launching, run passes the selection information to shepard on the selected host, and then adds the new job to the origin machine's .current file with status STARTED. At this point run is no longer involved with the process.
When it's invoked by run, shepard creates a lock file, .sheplock. .sheplock forces all other invocations of shepard to wait and also insures sole access of all control files by shepard. .sheplock's control extends through the invocation of shepard_queue. shepard passes the information to shepard_queue, which places the job in the .waiting file and gives the job the highest priority value for that script so that the newly submitted job will be the last one to execute. The origin machine's .current file is updated to status WAITING.
shepard_queue checks the job count of a particular script against the maximum job count in .limits and proceeds to execution if below, or exits, leaving the job enqueued. To execute the job, the script shepard_exec is passed all the relevant job information and submitted as a background process. The job is removed from .waiting and placed in .running with the process ID (pid) by shepard_exec. If the job fails it is placed in .restart. The .current file on the origin machine is updated to status RUNNING. shepard_ queue returns to shepard, removes the lock, and exits. A log of all activities is maintained so that the user can later determine what happened.
shepard_queue sources an application-specific file, which in this case is bmin31lv.script. This file defines the generic shell variables in shepard_exec for the specifics of the application. (The use of shell variables to represent the various file extensions makes the basic shepard_exec more flexible.) Data is moved by bmin31lv getdata, which is defined in $getdata_script. The application is executed with the assumption that it needs a standard input, and generates output to standard output and standard error. bmin31lv takes its command input via the standard input from bmintest.com, and generates run output via standard output to bmintest.log. It also uses bmintest.dat, which is moved along with bmintest.com into the execution environment. bmin31lv also generates a bmintest.out, which is returned to the origin machine. The output files are moved back across the network using the script bmin31lv.putdata, which is defined in $putdata_script. From the user's point of view, all of the requisite files are named, created, and moved based only on the application script and the dataset name; the specifics are buried in the scripts.
Upon completion of this process, shepard_exec calls shepard with the -z option. shepard_exec may have to wait while other processes (such as run) and other completing jobs execute shepard. Once in control, the job is removed from .running and placed in .finished. The origin machine's .current is updated to DONE, the log files are updated, and the job passes into history. shepard_queue is invoked with the -q option to check for waiting jobs, and launch if possible. The final act is to remove .sheplock.
A different example is the killing of a running job. When the kill task is selected in run, shepard is called on the selected host. Once control is established, a menu of running jobs is generated from .running and control is returned to run. The job to be killed is selected by its entry number. shepard is again invoked, and now passes the selection number of the job as the fifth argument. shepard looks up the pid of the selected job, and kills the script associated with that pid. The process listing is searched for child processes (which in this case is the application) and the child processes are also killed. The job is removed from .running and the log files are updated. Control passes back to run.
From the user's point of view, the shepard system achieves its goals of simplifying the network management of jobs, and tells the user which jobs are located where, based upon what is important: the application and the dataset. A benefit of the queue system is that numbers of jobs can be left pending (and easily managed) without fear of "choking" the system if they're improperly enqueued or if they're blocking other types of jobs.
Control Files and Menu Generation
The control files are doubly useful both for generating menus and building tables of values for lookup. In fact, the Unix utility program Awk is handy for both tasks. I provide code examples to show the process of generating "pick-an-item" menus and lookup of values based upon the selected item number. Although, the code examples are very simple, I have never seen Awk used in this manner.
The control files use space separation between the fields. Awk has the flexibility to use selected fields (words) out of a single record (line). This flexibility offers the option to use the first several fields on a line as lookup values, and to use the rest of the fields on the line as information displayed in the menu. An example of this method is .hosts, in which the first word on each line represents a possible host, and the remainder of the line describes the host.
The formats of the various control files are shown in Table 1. The other control files (.run.ini and .shepard.ini) and the application-specific scripts are all Bourne shell scripts, and are commented with respect to their functions.
Table 1: Control file formats
File Format -------------------------------------------------------------------- .runscripts: hostname script (remainder is descriptive comment) .hosts: hostname (remainder is descriptive comment on host) .tasklist: flag (remainder is description of 'run' task) .limits: hostname script maximum-jobs-per-script .current: script dataset host datadir start finish status .waiting: script dataset host datadir queue-position .running: script dataset host datadir process-id .finished: script dataset host datadir finished-time .restart: script dataset host datadir
Installation
The scripts and the control files should be placed on all desired machines. Give the scripts run, shepard, shepard_ queue, shepard_ exec, and run_update (Listings One through Five, pages 82-88) execution privilege, and place them in a directory accessible through the path. Place the control files for the scripts run (.run.ini, .current, .hosts, .tasklist, and .runscripts, Listings Six through Nine, page 90) and shepard (.limits and .shepard.ini, Listings Ten and Eleven, page 90) in the user's login directory. Create a directory for the application-specific scripts (Listings Twelve through Sixteen, page 90) and move those scripts into the directory. Finally, compile lockon.c (Listing Seventeen, page 90) and place the executable in a directory accessible through the path.
Modify the control files according to your needs and your network setup. Change .hosts to reflect the accessible machines on your network, and modify .runscripts so that it uses both the accessible machines and the control scripts for your applications. Make the same changes to .limits that is made to .runscripts, and add the numbers that correspond to a desired mix of running jobs for a maximum load situation.
Create the application-specific scripts for your specific applications and needs. Use the example scripts for bmin31lv as a template. If your applications do not have a graceful terminate or probe capability, set the variable assignments in the master application .script file equal to no strings.
Modify the control file .shepard.ini to reflect your applications present on all available platforms, your preferred mode of network access, and the directory in which the application-specific scripts are kept. (The application names are without the .script extension.) Make sure that the network mode is the same in the .shepard.ini files for pairs of platforms. Generally, you cannot mix network modes between specific pairs of machines, although other modes can be selected for other pairs.
Finally, if the machines on your network are not communicating freely, make the necessary changes to the system files that control access. You should have accounts on all desired machines. The /etc/hosts and /etc/hosts.equiv on each of a pair of desired machines must be set so that the rsh command works properly. If you intend to use nfs to move files between files, make sure that your nfs is enabled and that the necessary directories are mounted remotely.
The system works without modifications between Silicon Graphics Iris platforms that use Unix System V, Version 3.2, and a Convex C-220 that uses Berkeley Unix 4.2, when all of the communications requirements are met.
Future Enhancements
The shepard system is functional, but not complete. A facility to check for crashed jobs and then clean them up is under development. Also, the changes necessary in order to support multiple users are straightforward, but they introduce a complication with respect to the queuing limits: The mix of jobs must also include a mix of users.
_CONTROLLING BACKGROUND PROCESSES UNDER UNIX_ by Barr E. Bauer
[LISTING ONE]
<a name="025d_000c">
origin=`hostname`
# run - the user interface component of the shepard system -- B. E. Bauer 1990
# configuration files associated with run:
# .run.ini defaults for script,dataset,host,datadir.
# .current jobs originating from workstation environment
# .hosts host machines able to run shepard
# .tasklist list of tasks. Has flags for shepard
# .runscripts list of machines and possible scripts
# these files must be located in the login directory
# flag (and task definitions) definitions, Used in case statement
# and passed as actual flag arguments to shepard:
# x executes (submits) a job
# m monitors job
# p probes job
# s status of running jobs on all platforms
# r list of running jobs
# k kill job (with extreme prejudice)
# t terminate job in a controlled manner (script dependent)
# l list log on remote machine
# b bump a waiting job from the .waiting list
# d delete a waiting job
# f list finished jobs
# e list error log
# c change host
# w list waiting jobs
# a list restart jobs
# g restart a restartable job
#place the date/time in day-month-year@time single string format
set - `date`
year=$6 month=$2 day=$3 tm=$4
datetime=$day-$month-$year@$tm
echo 'welcome to run on '$origin' at '$datetime
. $HOME/.run.ini #source the run-script defaults
. $HOME/.shepard.ini # has network definition
# check for finished jobs, update list, display finished list
# find jobs with status RUNNING, check host for status
if (test -f $HOME/.current) then
cnt=`grep -c DONE $HOME/.current`
if (test "$cnt" != "0" ) then
awk 'BEGIN {
printf "\njobs recently finished\n"
printf "\n%-10s %-10s %-8s %-21s %-21s\n\n",\
"script","dataset","host","start","end"
} $7 == "DONE" {
printf "%-16s%-16s%-8s%-20s%-20s\n",$1,$2,$3,$5,$6
} ' $HOME/.current >tmp
echo ' '; cat tmp # display list of completed jobs
echo 'press any key to continue \c'; read sel
cat tmp >> $HOME/run.log # completed job data to runlog
awk '$7 != "DONE" {
print $0
} ' $HOME/.current >tmp
mv tmp $HOME/.current
else
echo "no new finished jobs"
fi
fi
# set default host. All activities focus on that host until changed
awk 'BEGIN {
n=1
printf "\n----- current hosts -------------------------\n\n"
} {
if ("'$defhost'" == $1)
printf "%-3s%-16s%s %s %s (default)\n",n,$1,$2,$3,$4
else printf "%-3s%-16s%s %s %s\n",n,$1,$2,$3,$4
n++
}
END {
printf "\nselect a host machine by number: "
}' $HOME/.hosts
read sel
if (test -z "$sel") then
host=$defhost
else
sel=`awk 'BEGIN {n=1}{if ("'$sel'" == n) print $1; n++}' $HOME/.hosts`
host=$sel; defhost=$sel
fi
loop=YES
# top of loop. exit with <ret>
while (test "$loop" = "YES")
do
# display menu of tasks
echo ' '; echo 'current host is ' $host
echo ' '
awk ' BEGIN {
n=1
printf "\t# flag task\n"
printf "\t----------------------------------------------\n"
}{
printf "\t%-3s\t%s\n",n,$0
n++
}
END {
printf "\ntask selection number [<ret> to exit]: "
} ' $HOME/.tasklist
read sel
# look up value for shepard flag associated with task.
# Use the flag in the case statement
task=`awk 'BEGIN {n=1} {if("'$sel'" == n) print $2; n++}' $HOME/.tasklist`
flag=`awk 'BEGIN {n=1} {if("'$sel'" == n) print $1; n++}' $HOME/.tasklist`
# if response is <ret>, exit while loop
if (test -z "$sel") then
break
fi
case $flag in
-x) # start a job. Queries for script, dataset, datadir
# list scripts available only on selected host
awk ' BEGIN {
n=1
def=0
printf "\n# (host) script"
printf "\n-------------------------------------\n"
}
"'$host'" == $1 {
if ($2 == "'$defscript'") {
printf "%-2s %s (default)\n",n,$0
def = n
}
else printf "%-2s %s\n",n,$0
n++
}
END {
printf "\nselect a script by number [%s]: ",def
} ' $HOME/.runscripts
read tmp
# look up the script selected by number (must be on one line)
sel=`awk 'BEGIN{n=1} "'$host'"==$1 {if("'$tmp'" == n) print $2; n++} ' $HOME/.runscripts`
if (test "$sel" = "") then
script=$defscript
else
script=$sel; defscript=$sel
fi
echo 'selected script is '$script
# get the dataset name
echo ' '; echo 'enter dataset name ['$defdata']: \c'
read sel
if (test "$sel" = "") then # substitute default for <ret>
dataset=$defdat
else
dataset=$sel; defdata=$sel
fi
echo 'selected dataset is '$dataset
# get the directory where the data is located
# if $SHEPARD_NETWORK is set to "remote", data moves between machines
# using nfs otherwise, data is retained on server
# home directory on the host machine, then back when done
echo ' '; echo 'enter directory of data on '
case $SHEPARD_NETWORK in
remote) echo $iam': \c';;
nfs) echo $iam' using nfs mount on '$host': \c';;
server) echo $host': \c'; defdir='$HOME';;
esac
read sel
if (test "$sel" = "") then # substitute default for <ret>
datadir=$defdir
else
datadir=$sel; defdir=$sel
fi
echo 'selected directory is '$datadir
# append new job entry to $HOME/.current
llist='$script $dataset $host $datadir $datetime'
echo $llist 'out' 'STARTED' >>$HOME/.current
if (test "$origin" = "$host") then
shepard $flag $script $dataset $host $datadir
else
rsh $host shepard $flag $script $dataset $origin $datadir
fi;;
-s) # listing of current file. shows activity on other platforms
awk ' BEGIN {
fmt="%-5s %-16s %-16s %-21s %-16s\n"
dash5="-----"
dash16="----------------"
dash21="---------------------"
n=1
printf "\n\ncurrent job status\n\n"
printf fmt,"#","script","dataset","submitted","status"
printf fmt,dash5,dash16,dash16,dash21,dash16
printf "\n"
} {
printf fmt,n,$1,$2,$5,$7
n++
}
END {
printf "\npress any key to continue "
} ' $HOME/.current
read sel;;
-[ktpdbg])
# these are all list processing commands using pick an item menuing
# the menu is generated by shepard on the selected host
# the item is picked in run and the selection happens in shepard
case $flag in
-[ktp]) lflag='-r';; # list running jobs
-[db]) lflag='-w';; # list waiting jobs
-g) lflag='-a';; # list restartable jobs
esac
if (test "$origin" = "$host") then
shepard $lflag dummy2 dummy3 dummy4 dummy5
else
rsh $host shepard $lflag dummy2 dummy3 dummy4 dummy5
fi
echo ' '; echo 'select number of job to \c'
case $flag in
-k) echo 'kill \c';;
-t) echo 'halt gracefully \c';;
-g) echo 'restart \c';;
-d) echo 'remove from waiting queue \c';;
-b) echo 'bump to top of queue \c';;
-p) echo 'probe running status \c';;
esac
read sel # select one from list
arg5=$sel
if (test "$origin" = "$host") then
shepard $flag dummy2 dummy3 dummy4 $arg5
else
rsh $host shepard $flag dummy2 dummy3 dummy4 $arg5
fi;;
-c) # change hosts
awk 'BEGIN {
n=1
printf "----- current hosts -------------------------\n\n"
} {
if ("'$defhost'" == $1) {
printf "%-3s%-16s%s %s %s (default)\n",n,$1,$2,$3,$4 }
else printf "%-3s%-16s%s %s %s\n",n,$1,$2,$3,$4
n++
}
END {
printf "select a new host machine by number: "
}' $HOME/.hosts
read sel
if (test -z "$sel") then
host=$defhost
else
sel=`awk 'BEGIN {n=1}{if ("'$sel'"==n) print $1; n++}' $HOME.hosts`
host=$sel; defhost=$sel
fi;;
-[rewfalm]) # process listing commands
if (test "$origin" = "$host") then
shepard $flag dummy2 dummy3 dummy4 dummy5
else
rsh $host shepard $flag dummy2 dummy3 dummy4 dummy5
fi
read sel;;
*) # woops
echo $flag 'is not a recognized option, try again'
esac
done # bottom of while loop
# write current values to run-script default file
# $HOME/.run.ini is sourced on invocation in effect restoring the
# last values used. Handy for checking on a previously
# started job - values properly default to the previous
echo 'defscript='$defscript >$HOME/.run.ini
echo 'defdata='$defdata >>$HOME/.run.ini
echo 'defhost='$defhost >>$HOME/.run.ini
echo 'defdir='$defdir >>$HOME/.run.ini
echo 'end of run'
<a name="025d_000d"><a name="025d_000d">
<a name="025d_000e">[LISTING TWO]
<a name="025d_000e">
trap 'rm -f $HOME/.sheplock; exit' 1 2 3 15
# shepard - task management component od shepard system -- B. E. Bauer 1990
# Shepard is the action component of the system. When invoked, it
# owns all the associated files (see top of shepard_queue for list)
# and updates the current file on the originator, log and err files.
# Shepard can be invoked from local or remote machines; it senses
# local or remote operation and behaves accordingly.
# Shepard handles all tasks except for job queueing (shepard_queue) and
# application-specific job probing (defined in $probe_script as sourced
# in 'script'.script). Shepard is called by terminating jobs for cleanup.
# Shepard can be present in several executing copies called by run (the
# user interface) and by completing jobs waiting for cleanup. To avoid
# collision between shepards, absolute ownership of all associated files
# is essential, and is accomplished by creating a lock file. All other
# versions of shepard have to wait until the first is done.
# wait until lock file established insures complete ownership
# of all files by only one version of shepard at a time
until lockon .sheplock
do sleep 5; done
iam=`hostname`
. $HOME/.shepard.ini # source the initialization file
# do not display greeting message if called from terminating process
if (test "$1" != "-z") then
echo 'shepard on '$iam' at '`date`
fi
# if you see the message, you made it.
# Important verification that remote shell command is functioning
# lookup values from files depending on mode
pass=NO
case $1 in # select the file name associated with flag
-[ktp]) fname=$HOME/.running; pass=YES;;
-[bd]) fname=$HOME/.waiting; pass=YES;;
-g) fname=$HOME/.restart; pass=YES;;
esac
if (test "$pass" = "YES") then # do the lookup
scr=`awk 'BEGIN {n=1} {if ("'$5'" == n) print $1; n++}' $fname`
dset=`awk 'BEGIN {n=1} {if ("'$5'" == n) print $2; n++}' $fname`
host=`awk 'BEGIN {n=1} {if ("'$5'" == n) print $3; n++}' $fname`
ddir=`awk 'BEGIN {n=1} {if ("'$5'" == n) print $4; n++}' $fname`
sel=`awk 'BEGIN {n=1} {if ("'$5'" == n) print $5; n++}' $fname`
tname=$host':'$scr'('$dset')' # compact file name
fi
# no loop in shepard. Does the command then exits
case $1 in
-x) # runs job through queue manager which handles submission
shepard_queue $2 $3 $4 $5;;
-m) # system-dependent code here. "big" is using Berkeley UNIX
# while all others use SYSTEM V. Options to ps are different
if (test "`hostname`" = "big") then
ps -ax | grep -n shepard_exec # CONVEX specific (for example)
else
ps -ef # SGI IRIS specific (for example)
fi;;
-p) # probe job - script-dependent
# source the file containing application-specific scripts
. $SHEPARD_DIR/$2.script
. $probe_script;; # defined in sourced file $script.script
echo 'press <ret> to continue \c'
-r) # list running jobs on host
cnt=`wc -l $HOME/.running | awk '{print $1}'`
if (test "$cnt" = "0") then
echo ' '; echo 'no jobs running'; echo ' '
else
awk ' BEGIN {
fmt="\n%-5s %-16s %-16s %-8s\n"
printf "\n----- running jobs on %s -----\n","'$host'"
printf fmt,"#","script","dataset","pid"
printf "----- ---------------- ---------------- --------\n"
n=1
} {
printf fmt,n,$1,$2,$5
n++
}
END {
printf "\npress any key to continue "
} ' $HOME/.running
fi;;
-w) # list waiting jobs on host
cnt=`wc -l $HOME/.waiting | awk '{print $1}'`
if (test "$cnt" = "0") then
echo ' '; echo 'no jobs waiting'; echo ' '
else
awk ' BEGIN {
fmt="\n%-5s %-16s %-16s %-8s\n"
printf "\n----- waiting jobs on %s -----\n","'$host'"
printf fmt,"#","script","dataset","position"
printf "----- ---------------- ---------------- --------\n"
n=1
} {
printf fmt,n,$1,$2,$5
n++
}
END {
printf "\npress any key to continue "
} ' $HOME/.waiting
fi;;
-a) # list restartable jobs on host
cnt=`wc -l $HOME/.restart | awk '{print $1}'`
if (test "$cnt" = "0") then
echo ' '; echo 'no jobs in restart'; echo ' '
else
awk ' BEGIN {
fmt="\n%-5s %-16s %-16s %-8s\n"
printf "\n----- restartable jobs on %s -----\n","'$host'"
printf fmt,"#","script","dataset","position"
printf "----- ---------------- ---------------- --------\n"
n=1
} {
printf fmt,n,$1,$2,$5
n++
} ' $HOME/.restart
fi;;
-g) # restart a job from $HOME/.restart and update
# file to select passed as shell argument 5
# copys the selected entry to $HOME/.waiting with priority=RESTART
awk ' BEGIN {
n=1
} {
if (n == "'$5'") printf "%s %s %s %s RESTART\n",$1,$2,$3,$4
n++
} ' $HOME/.restart >> $HOME/.waiting
awk ' BEGIN { # restarted job is purged from $HOME/.restart
n=1
} {
if (n != "'$5'") print $0
n++
}' $HOME/.restart > tmp
mv tmp $HOME/.restart
echo 'restarting '$tname' at '$datetime >>shepard.log
#update .current on origin machine
if (test "$host" = "$iam") then
run_update -g $scr $dset $sel
else
rsh $host run_update -g $scr $dset $sel
fi
shepard_queue -r;; # do the restart
-k) # kill job with extreme prejudice
# pid passed as shell argument 5, assigned to sel
# running processes have 2 entries in the process list
# first = shepard_exec and has the pid stored in running
# second = the executable application
# searching the process list for first finds second; both
# must be killed to stop the application: killing shepard_exec
# alone leaves the application program still running
if (test "$iam" = "big") then
cleanup=`ps -axl | awk ' "'$sel'" == $4 {print $3}'`
else
cleanup=`ps -ef | awk ' "'$sel'" == $4 {print $3}'`
fi
kill -9 $sel
kill -9 $cleanup
if (test "$?" = "0") then
echo 'killed '$tname' at '$datetime >>$HOME/shepard.log
else
echo 'status of kill command nonzero - check log for problems'
fi
awk ' $5 != "'$sel'" { print $0 }' $HOME/.running > $HOME/tmp
mv $HOME/tmp $HOME/.running
#update .current on origin machine
if (test "$host" = "$iam") then
run_update -k $scr $dset $sel
else
rsh $host run_update -k $scr $dset $sel
fi
shepard_queue -q;; # check for waiting jobs
-t) # terminate job gracefully pass script and origin variables
# source the file containing application-specific scripts
. $SHEPARD_DIR/$2.script
. $terminate_script # found in scriptname.script
echo 'terminated '$tname' at '$datetime >> $HOME/shepard.log
#update .current on origin machine
if (test "$host" = "$iam") then
run_update -t $scr $dset $sel
else
rsh $host run_update -t $scr $dset $sel
fi;; # when the application exits, it will check for waiting jobs
-l) # list the job log on host
tail -30 shepard.log;; # only the last is generally interesting
-b) # bump priority of specific job
# $HOME/.waiting can be in any order, use 2-pass approach
# pass 1: set desired to zero, increment all others
# pass 2: change 0 to 1, zero now being easy to spot
awk ' {
if ($1 == "'$scr'") {
if ($5=="'$sel'") $5 = 0
if ($5 < "'$sel'") $5 += 1
}
printf "%s %s %s %s %s\n",$1,$2,$3,$4,$5
} ' $HOME/.waiting | awk ' {
if ($5 == 0) $5 = 1
printf "%s %s %s %s %s\n",$1,$2,$3,$4,$5
} ' > $HOME/tmp
mv $HOME/tmp $HOME/.waiting
echo 'bumped '$tname' at '$datetime >> $HOME/shepard.log
if (test "$host" = "$iam") then
run_update -b $scr $dset $sel
else
rsh $host run_update -b $scr $dset $sel
fi;;
-d) # delete a waiting job from waiting, selected passed as shell arg 5
# same script/higher priority have their priorities--
awk ' {
if ($1 == "'$scr'") {
if ($5=="'$sel'") next # excise deleted job
if ($5 > "'$sel'") $5 = $5 - 1
}
print $0
} ' $HOME/.waiting > tmp
mv tmp $HOME/.waiting
echo 'deleted '$tname' at '$datetime >> $HOME/shepard.log
#update .current on origin machine
if (test "$host" = "$iam") then
run_update -d $scr $dset $sel
else
rsh $host run_update -d $scr $dset $sel
fi;;
-f) # list finished jobs
awk ' BEGIN {
fmt="\n%-16s %-16s %-12s\n"
printf "\n----- finished jobs on %s -----\n","'$host'"
printf fmt,"script","dataset","origin"
printf "---------------- ---------------- ------------\n"
} {
printf fmt,$1,$2,$3
}
END {
printf "\npress any key to continue "
} ' $HOME/.finished;;
-e) # list error log
tail -30 $HOME/shepard.err;;
-z) # go to cleanup routine, $5 has the completed jobs pid number
echo 'finished '$4':'$2'('$3') at '`date` >>shepard.log
# write entry to .finished
# run on origin will look here for completed jobs
echo $2 $3 $4 $5 `date` >> $HOME/.finished
# excise finished job from $HOME/.running list
awk '{
if ("'$5'" != $5) print $0
}' $HOME/.running >tmp
mv tmp $HOME/.running
#update .current on origin machine
if (test "$4" = "$iam") then
run_update -f $2 $3 $5
else
rsh $4 run_update -f $2 $3 $5
fi
#check queue for waiting process
shepard_queue -q;;
esac
rm -f $HOME/.sheplock # remove locking file
# normal return to run if invoked by remote shell, otherwise terminates
<a name="025d_000f"><a name="025d_000f">
<a name="025d_0010">[LISTING THREE]
<a name="025d_0010">
trap 'rm -f $HOME/tmp; exit' 1 2 3 15
# shepard_queue - queue manager for shepard system -- B. E. Bauer 1990
# shepard_queue places jobs in a waiting queue and allows a job
# to actually start if the count of similar jobs running is
# below a user defined threshold. Its like a FIFO queue with a twist.
# This is intended to balance throughput vs system demands on
# multiprocessor high performance computers. Alter for your environment
# jobs in $HOME/.waiting have a number associated with their place in the
# queue. 1=next to start up to limit defined in .limits
# passed arguments:
# normal queue submit: 1: script name
# 2: dataset name
# 3: originating machine name
# 4: dataset directory
# restart 1: -r (no other values passed)
# queue check 1: -q (no other values passed)
#
# for restart, $HOME/.waiting has the restart job preappended
iam=`hostname`
. $HOME/.shepard.ini # source the initialization file
mode=NORMAL
if (test "$1" = "-r") then # restart entry submitted
# get the script which has the RESTART code (normally passed as $1)
scr=`awk 'BEGIN {n=0} $5=="RESTART" {print $1}' $HOME/.waiting`
# find and replace RESTART with last queue slot for corresponding script
awk ' BEGIN {
count = 1
} {
if ("'$scr'" != $1) print $0
else if ($5 != "RESTART") {
count++
printf "%s %s %s %s %s\n",$1,$2,$3,$4,$5
}
else printf "%s %s %s %s %s\n",$1,$2,$3,$4,count
} ' $HOME/.waiting > $HOME/tmp
mv $HOME/tmp $HOME/.waiting
elif (test "$1" != "-q") then # new job to submit
# append new job entry to $HOME/.waiting list
echo $1 $2 $3 $4 'NEW' >> $HOME/.waiting
# change NEW label to count of jobs having that script
# newest entry has the highest number/last to be executed
awk ' BEGIN {
count = 1
} {
if ("'$1'" != $1) print $0
else if ($5 != "NEW") {
count++
print $0
}
else printf "%s %s %s %s %s\n",$1,$2,$3,$4,count
} ' $HOME/.waiting > $HOME/tmp
mv $HOME/tmp $HOME/.waiting
cnt=`awk 'BEGIN{n=0}"'$1'" == $1 {n++} END {print n}' $HOME/.waiting`
if (test "$3" = "$iam") then
run_update -w $1 $2 cnt
else
rsh $3 run_update -w $1 $2 cnt
fi
else
mode=QUEUE # flag suppresses terminal response when in -q mode
fi
didit=NO # flag reports job starting status
# loop through scripts available on this host
# available scripts are in the environment variable SHEPARD_SCRIPTS
# The FIFO queue has a twist: differing job types are subqueued with
# limits for each found in .limits without maintaining separate queue
# structures. This method is easier to implement and permits a maximum
# load balance consisting of a mix of program types, tailored to ones
# needs. In this way, a number of program type 'a' exceeding the limit
# only runs the number set in .limits, while the others queue leaving
# processor time for program types 'b' and 'c'. The optimum load balance is
# determined by the system resource requirements of each program and
# ones needs for throughput; adjusting .limits allows changes on the fly.
for i in $SHEPARD_SCRIPTS
do
# count jobs actually running for each script, get associated job limit
if (test -f "$HOME/.running") then
rcnt=`awk 'BEGIN{n=0} "'$i'"==$1 {n++} END{print n}' $HOME/.running`
else
rcnt=0 # set rcnt to 0 if $HOME/.running is not present
fi
rlim=`awk '"'$iam'" == $1 && "'$i'" == $2 {print $3}' $HOME/.limits`
if (test -z "$rlim") then
rlim=1 # if no limit in $HOME/.limits, one job permitted
fi
# if more running jobs exceeds the limit, continue to next script
if (test "$rcnt" -ge "$rlim") then
continue
fi
# loop to next script if no jobs waiting with priority=1
script=`awk ' "'$i'" == $1 && $5 == "1" { print $1}' $HOME/.waiting`
if (test "$script" != "$i") then
continue
fi
# found one for current script, get the remaining values
dataset=`awk ' "'$i'" == $1 && $5 == "1" { print $2}' $HOME/.waiting`
origin=`awk ' "'$i'" == $1 && $5 == "1" { print $3}' $HOME/.waiting`
datadir=`awk ' "'$i'" == $1 && $5 == "1" { print $4}' $HOME/.waiting`
# put date/time in a single string format
set - `date`
day=$3 month=$2 year=$6 tm=$4
datetime=$day-$month-$year@$tm
# submit shepard_exec to the background, get its pid
wait 10 # shepard_queue does not wait for shepard_exec
nohup shepard_exec $script $dataset $origin $datadir >shepard_junk.log &
pid=$! # process identification number - unique for job
errflag=$?
# shepard_exec did not initiate, for some reason
# append the shepard_junk.log to shepard.err, alert the user
# the job is placed in .restart
if (test "$errflag" != "0") then
#notify the user
echo $script'('$dataset') did not start at '$datetime
echo ' return code '$errflag
echo '------ process error logfile contents -----'
cat $HOME/shepard_junk.log
echo '------ end of log from '$script'('$dataset') -----'
echo ' '; echo 'check the contents of shepard.err for details'
# update shepard.err
echo $script'('$dataset') did not start at '$datetime >tmp
echo '------ process error logfile contents -----' >>tmp
cat shepard_junk.log >>tmp
echo '------ end of log from '$script'('$dataset') -----' >>tmp
cat tmp >> $HOME/shepard.log; rm tmp
# remove from $HOME/.waiting, place in .restart
awk ' $1 == "'$script'" && $2 == "'$dataset'" && $5 == 1 {
print $0
}' $HOME/.waiting >> $HOME/.restart
awk '{
if ($1 == "'$i'" && $5 == 1) continue
if ($1 == "'$i'") {
$5 = $5 - 1
printf "%s %s %s %s %s\n",$1,$2,$3,$4,$5
}
}' $HOME/.waiting > $HOME/tmp
mv $HOME/tmp $HOME/.waiting
exit
fi
didit=YES
# append job specifics to $HOME/.running
echo $script $dataset $origin $datadir $pid >>$HOME/.running
# append job info to shepard.log
echo $script'('$dataset') started '$datetime >>$HOME/shepard.log
# remove running job from $HOME/.waiting, update priority
awk '{
if ($1 == "'$i'" && $5 == 1) next
if ($1 == "'$i'") {
$5 = $5 - 1
printf "%s %s %s %s %s\n",$1,$2,$3,$4,$5
}
}' $HOME/.waiting > $HOME/tmp
mv $HOME/tmp $HOME/.waiting
#update .current on origin machine
if (test "$iam" = "$origin") then
run_update -r $script $dataset $pid
else
rsh $origin run_update -r $script $dataset $pid
fi
# if job is successfully started, notify user
if (test "$didit" = "YES") then
echo ' '
echo $script'('$dataset') started on '$iam' at '$datetime
fi
done
if (test "$didit" = "NO") then
if (test "$mode" != "QUEUE") then
echo ' '; echo 'no jobs were submitted'
fi
fi
trap '' 1 2 3 15
<a name="025d_0011"><a name="025d_0011">
<a name="025d_0012">[LISTING FOUR]
<a name="025d_0012">
trap 'shepard -z $1 $2 $3 $$' 1 2 3 15
# shepard_exec - execution potion of shepard system -- B. E. Bauer, 1990
# passed args: 1: script, 2: dataset, 3: origin, 4: datadir
. $HOME/.shepard.ini # source initialization file
. $SHEPARD_DIR/$1.script # source application-specific definitions
# routine to move the required files into the execution environment
# sourcing vs separate shell obviates need to pass values
. $SHEPARD_DIR/$getdata_script
# run the program. Assumes here that stdin, stdout, and stderr are
# required (generally true for UNIX) during execution. All other data
# files were moved into the execution environment by $getdata_script
$exe < $2$inp 1> $2$log 2> $2$err
# source the script to return data back in its proper location
. $SHEPARD_DIR/$putdata_script
# clean up and update status files
shepard -z $1 $2 $3 $$ # pid of completing process returns as arg5
trap '' 1 2 3 15
<a name="025d_0013"><a name="025d_0013">
<a name="025d_0014">[LISTING FIVE]
<a name="025d_0014">
trap 'rm -f $HOME/tmp; exit' 1 2 3 15
# run_update - update component of shepard system -- B.E. Bauer 1990
# updates the .current file to reflect system activities
flag=$1 script=$2 dataset=$3 opt=$4
set - `date`
day=$3 month=$2 year=$6 tm=$4
datetime=$day-$month-$year@$tm
case $flag in
-w) stat='WAITING';;
-r) stat='RUNNING';;
-g) stat='RESTART';;
-b) stat='BUMPED';;
-k) stat='KILLED';;
-f) stat='DONE';;
-d) stat='DELETED';;
-t) stat='TERMINATED';;
esac
awk ' {
if ("'$script'" == $1 && "'$dataset'" == $2) {
printf "%s %s %s %s %s %s %s\n",$1,$2,$3,$4,$5,"'$datetime'","'$stat'"
}
else print $0
}' $HOME/.current >$HOME/tmp
mv $HOME/tmp $HOME/.current
trap '' 1 2 3 15
<a name="025d_0015"><a name="025d_0015">
<a name="025d_0016">[LISTING SIX]
<a name="025d_0016">
big bmin31lv Batchmin large (<2000 atoms)
big bmin31mv Batchmin medium (<1000 atoms)
big spartan ab initio electronic structure calculation
big amber biological structure simulation
big smapps Monte Carlo peptide simulation
big ampac semi-empirical electronic structure calculation
big dspace NMR distance -> structure
moe bmin31ls Batchmin large (<2000 atoms) use with caution!
moe bmin31ms Batchmin medium (<1000 atoms) default
moe bmin31ss Batchmin small (<250 atoms)
moe amber biological structure simulation
moe ampac semi-empirical electronic structure calculation
moe spartan ab initio electronic structure calculation
moe smapps Monte Carlo peptide simulation
larry bmin31ss Batchmin small (<250 atoms)
larry ampac semi-empirical electronic structure calculation
<a name="025d_0017"><a name="025d_0017">
<a name="025d_0018">[LISTING SEVEN]
<a name="025d_0018">
larry SGI IRIS 4D/25TG (B-1-3-09)
curly SGI IRIS 4D/120GTX (B-8-3-22; CADD room)
moe SGI IRIS 4D/240s (B-8-3-22; CADD room)
big CONVEX 220 (B-20-B)
<a name="025d_0019"><a name="025d_0019">
<a name="025d_001a">[LISTING EIGHT]
<a name="025d_001a">
-x execute (submit) a job
-m monitor remote host process status (ps command)
-p probe running job
-s status of running jobs on all platforms
-r running job list
-k kill job (with extreme prejudice)
-t terminate job gracefully
-g restart job
-l log file on remote machine (tail -30)
-b bump waiting job to next
-d delete a waiting job
-f finished job list on host machine
-e error log on host machine (tail -30)
-c change hosts
-w waiting job list on host machine
-a restartable job list on host machine
<a name="025d_001b"><a name="025d_001b">
<a name="025d_001c">[LISTING NINE]
<a name="025d_001c">
# Loads values for script, dataset, host, and datadir last used by run.
# This file is recreated at the end of run.
defscript=bmin31lv
defdata=bmintest3
defhost=big
defdir=pla2
<a name="025d_001d"><a name="025d_001d">
<a name="025d_001e">[LISTING TEN]
<a name="025d_001e">
big bmin31lv 3
big bmin31mv 1
big spartan 1
big amber 2
big smapps 1
big ampac 3
moe bmin31ms 2
moe bmin31ss 4
moe amber 2
moe smapps 1
moe ampac 4
moe spartan 1
larry bmin31ss 1
larry ampac 1
<a name="025d_001f"><a name="025d_001f">
<a name="025d_0020">[LISTING ELEVEN]
<a name="025d_0020">
# Definitions for runnable scripts, dataset network movement and directory for
# various files. The runnable scripts must be in agreement with contents of
# .runscripts. Behavior of network for the originating machine is set here.
# options for SHEPARD_NETWORK: server, nfs, remote
# SHEPARD_DIR is location of application-specific shepard scripts
# this file is sourced and executes directly in environment of script
case `hostname` in
larry|curly) # SGI IRIS workstation definitions
SHEPARD_SCRIPTS='bmin31ss ampac'
SHEPARD_NETWORK=server
SHEPARD_DIR=$HOME/shepard_dir;;
moe) # SGI IRIS-240 compute server definitions
SHEPARD_SCRIPTS='bmin31ss bmin31ms amber smapps ampac spartan'
SHEPARD_NETWORK=server
SHEPARD_DIR=$HOME/shepard_dir;;
big) # CONVEX specific definitions
SHEPARD_SCRIPTS='bmin31lv bmin31mv amber smapps ampac spartan dspace'
SHEPARD_NETWORK=server
SHEPARD_DIR=$HOME/shepard_dir;;
esac
<a name="025d_0021"><a name="025d_0021">
<a name="025d_0022">[LISTING TWELVE]
<a name="025d_0022">
# bmin31lv script for large vector (CONVEX) version of Batchmin v 3.1
exe=bmin31lv # the executable (in PATH)
inp=.com # extension for standard input
log=.log # extension for standard output
err=.err # extension for error output (channel 2)
getdata_script=bmin31lv.getdata # get the input datafiles
putdata_script=bmin31lv.putdata # put the output back
terminate_script=bmin31lv.terminate # application-specific shutdown
probe_script=bmin31lv.probe # conducts an application-specific probe
<a name="025d_0023"><a name="025d_0023">
<a name="025d_0024">[LISTING THIRTEEN]
<a name="025d_0024">
# bmin31lv.getdata: get)
case $SHEPARD_NETWORK in
server) cd $4;; # data stays put on host machine
remote) rsh $3 cat $4/$2.dat >$2.dat # move data. This is a kluge
rsh $3 cat $4/$2$inp >$2$inp;; # remote cat puts output on host
nfs) cp $4/$2.dat . # copy via remotely mounted nfs dir
cp $4/$2$inp . ;;
esac
<a name="025d_0025"><a name="025d_0025">
<a name="025d_0026">[LISTING FOURTEEN]
<a name="025d_0026">
# bmin31lv.putdata: put)
# all application-specific output files are moved, if necessary
case $SHEPARD_NETWORK in
server) cd $HOME;; # movement of files is not necessary
remote) rsh $3 cat ">"$4/$2.out <$2.out # another network kluge
rsh $3 cat ">"$4/$2$log <$2$log # remote cat with ">" writes
rsh $3 cat ">"$4/$2$err <$2$err;; # to remote. < read local.
nfs) cp $2.out $4/$2.out
cp $2$log $4/$2$log
cp $2$err $4/$2$err;;
esac
<a name="025d_0027"><a name="025d_0027">
<a name="025d_0028">[LISTING FIFTEEN]
<a name="025d_0028">
# sourced from shepard
# batchmin terminates when it finds dataset.stp in execution dir
case $SHEPARD_NETWORK in
server) echo 'help me, please help me' > $4/$2.stp;;
remote|nfs) echo 'help me, please help me' > $2.stp;;
esac
<a name="025d_0029"><a name="025d_0029">
<a name="025d_002a">[LISTING SIXTEEN]
<a name="025d_002a">
# Sourced from shepard. $dset=jobname, $ddir=directory, $log=logfile ext
# Script prints the last 30 lines of the log file from the selected job
case $SHEPARD_NETWORK in
server) tail -30 $ddir/$dset$log;;
remote|nfs) tail -30 $dset$log;;
esac
<a name="025d_002b"><a name="025d_002b">
<a name="025d_002c">[LISTING SEVENTEEN]
<a name="025d_002c">
/* lockon.c - creates lock file from argv[1] having no privelege
B. E. Bauer, 1990
*/
main (argc, argv)
int argc;
char *argv[];
{
int fp, locked;
locked = 0;
if (argc != 1) {
printf ("\nuseage: lockon lockfile\n");
exit (0);
}
if ((fp = creat(argv[1], 0)) < 0) ++locked;
else close(fp);
return (locked);
} | http://www.drdobbs.com/parallel/controlling-background-processes-under-u/184408456 | CC-MAIN-2015-35 | refinedweb | 7,611 | 61.87 |
Originally posted by: Peter O.
// -- start cutting here
POINT GetBitmapSize (HBITMAP h)
{
POINT p;
BITMAP o;
GetObject (h,sizeof(o),&o);
p.x=o.bmWidth;
p.y=o.bmHeight;
return (p);
}
void OpenBitmapForWork (HBITMAP b,tWorkBMP *w)
{
BITMAPINFO s;
HDC h=GetDC(NULL);
POINT v=GetBitmapSize(b);
CreateWorkingBitmap (v.x,v.y,w);
SetBMIHeader (&s,w->x,w->y);
GetDIBits (h,b,0,w->y,w->b,&s,DIB_RGB_COLORS);
ReleaseDC (NULL,h);
}
// -- stop cutting here
The homepage link is no longer valid.
ReplyReply
Originally posted by: yuval gross
does anybody know how to remove the antialiasing from a given bitmap??
If I mask out the background of a bitmap (say in white)
and remain with the foreground image which still has the antialiasing pixels - is there a way to get rid of these pixels??
does anybody know a function or an algorithm to do so?
Originally posted by: Macky
Hello,
I'm looking for a way to save and extract BITMAP Files in a database.
I don't know what I can do. May I use an ActiveX or my own code for date.
And how to speficy a member variable that support BITMAP.
I need your help.
Thanks a lot.
Macky
Originally posted by: Rambhavan Verma
Dear sir,.
Originally posted by: Espinoza
Hey Dude, what about OpenBitmapForWork ???Reply
Originally posted by: David King
If you use SetStretchBltMode(HALFTONE) before calling StretchBlt() then you will have the same image quality as Adobe Photoshop.Reply
Originally posted by: David Streeter
I can get the code to shrink bitmaps but when it enlarges them the bitmaps picture is left the same physical size as the original in a black bitmap! Anybody help?Reply
Originally posted by: objects
OpenBitmapForwork...
Originally posted by: Etienne Rossignon
Hi,
could you provide the OpenBitmapForWork which appears to miss in your article
Cheers | http://www.codeguru.com/comment/get/48156110/20/ | CC-MAIN-2015-40 | refinedweb | 305 | 57.06 |
The QNetworkRequest class holds a request to be sent with QNetworkAccessManager. More...
#include <QNetworkRequest>
This class was introduced in Qt 4.4..
Controls the caching mechanism of QNetworkAccessManager.
List of known header types that QNetworkRequest parses. Each known header is also represented in raw form with its full HTTP name.
See also header(), setHeader(), rawHeader(), and setRawHeader().
Indicates if an aspect of the request's loading mechanism has been manually overridden, e.g. by QtWebKit.
This enum was introduced or modified in Qt 4.7.
This enum lists the possible network request priorities.
This enum was introduced or modified in Qt 4.7.().
Return the priority of this request.
This function was introduced in Qt 4.7.
See also setPriority().(). URL this network request is referring to to be url.
Returns this network request's SSL configuration. By default, no SSL settings are specified.
See also setSslConfiguration().
Returns the URL this network request is referring to.
Returns false if this object is not the same as other.
See also operator==().
Creates a copy of other
Returns true if this object is the same as other (i.e., if they have the same URL, same headers and same meta-data settings).
See also operator!=(). | http://doc.qt.nokia.com/main-snapshot/qnetworkrequest.html | crawl-003 | refinedweb | 203 | 62.95 |
DataBinding
Databinding for the RadDataBar control involves the correlation between the business logic/data, and the visualization of the control.
The DataBinding involves the following three properties:
ItemsSource (a property of RadStackedDataBar and RadStacked100Databar): Gets or sets the data source used to generate the content of the databar control. Elements can be bound to data from a variety of data sources in the form of common language runtime (CLR) objects and XML - see the list of the supported data sources bellow.
Value (a property of RadDataBar): Expects a value which will be used to determine the size of the bar.
ValuePath (a property of RadStackedDataBar and RadStacked100DataBar): Expects the name of the property from the underlying datasource, which will determine the value of each bar in the stack.
You can bind the ItemsSource of RadStackedDataBar and RadStacked100DataBar to any class that implements the IEnumerable interface.
RadDataBar will automatically update its size if the value it is bound to changes. For this to happen the underlying data context must implement the INotifyPropertyChanged interface.
RadStackedDataBar and RadStacked100DataBar also provide full support for change notifications - data sources that implement the INotifyCollectionChanged, and underlying data items that implement INotifyPropertyChanged are properly tracked and automatically reflected by the UI.
You'll see the binding in action below.
Let's create a sample class with four properties - two integers, a collection of integers and a collection of another class.
Example 1: The Product class
public class Product { public int Value1 { get; set; } public int Value2 { get; set; } public IEnumerable<int> Ints { get; set; } public IEnumerable<Item> Items { get; set; } } public class Item { public double Val { get; set; } public string Name { get; set; } }
Public Class Product Public Property Value1() As Integer Public Property Value2() As Integer Public Property Ints() As IEnumerable(Of Integer) Public Property Items() As IEnumerable(Of Item) End Class Public Class Item Public Property Val() As Double Public Property Name() As String End Class
The next step is to set values for the properties in our class.
Example 2: Sample data
var items = new List<Item>() { new Item{ Val = 9, Name = "nine", }, new Item{ Val = 10, Name = "ten", }, new Item{ Val = 11, Name = "eleven", }, new Item{ Val = 20, Name = "twenty", }, new Item{ Val = 22, Name = "twenty two", }, new Item{ Val = 90, Name = "ninety", }, new Item{ Val = -9, Name = "-nine", }, new Item{ Val = -10, Name = "-ten", }, new Item{ Val = -11, Name = "-eleven", }, new Item{ Val = -20, Name = "-twenty", }, new Item{ Val = -100, Name = "-hundred", }, }; this.DataContext = new Product() { Value1 = 20, Value2 = 30, Ints = new List<int>() {5, 6, 7, 8, 9, }, Items = items };
Dim items = New List(Of Item)() From { New Item With {.Val = 9, .Name = "nine"}, New Item With {.Val = 10, .Name = "ten"}, New Item With {.Val = 11, .Name = "eleven"}, New Item With {.Val = 20, .Name = "twenty"}, New Item With {.Val = 22, .Name = "twenty two"}, New Item With {.Val = 90, .Name = "ninety"}, New Item With {.Val = -9, .Name = "-nine"}, New Item With {.Val = -10, .Name = "-ten"}, New Item With {.Val = -11, .Name = "-eleven"}, New Item With {.Val = -20, .Name = "-twenty"}, New Item With {.Val = -100, .Name = "-hundred"}} Dim TempProduct As Product = New Product() With {.Value1 = 20, .Value2 = 30, .Ints = New List(Of Integer)() From {5, 6, 7, 8, 9}, .Items = items} Me.DataContext = New Product() With {.Value1 = 20, .Value2 = 30, .Ints = New List(Of Integer)() From {5, 6, 7, 8, 9}, .Items
The only thing left to do is to create our databar(s) and bind them using the properties exposed for the purpose (as mentioned in the beginning of the article).
Example 3: Define RadDataBars
<telerik:RadDataBar <telerik:RadDataBar <telerik:RadStackedDataBar <telerik:RadStackedDataBar
Note that RadDataBar doesn't have an ItemsSource property since it is a single bar and needs a single value to work.
On the other hand RadStackedDataBar requires a collection of values - the number of items in the collection determines the number of bars that will be visualized in stack.
When bound to a list of business objects, you should set the name of the property from the business object that will provide the value for the bars. For the purpose RadStackedDataBar and RadStacked100Databar expose the ValuePath property.
When run this code will produce the following result. | https://docs.telerik.com/devtools/silverlight/controls/raddatabar/databinding | CC-MAIN-2018-43 | refinedweb | 697 | 60.35 |
Cover Image credit: The ProFroster. Fun fact: our team helped design and manufacture these!
Let me talk to you about cake. Hungry yet? Good. Hungry for knowledge?! Even better. Because I'm not talking about cake that you eat — I'm talking about Interview Cake.
Interview Cake is a website that I found recently that provides a ton of tech-interview-level questions and write-ups to help you get better at things like algorithms, time and space efficiency, explaining yourself, and thinking problems all the way through, even past the sticky edge cases. Is this an advertisement for them? No it is not. Am I going to continue to pepper you with rhetorical questions? Possibly. Mind your own business. Anyway, the purpose of this article is to write up a solution that I went through last week that initially looked like a snap and turned out to be way harder. Their final solution was, at least in my eyes, mindblasting. You read that right. I said
Let me lay out the problem for you.
The Problem
The problem is this:
You are given a list of integers in the range (0, n] (excluding 0, including n), that fill an array such that there are n + 1 numbers in the array. In other words, this array has one of each integer except for one unknown value that has a duplicate. The numbers in the array are not in any particular order.
Example: [4, 3, 7, 1, 5, 3, 2, 6] : 8 numbers, 1..7. The only duplicate is 3.
Your goal: Find the duplicate.
If you're feeling spunky, go ahead and give it a try. This is just the first portion of the problem, but it'll help you get your head in the game.
Ready with your solution? Here's mine, for reference.
def find_duplicate(nums) nums.select { |num| nums.count(num) > 1 }.first end
Alright, that's it. That's the whole thing, article over. Just kidding. I forgot to mention:
The Rest of the Problem
Here's where it gets interesting: the last two requirements of the problem.
- Your solution must be better than O(n^2) in time.
- Your solution must remain O(1) in space.
To make sure everybody is on the same page with me in terms of what that means, let me do a 30 second explanation of "Big-O Notation", which is what those O(n) and O(1) are called. If you're already comfortable with Big-O, go ahead and skip ahead.
Big-O Notation
"Big-O Notation" has to do with how efficient an algorithm or program is, as a function of the number of items used as inputs. Let me put it this way: Let's say you're given n numbers in your input list. If your solution requires you to loop through the whole list once (in the worst case, like if the number you're looking for is at the end of the list), then your solution is considered O(n). O(n) is also known as linear efficiency. This is because, if we double the size of the input to
2*n, your algorithm will have to process twice as many steps and most likely will be twice as slow. If we increase the size to
100*n, your algorithm will similarly do
100*n steps.
Now, what if you had a function that was O(n^2)? That would mean that your function looped through each of the
n inputs
n times (e.g. in a double for-loop). Thus, if, instead of
n inputs, you had
2*n inputs, your program would actually have to do
(2*n)^2 or
4*n steps! If your program had
100*n inputs, it would have to do
(100*n)^2 steps —
10000*n! Hopefully you can see that O(n) is quite a bit more efficient than O(n^2).
So what does O(1) mean? The 1 is a little misleading, because it simply stands for constant time, meaning that no matter how many inputs you have, your program will always take the same amount of steps, and thus, roughly the same amount of time. This is the Holy Grail of algorithms. This is the reason why it's so much faster to look up items from a Hash (or dict, or object, or whatever your language of choice calls it) than it is from a List or Array.
The last thing: Space Complexity. Space Complexity works the same as Time Complexity, except it has to do with how much computer memory you're using. Some examples might get things accross better.
O(1): When you have 10 inputs, your program keeps track of 3 variables. When you have 20,000 inputs, your program keeps track of 3 variables.
O(n): When you have 10 inputs, your program keeps track of two separate extra lists for a total of 20 slots. When you have 20,000 inputs, you need 40,000 extra slots to keep track of everything.
O(n^2): When you have 10 inputs, you need 100 extra slots. (Don't ask me why, you wrote the program. Seems like overkill). When you have 20,000 inputs, you end up needing 400,000,000 extra slots (and also a new computer because, congratulations, you killed this one).
Hopefully this super brief explanation helps. If you're still confused, Vaidehi Joshi does a better job than me of explaining it, with pictures! See also the whole BaseCS series. See also also the BaseCS Podcast.
ONWARD!
Rejecting Some Possible Solutions
Possibility 1: The Naive Solution (a.k.a. My Solution)
So what do those requirements really mean for us? Well, let's look back at my initial solution. For each item in the list, I go back through the list again and count the number of occurrences. My function is actually O(n^2) in Time (a double-for-loop!).
While you might argue that my solution is "good enough" for most cases (and I would agree), that's not what the requirements say we have to do.
Possibility 2: The Other Naive Solution (a.k.a. Keeping Track)
You could loop through just once, keeping track of the numbers you've already seen in a set. Once you see a number that's already in your set, you know that's the duplicate!
require 'set' def find_dupes(nums) history = Set.new nums.each do |num| return num if history.include?(num) history << num end return -1 # We should never reach this stage end
How'd we do? Well, we only ever loop through the whole list once at most, bringing us to O(n) Time Complexity. Right on! But we create the
history set that could contain (in the worst case) almost all
n of our input values. This looks like O(n) in Space as well, which means that we fail the second requirement. 💩!
Possibility 3: The Sorting Solution (a.k.a. The Slightly Tricky Solution)
What about doing a sort? Since sorting can be done in O(nlogn) time, which is better than O(n^2), we might have a chance. We could sort our numbers, and then loop through them once while only keeping track of the last number that we saw. If we see the same number twice, it's a duplicate.
def find_dupes(nums) nums.sort! previous = 0 nums.each do |num| return num if num == previous previous = num end return -1 end
This gets us O(1) in Space and O(nlogn) (ish) in Time. One problem with this. If we don't create a new array to put our sorted numbers in, we're destroying/modifying the order of the list that gets passed into us, which isn't good. If we create a new array to put our sorted numbers in, we jump up to O(n) in Space, which is a fail. Hmmm… There's a better way — trust me.
The Better Way
OK. Here's the solution they provided. It has some CS concepts in it, but don't worry. I'll walk you through. I don't think I would have ever thought of it in a million years, but I guess that's why we practice, right?
A Linked List (Sort Of)
OK. Do me a favor and imagine the input list as a series of connected nodes: a Linked List, if you will. Each slot in the array has its own index and the number that points to the index of another node in the list. The original problem on Interview Cake bases things on a 1-base array, so that's how I'll explain things too. Thus, we end up with something like this:
Study that list for a minute. Get a piece of paper and pencil and try some more. [3, 1, 2, 4, 1]. [8, 6, 4, 2, 1, 2, 5, 3, 7]. [2, 1, 1, 3]. What do those look like? Do you start to see patterns? I mean, besides the pattern that I suck at freehand diagrams?
Here's some things to note:
- The last node never has any arrows pointing at it. That's because it's at position
n+1, and the maximum value in the list is
n. If we're thinking of our array like a kind of linked list, the last node would be a good candidate for the head.
- Because there is always a duplicate, there is always a loop somewhere in the list. At some point, every diagram becomes cyclic.
- Because there is always a cycle, there is always a node that has two arrows pointing at it.
- This node with two arrows pointing at it is always the first node in the cycle.
- The index (1-based) of this two-arrow node is always the duplicate value.
So how does that help us? Well, if we can find a way to figure out where the start of the cycle is, we can return the index of that node as our result.
Finding the Length of the Cycle
To find the start of the cycle, we'll need its length. Trust me on this, and it'll make sense in a little bit. That is actually not as hard as you might think. In order to get the cycle's length, we need a sure-fire way to get into the cycle. Well, we only have a certain number of nodes, right? So, if we just start stepping, we might end up in the cycle at some point, but after
n+1 steps, we're guaranteed to be somewhere within the cycle. Because, even if the cycle is the size of the entire list like this:
You still can only go to each of the nodes once before you create a cycle. I'll try to show my solution being built as we go. If you're somebody who has to see things written out in code, hopefully this will help you.
class DuplicateFinder def initialize(nums) @nums = nums end def step(current) # Convenience method to move to next node @nums[current - 1] # -1 because of 1-based counting end def find_a_number_in_the_cycle next_step = @nums.last @nums.length.times do next_step = step(next_step) end next_step # Returns the number at the index we're on end end
OK. So now we're in the cycle, so what do we do? Well, within the cycle, the numbers are all unique! So all we have to do is remember the node we're at initially, and start stepping and counting. Once we see the same number again, we'll know that we've travelled the loop exactly one time and we'll know how long the loop is!
class DuplicateFinder # ... def length_of_cycle stop_num = find_a_number_in_the_cycle next_num = step(stop_num) steps = 1 until next_num == stop_num next_num = step(next_num) steps += 1 end steps end
The Yardstick Method
Now we're at the real amazing part. It has to do with something that could be called the Yardstick Method (or, I suppose, the Meterstick Method, if you must 😉). Let's go back to the head of the list and start over. For example. Let's say we have the list
[4, 1, 2, 3, 4, 5, 6, 7, 8, 9]. If you draw it out, the cycle is 4 nodes long. So, what we need to do is imagine we have a stick that is 4 nodes long, just like the cycle. We can translate this into code by using two pointers: one at the head of the stick and one at the tail.
Now we step our whole stick forward one node, moving both the head and the tail, so the stick stays the same length.
What happens if we continue this process?
Both the head and the tail of the stick are pointing at the same number! And it's the number with two arrows at the beginning of the cycle! AND what index (1-based, like our linked list) do they meet at? Index 4! AAAAND what is the duplicate number in our list? 4!
For completeness, how does this look in code?
class DuplicateFinder def initialize(nums) @nums = nums end def step(current) @nums[current - 1] end def find_a_number_in_the_cycle next_step = @nums.last @nums.length.times do next_step = step(next_step) end next_step end def length_of_cycle stop_num = find_a_number_in_the_cycle next_num = step(stop_num) steps = 1 until next_num == stop_num next_num = step(next_num) steps += 1 end steps end def duplicate stick = length_of_cycle head = @nums.last tail = @nums.last stick.times { head = step(head) } until head == tail head = step(head) tail = step(tail) end # When head and tail point to the same number # then on the next step, they'll be on the same node # This current same number means head and tail both = the duplicate! head end end
Evaluation
So, how'd we do?
Space: We generally keep track of the next node to step to, and a few other variables, but I think we can safely say that our space usage is ~O(1). We don't ever save a copy of our array anywhere.
Time: We loop through once to find the length of the cycle, and then we loop again to find the duplicate. This gets us to ~O(n) since we always loop through the array the same number of times regardless of input length and it's only a matter of how long the array is.
VICTORY. This was a really tricky one. If it didn't make sense, it's not your fault. I had to read through it a few times, do the problem a few times, and even write this blog post before I fully understood how it worked. Feel free to reach out with questions if I can help clarify anything for you. And again, go check out Interview Cake for more practice on puzzles like these (although they're not all quite as tricky as this one is).
Originally posted on
assert_not magic?
Discussion
Nice, creative solution. But since we know that range is 1..n what about
array_sum = [1, 2, 3, 4, 1].sum
consecutive_sum = n∗(n+1)/2
duplicate = array_sum - consecutive_sum
Oh shoot! I can’t believe I didn’t think of that. You’re totally right. Nice one! 👍🏻 | https://practicaldev-herokuapp-com.global.ssl.fastly.net/rpalo/cake-and-duplicates-8gm | CC-MAIN-2020-40 | refinedweb | 2,555 | 82.54 |
In one of the previous article, we learned how to generate and return the PDF file in response. This was the right choice if you want to download the PDF file. But if you want to display PDF file inside the browser window then we need to make use of FileResponse.
Remember that browsers won't display PDF if proper plugins are not available.
Let's say you want to display the payslip of employees. Below is the directory structure where we are going to store the payslips.
-project |-media | |-payslips | | |-2019 | | | |-january | | | |-feburary | | | | |-6754599.pdf | | | | |-6754600.pdf
All the media files are stored in the
media folder in the project root. We have further created more folders to segregate documents. Salary slips are stored year and month wise. Salary slip file name is [employee id].[extension], pdf in this case.
Now in view responsible to display payslip, write below code.
@login_required
def payslip_view(request, employee):
data = dict()
data["employee"] = employee
if "GET" == request.method:
return render(request, "appname/payslip.html", data)
# else for post call, procced
post_data = request.POST.copy()
year = post_data.get("year", None)
month = post_data.get("month", None)
if not year or not month:
messages.error(request, "Please select year and month.")
return HttpResponseRedirect(reverse("appname:payslip", args=(employee,)))
try:
filename = employee + ".pdf"
filepath = os.path.join(settings.MEDIA_ROOT, "payslips", year, month, filename)
print(filepath)
return FileResponse(open(filepath, 'rb'), content_type='application/pdf')
except FileNotFoundError:
messages.error(request, "Payslip of Employee with Id " + employee + " doesn't exists for " + month + " " + year)
return HttpResponseRedirect(reverse("appname:payslip", args=(employee,)))
Import required classes/modules.
from django.contrib import messages
from django.http import HttpResponseRedirect, Http404, FileResponse
from django.shortcuts import render
from django.urls import reverse
from django.contrib.auth.decorators import login_required import os from django.conf import settings
You need to create another view which will display the HTML page with drop downs to select year and month for the logged in employee. Once the year and month are selected and form is submitted, post request is handled by the above view and payslip is displayed in the browser window.
Host your Django project for free. | https://pythoncircle.com/post/682/how-to-display-pdf-in-browser-in-django-instead-of-downloading-it/ | CC-MAIN-2022-05 | refinedweb | 358 | 61.63 |
Programming Reference/Librarys
Question & Answer
Q&A is closed
Q&A is closed
copy text from a text mode window in memory.
stores the text content of the rectangular area of the screen, which is defined by left, top, right and bottom, and also stores it in the storage area pointed to by dst. all coordinates are absolute screen coordinates, not window-based. The top left corner has coordinates (1,1). sequentially reads the contents of the rectangle from the left to right and from top to bottom in the memory. each screen position is represented by 2 bytes in memory: The first byte contains the characters present in the cell, and the second byte contains the graphic attribute of the cell. The memory requirement for a rectangle with a width of w and a height of h columns goals is defined as follows:
bytes = (h line) x (w columns) x 2
returns returns 1 if the operation was successful else 0
#include <conio.h> int main(void) { int i; char buffer[79]; cprintf("This will be stored in the buffer"\n); cprintf("This also"\n); gettext(1, 1, 80, 25, buffer); gotoxy(1, 25); clrscr(); gotoxy(1, 25); cprintf("hit some key to restore"); getch(); puttext(1, 1, 80, 25, buffer); gotoxy(1, 25); return 0; }
This will be stored in the buffer This also hit some key to restore
This will be stored in the buffer This also ... | https://code-reference.com/c/conio.h/gettext | CC-MAIN-2018-09 | refinedweb | 240 | 60.18 |
User:Sj/2008/Week 28
From OLPC
people to discuss and represent global community...
beauty
games
- GROW (eyemaze)
- for mika : (note his FAQ. needs specific thoughtful ja request. also: send xo!)
-
- EDaughter (et al)
flash
- sambakza (amalloc)
- o.n.e (n201)
cultural centers
- gyeonggi-do cultural center (sambakza)
- wdl (demo library interface)
- mit (simile project; disbanding!!)
sites
- flickr
- sg site
- jayisgames
gear
- scottevest
books
- alchemist
film
- chaplin
- qatsi, anima mundi
music
- peter and wolf; music-list
- jams, spec. artists
our real culture. total historical pop : 12B since 1900 (100+B since 8000 BC) Things that have touched 1B/100M/(50) people (+/*/-). ++ : 10B is roughly 80% saturation this past century. -- : 10M is roughly 1/4% current pop saturation & starting with English language. Note separately: Chinese, Hindi, French, Spanish, Arabic. Literature: ++ Bible (5T copies in 200 yrs? ~200 copies per person? extreme, bad stat. ) : plus 10^6 derivatives, allegories, &c + Shakespeare (+ many individual plays) * any other playwrights? 10 major elements, 10^4 derivatives + Potterdom: 400M vols + fanfic and extensions; 100M? dvd sales; 100M+ film sales. * 10^2 major derivatives Reference: + Wikipedia (over 1B served) * EB (? sold? 120k sets in 1990, 50k in 1994. Say 100M touched by libraries. Online... not much there there) Games: * The Sims (100M by 2008 over 8 yrs; x 1.5?) * GTA (~100M copies as of mid-2008; x 1.5?) - Simgirls (50M views/uses. Easily the most popular on newgrounds ?!), based on DNA2 characters. : abandoned by creator (99megastore.com), by far the least elegant of the top 20. 100M total views/uses : spawned 2+ major copycats. vaguely pursued by fan coders @ -- Dragracer1-3 : 25M x2 editions in all? life-relevant sim car flash, dealerships should use. see also CreateARide. -- Guitar Hero (15M units. redoctane/harmonix --> neversoft) * Warcraft (x3 + WOW : 50M?) - WOW (10M active subscribers, 60% global MMORPG base; avg 10+ hrs/week, 1000 hrs invested?! x2 culture, x5 impact) -- Alien Hominid (20M via newgrounds x-arcade) Game groups - Nickelodeon (50M through mid-2008) - Rare (rareware.com : 100M units 1985-2008; Sesame 123, viva pin~ata) Game platforms: * PS (PS2: 100m? PS3: 15m) *+ Nintendo (orig: 10m? GameCube: 15m+) * GB orig & color: 100m (2006) * GBA: 80m -- Wii: 20m+, growing fast - Xbox (360: 20m promised in 08? orig: 50m?) Tools: + music: 1B+ people each year * 1B pos sales in 2006 (avg 10 per person?) * Apple iPod (100M+ units, 4/2007) + phones: 1B units/yr? in 2009 + laptops: Software platforms: * WinXP (100M++? no stats found) * WinVista (100M by 08) Food: ++ Soda. Coke, Pepsi (1B a day?? 5B) ++ Hamburgers. McD's, BKing? O(10B)
levels of sharing
1. public index : existence < creation metadata < contact & download/access info 2. public access : automatic purchase < viewing < (ft) searching < downloading 3. public forums : reproducable copies < sharing with audiences (limited/edu < nc-nd < nd) 4. accessibility : reformatting < localization 5. public reuse : recombination < alteration (nc-sa < nc) 6. public resale : by-nd < by-sa < by 7. public domain : public culture. no restrictions.
levels of publicity
1. mention within the work itself : formulaic notice > explanation 2. mention in a forum or publication : private > public > forum/publication of record 3. listing in a directory or repository : private > public > repository of record 4. periodic announcement or outreach : to specialists > via mass media 5. social meme : topical > general | new word coined
thoughts on the smell of death:
we are many orders of magnitude below efficient use/finding/sharing of knowledge. so many ideas, imperfectly carried out, can have great effect. So many people take an idea that is not totally useless, carry it out long enough to have some effect, apply their personal brand and call it innovation. Along with this branding often comes an assumption of inherent value of related ideas, which precludes pulling the best from dozens of experiments and leads the insights of each successful project to carry the dead weight of the other 90%. Combined with the notion of ownership of the original idea, you have lots of vaguely good ideas which can't be readily refined and combined.
So you have groups such as the HC with a secret project to develop a new interface to the books and information in archives; the LOC with a non-public domain interface to the World Digital Library; the Harvard Open Collections project which prevents their digital collections from being downloaded, and so on -- each looking for the payoff or royalties that will confirm to their satisfaction that they are doing valuable and sustainable work.
24h list
- CP - emails to the 2 30+ requests. one waits on kq? hilaire does not. see minutes from last meeting.
- check db, update requests, send early morning to christine.
- prep for 11:30 15-min meeting, send reminder.
- draft outreach email to var groups: distros, artists, creators
- revisit tactlist : vip's, prolificists, polymaths
- CT - draft email to N on state of partners; how some (ICDL, WDL!) want first to recoup their investments,
whereas others less directly on our course (FHistory, Berkman) simply want to help however they can
- Community - update job descs from draft to K, w/Wade's ideas. call Wade early... or tonight?
- draft invite to community list - to organizers of all stripes, for active disc about how to be productive
- list fellow communities to draw in (each may have an organizer; berk, flick, &c)
- first-cut stats of members -- # of editors, posters, patchers; and those just w/accounts
- " " for chapters -- # of chaps w/boards, overview page, contact info & reqs.
- Broadcasts - draft Week, xoxo one-page w/FA blurb
- draft email invite to article-OTD list - with details from one great article a day from our wiki
- (include a quote and a term)
- weekly xoxo meta-section on comm & media - blogs, photos, video, talks, press
- Lists : talk to Henry about new OTD list, general list reorg
- draft mail to all list owners noting upcoming list changes, update specifications suggestion for merges/renames
- have section for weekly xoxo notes by list and list-grp
- Other infrastructure
- note need for focus on wikis, lists, and more
- - rt security: make sure newbies only see a fixed set of queues
- - teamw security: restore namespace protection
- - olpcw semwiki : for femslade
- ask for weekly [public] tech/list/infra updates for xoxo
- RfV : mailing list help; OTD editor; xoxo copyeditor & translators; stats compiler; wiki categorizer(s); rt queues (cont, vol)
- Offers/email - first-cut stats, status
- curators/coords (C&C) update w/tact, freshness
- post version of 2007 spreadsheet w/ 4 numbers
Other things
hjl
nnn | http://wiki.laptop.org/go/User:Sj/2008/Week_28 | CC-MAIN-2016-26 | refinedweb | 1,067 | 57.77 |
Annotated notes from Lecture 21
GOALS:
TUTORIAL TODAY:
Load up this ipython notebook and change the values of
m and
b in the "Fitting Lines to Data" section,
A and
B in "Curve Fitting", and then again
a and
b in "Fitting a Power Law"
# You can ignore this, it's just for aesthetic purposes matplotlib.rcParams['figure.figsize'] = (8,5) rcParams['savefig.dpi'] = 100
# These import commands set up the environment so we have access to numpy and pylab functions import numpy as np import pylab as pl # Data Fitting # First, we'll generate some fake data to use x = np.linspace(0,10,50) # 50 x points from 0 to 10 # Remember, you can look at the help for linspace too: # help(np.linspace)
# y = m x + b y = 2.5 * x + 1.2
# let's plot that pl.clf() pl.plot(x,y)
[<matplotlib.lines.Line2D at 0x105959150>]
# looks like a simple line. But we want to see the individual data points pl.plot(x,y,marker='s')
[<matplotlib.lines.Line2D at 0x1031a3290>]
# We need to add noise first noise = pl.randn(y.size) # Like IDL, python has a 'randn' function that is centered at 0 with a standard deviation of 1. # IDL's 'randomu' is 'pl.rand' instead # What's y.size? print y.size print len(y)
50 50
y.size is the number of elements in y, just like
len(y) or, in IDL,
n_elements(y)
# We can add arrays in python just like in IDL noisy_flux = y + noise # We'll plot it too, but this time without any lines # between the points, and we'll use black dots # ('k' is a shortcut for 'black', '.' means 'point') pl.clf() # clear the figure pl.plot(x,noisy_flux,'k.') # We need labels, of course pl.xlabel("Time") pl.ylabel("Flux")
<matplotlib.text.Text at 0x1059705d0>
Now we're onto the fitting stage. We're going to fit a function of the form $$y = m*x + b$$ which is the same as $$f(x) = p[1]*x + p[0]$$ to the data. This is called "linear regression", but it is also a special case of a more general concept: this is a first-order polynomial. "First Order" means that the highest exponent of x in the equation is 1
# We'll use polyfit to find the values of the coefficients. The third # parameter is the "order" p = np.polyfit(x,noisy_flux,1) # help(polyfit) if you want to find out more
# print our fit parameters. They are not exact because there's noise in the data! # note that this is an array! print p print type(p) # you can ask python to tell you what type a variable is
[ 2.59289715 0.71443764] <type 'numpy.ndarray'>
# Great! We've got our fit. Let's overplot the data and the fit now pl.clf() # clear the figure pl.plot(x,noisy_flux,'k.') # repeated from above pl.plot(x,p[0]*x+p[1],'r-') # A red solid line pl.xlabel("Time") # labels again pl.ylabel("Flux")
<matplotlib.text.Text at 0x107b2ca50>
# Cool, but there's another (better) way to do this. We'll use the polyval # function instead of writing out the m x + b equation ourselves pl.clf() # clear the figure pl.plot(x,noisy_flux,'k.') # repeated from above pl.plot(x,np.polyval(p,x),'r-') # A red solid line pl.xlabel("Time") # labels again pl.ylabel("Flux")
<matplotlib.text.Text at 0x105978dd0>
# help(polyval) if you want to find out more
Let's do the same thing with a noisier data set. I'm going to leave out most of the comments this time.
noisy_flux = y+noise*10 p = polyfit(x,noisy_flux,1) print p
[ 3.4289715 -3.65562359]
# plot it pl.clf() # clear the figure pl.plot(x,noisy_flux,'k.') # repeated from above7617750>
Despite the noisy data, our fit is still pretty good! One last plotting trick, then we'll move on.
pl.clf() # clear the figure pl.errorbar(x,noisy_flux,yerr=10,marker='.',color='k',linestyle='none') # errorbar requires some extras to look nice36977d0>
# this time we want our "independent variable" to be in radians x = np.linspace(0,2*np.pi,50) y = np.sin(x) pl.clf() pl.plot(x,y)
[<matplotlib.lines.Line2D at 0x105f919d0>]
# We'll make it noisy again noise = pl.randn(y.size) noisy_flux = y + noise pl.plot(x,noisy_flux,'k.') # no clear this time
[<matplotlib.lines.Line2D at 0x107b1cbd0>]
That looks like kind of a mess. Let's see how well we can fit it. The function we're trying to fit has the form: $$f(x) = A * sin(x - B)$$ where $A$ is a "scale" parameter and $B$ is the side-to-side offset (or the "delay" if the x-axis is time). For our data, they are $A=1$ and $B=0$ respectively, because we made $y=sin(x)$
# curve_fit is the function we need for this, but it's in another package called scipy from scipy.optimize import curve_fit # we need to know what it does: help`` Parameters ---------- f : callable The model function, f(x, ...). It must take the independent variable as the first argument and the parameters to fit as separate remaining arguments. xdata : An N-length sequence or an (k,N)-shaped array for functions with k predictors. The independent variable where the data is measured. ydata : N-length sequence The dependent data --- nominally f(xdata, ...) p0 : None, scalar, or M-length sequence Initial guess for the parameters. If None, then the initial values will all be 1 (if the number of parameters for the function can be determined using introspection, otherwise a ValueError is raised). sigma : None or N-length sequence If not None, it represents the standard-deviation of ydata. This vector, if given, will be used as weights in the least-squares problem.. See Also -------- leastsq Notes ----- The algorithm uses the Levenburg-Marquardt algorithm through `leastsq`. Additional keyword arguments are passed directly to that algorithm. Examples -------- >>> import numpy as np >>> from scipy.optimize import curve_fit >>>)
Look at the returns:.
So the first set of returns is the "best-fit parameters", while the second set is the "covariance matrix"
def sinfunc(x,a,b): return a*np.sin(x-b) fitpars, covmat = curve_fit(sinfunc,x,noisy_flux) # The diagonals of the covariance matrix are variances # variance = standard deviation squared, so we'll take the square roots to get the standard devations! # You can get the diagonals of a 2D array easily: variances = covmat.diagonal() std_devs = np.sqrt(variances) print fitpars,std_devs
[ 1.24208994 0.15896795] [ 0.2237797 0.17677306]
# Let's plot our best fit, see how well we did # These two lines are equivalent: pl.plot(x, sinfunc(x, fitpars[0], fitpars[1]), 'r-') pl.plot(x, sinfunc(x, *fitpars), 'r-')
[<matplotlib.lines.Line2D at 0x105978110>]
Again, this is pretty good despite the noisiness.
Power laws occur all the time in physis, so it's a good idea to learn how to use them.
What's a power law? Any function of the form: $$f(t) = a t^b$$ where $x$ is your independent variable, $a$ is a scale parameter, and $b$ is the exponent (the power).
When fitting power laws, it's very useful to take advantage of the fact that "a power law is linear in log-space". That means, if you take the log of both sides of the equation (which is allowed) and change variables, you get a linear equation! $$\ln(f(t)) = \ln(a t^b) = \ln(a) + b \ln(t)$$ We'll use the substitutions $y=\ln(f(t))$, $A=\ln(a)$, and $x=\ln(t)$, so that $$y=a+bx$$ which looks just like our linear equation from before (albeit with different letters for the fit parameters).
We'll now go through the same fitting exercise as before, but using powerlaws instead of lines.
t = np.linspace(0.1,10) a = 1.5 b = 2.5 z = a*t**b
pl.clf() pl.plot(t,z)
[<matplotlib.lines.Line2D at 0x1077799d0>]
# Change the variables # np.log is the natural log y = np.log(z) x = np.log(t) pl.clf() pl.plot(x,y) pl.ylabel("log(z)") pl.xlabel("log(t)")
<matplotlib.text.Text at 0x10779f190>
It's a straight line. Now, for our "fake data", we'll add the noise before transforming from "linear" to "log" space
noisy_z = z + pl.randn(z.size)*10 pl.clf() pl.plot(t,z) pl.plot(t,noisy_z,'k.')
[<matplotlib.lines.Line2D at 0x107785c10>]
noisy_y = np.log(noisy_z) pl.clf() pl.plot(x,y) pl.plot(x,noisy_y,'k.') pl.ylabel("log(z)") pl.xlabel("log(t)")
<matplotlib.text.Text at 0x105a9aed0>
Note how different this looks from the "noisy line" we plotted earlier. Power laws are much more sensitive to noise! In fact, there are some data points that don't even show up on this plot because you can't take the log of a negative number. Any points where the random noise was negative enough that the curve dropped below zero ended up being "NAN", or "Not a Number". Luckily, our plotter knows to ignore those numbers, but
polyfit doesnt.
print noisy_y
[ 2.64567168 1.77226366 nan 1.49412348 nan 1.28855427 0.58257979 -0.50719229 1.84461177 2.72918637 nan -1.02747374 -0.65048639 3.4827123 2.60910913 3.48086587 3.84495668 3.90751514 4.10072678 3.76322421 4.06432005 4.23511474 4.26996586 4.25153639 4.4608377 4.5945862 4.66004888 4.8084364 4.81659305 4.97216304 5.05915226 5.02661678 5.05308181 5.26753675 5.23242563 5.36407125 5.41827503 5.486903 5.50263105 5.59005234 5.6588601 5.7546482 5.77382726 5.82299095 5.92653466 5.93264584 5.99879722 6.07711596 6.13466015 6.12248799]
# try to polyfit a line pars = np.polyfit(x,noisy_y,1) print pars
[ nan nan]
In order to get around this problem, we need to mask the data. That means we have to tell the code to ignore all the data points where
noisy_y is
nan.
My favorite way to do this is to take advantage of a curious fact: $1=1$, but
nan!=
nan
print 1 == 1 print np.nan == np.nan
True False
So if we find all the places were
noisy_y !=
noisy_y, we can get rid of them. Or we can just use the places where
noisy_y equals itself.
OK = noisy_y == noisy_y print OK
[ True True False True False True True True True True False True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True]
This
OK array is a "boolean mask". We can use it as an "index array", which is pretty neat.
print "There are %i OK values" % (OK.sum()) masked_noisy_y = noisy_y[OK] masked_x = x[OK] print "masked_noisy_y has length",len(masked_noisy_y)
There are 47 OK values masked_noisy_y has length 47
# now polyfit again pars = np.polyfit(masked_x,masked_noisy_y,1) print pars
[ 1.50239281 1.9907672 ]
# cool, it worked. But the fit looks a little weird! fitted_y = polyval(pars,x) pl.plot(x, fitted_y, 'r--')
[<matplotlib.lines.Line2D at 0x10368e1d0>]
The noise seems to have affected our fit.
# Convert bag to linear-space to see what it "really" looks like fitted_z = np.exp(fitted_y) pl.clf() pl.plot(t,z) pl.plot(t,noisy_z,'k.') pl.plot(t,fitted_z,'r--') pl.xlabel('t') pl.ylabel('z')
<matplotlib.text.Text at 0x10761fb50>
That's pretty bad. A "least-squares" approach, as with
curve_fit, is probably going to be the better choice. However, in the absence of noise (i.e., on your homework), this approach should work
def powerlaw(x,a,b): return a*(x**b) pars,covar = curve_fit(powerlaw,t,noisy_z) pl.clf() pl.plot(t,z) pl.plot(t,noisy_z,'k.') pl.plot(t,powerlaw(t,*pars),'r--') pl.xlabel('t') pl.ylabel('z')
<matplotlib.text.Text at 0x107451e10>
We need to cover a few syntactic things comparing IDL and python.
In IDL, if you wanted the maximum value in an array, you would do:
maxval = max(array, location_of_max)
In python, it's more straightforward:
location_of_max = array.argmax()
or
location_of_max = np.argmax(array)
Now, say we want to determine the location of the maximum of a number of different functions. The functions we'll use are:
sin(x)
sin$^2$
(x)
sin$^3$
(x)
sin(x)cos(x)
We'll define these functions, then loop over them.
# sin(x) is already defined def sin2x(x): """ sin^2 of x """ return np.sin(x)**2 def sin3x(x): """ sin^3 of x """ return np.sin(x)**3 def sincos(x): """ sin(x)*cos(x) """ return np.sin(x)*np.cos(x) list_of_functions = [np.sin, sin2x, sin3x, sincos]
# we want 0-2pi for these functions t = np.linspace(0,2*np.pi) # this is the cool part: we can make a variable function for fun in list_of_functions: # the functions know their own names (in a "secret hidden variable" called __name__) print "The maximum of ",fun.__name__," is ", fun(t).max()
The maximum of sin is 0.999486216201 The maximum of sin2x is 0.998972696375 The maximum of sin3x is 0.998459440388 The maximum of sincos is 0.4997431081
# OK, but we wanted the location of the maximum.... for fun in list_of_functions: print "The location of the maximum of ",fun.__name__," is ", fun(t).argmax()
The location of the maximum of sin is 12 The location of the maximum of sin2x is 12 The location of the maximum of sin3x is 12 The location of the maximum of sincos is 6
# well, that's not QUITE what we want, but it's close # We want to know the value of t, not the index! for fun in list_of_functions: print "The location of the maximum of ",fun.__name__," is ", t[fun(t).argmax()]
The location of the maximum of sin is 1.5387392589 The location of the maximum of sin2x is 1.5387392589 The location of the maximum of sin3x is 1.5387392589 The location of the maximum of sincos is 0.769369629451
# Finally, what if we want to store all that in an array? # Well, here's a cool trick: you can sort of invert the for loop # This is called a "list comprehension": maxlocs = [ t[fun(t).argmax()] for fun in list_of_functions ] print maxlocs
[1.5387392589011231, 1.5387392589011231, 1.5387392589011231, 0.76936962945056153]
# Confused? OK. Try this one: print range(6) print [ii**2 for ii in range(6)]
[0, 1, 2, 3, 4, 5] [0, 1, 4, 9, 16, 25]
The next big programming topic is called recursion.
The next little programming topic is called recursion.
For better or worse, you must visit the wiki page on recursion
Recursion is when a function calls itself. But, a recursive function must have an "end condition" to avoid an infinite loop. If you try to make an infinite loop, you will get a "stack overflow" (python will give you an error).
def fail(x): """ an infinite recursion. Will fail """ return fail(x) # WARNING: this will definitely fail, but it may take a long time! # print fail(1)
Recursion is a useful mathematical tool. There are some problems that are best solved via recursion. The most commonly used example is the fibonacci sequence:
0 1 1 2 3 5 8 13 21 ....
this sequence is defined by the recursive relation
$$F_n = F_{n-1} + F_{n-2}$$
or $$f(n) = f(n-1) + f(n-2)$$
It has the base conditions: $$f(0) = 0$$ $$f(1) = 1$$
This one is pretty easy to define in code. But I'll leave it as an exercise.
The following code shows a hierarchy of what will happen if you call
fibonacci(5). Don't worry about trying to understand the 'digraph' code, it's just a graph visualization tool.
%install_ext
Installed hierarchymagic.py. To use it, type: %load_ext hierarchymagic
%load_ext hierarchymagic
%%dot --format svg -- digraph G { f5 [label="f(5)"]; Lf1 [label="f(1)"]; LLf0 [label="f(0)"]; Lf2 [label="f(2)"]; Lf3 [label="f(3)"]; RRf1 [label="f(1)"]; RRMf1 [label="f(1)"]; RRf0 [label="f(0)"]; LLf1 [label="f(1)"]; RMf0 [label="f(0)"]; RMf1 [label="f(1)"]; Rf2 [label="f(2)"]; RMf2 [label="f(2)"]; Rf3 [label="f(3)"]; Rf4 [label="f(4)"]; f5->Lf3; f5->Rf4; Lf3->Lf2; Lf3->Lf1; Rf4->Rf3; Rf4->Rf2; Rf2->RRf1; Rf2->RRf0; Lf2->LLf1; Lf2->LLf0; Rf3->RMf2; Rf3->RMf1; RMf2->RMf0; RMf2->RRMf1; }
# EXERCISE: Write a recursive Fibonacci function! def fibonacci(n): return # put your code here!
# EXERCISE: Write a recursive factorial function # Recall: factorial(x) = factorial(x-1) * x # factorial(1) = 1 def factorial(x): return
# This is the test for the fibonacci code. # Run this after you've written your fibonnacci sequence code # it will fail if your code is wrong! for ii,ff in zip(range(9),[0,1,1,2,3,5,8,13,21]): assert fibonacci(ii) == ff print "Success!"
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-47-02b5a0d0ea36> in <module>() 3 # it will fail if your code is wrong! 4 for ii,ff in zip(range(9),[0,1,1,2,3,5,8,13,21]): ----> 5 assert fibonacci(ii) == ff 6 print "Success!" AssertionError:
# This is the test for the factorial code. # Run this after you've written your factorial code # it will fail if your code is wrong! for ii,ff in zip(range(1,9),[1,2,6,24,120,720,5040,40320]): assert factorial(ii) == ff print "Success!" | http://nbviewer.jupyter.org/gist/keflavich/4042018 | CC-MAIN-2016-18 | refinedweb | 2,934 | 75.4 |
How do I update an ObservableCollection via a worker thread?
I've got an ObservableCollection<A> a_collection; The collection contains 'n' items. Each item A looks like this :
public class A : INotifyPropertyChanged { public ObservableCollection<B> b_subcollection; Thread m_worker; }
Basically, it's all wired up to a WPF listview + a details view control which shows the b_subcollection of the selected item in a separate listview (2-way bindings, updates on propertychanged etc.). The problem showed up for me when I started to implement threading. The entire idea was to have the whole a_collection use it's worker thread to "do work" and then update their respective b_subcollections and have the gui show the results in real time.
When I tried it , I got an exception saying that only the Dispatcher thread can modify an ObservableCollection, and work came to a halt.
Can anyone explain the problem, and how to get around it?
Cheers
Answers
Technically the problem is not that you are updating the ObservableCollection from a background thread. The problem is that when you do so, the collection raises its CollectionChanged event on the same thread that caused the change - which means controls are being updated from a background thread.
In order to populate a collection from a background thread while controls are bound to it, you'd probably have to create your own collection type from scratch in order to address this. There is a simpler option that may work out for you though.
Post the Add calls onto the UI thread.
public static void AddOnUI<T>(this ICollection<T> collection, T item) { Action<T> addMethod = collection.Add; Application.Current.Dispatcher.BeginInvoke( addMethod, item ); } ... b_subcollection.AddOnUI(new B());
This method will return immediately (before the item is actually added to the collection) then on the UI thread, the item will be added to the collection and everyone should be happy.
The reality, however, is that this solution will likely bog down under heavy load because of all the cross-thread activity. A more efficient solution would batch up a bunch of items and post them to the UI thread periodically so that you're not calling across threads for each item.
The BackgroundWorker class implements a pattern that allows you to report progress via its ReportProgress method during a background operation. The progress is reported on the UI thread via the ProgressChanged event. This may be another option for you.
New option for .NET 4.5
Starting from .NET 4.5 there is a built-in mechanism to automatically synchronize access to the collection and dispatch CollectionChanged events to the UI thread. To enable this feature you need to call BindingOperations.EnableCollectionSynchronization from within your UI thread.
EnableCollectionSynchronization does two things:
- Remembers the thread from which it is called and causes the data binding pipeline to marshal CollectionChanged events on that thread.
- Acquires a lock on the collection until the marshalled event has been handled, so that the event handlers running UI thread will not attempt to read the collection while it's being modified from a background thread.
Very importantly, this does not take care of everything: to ensure thread-safe access to an inherently not thread-safe collection you have to cooperate with the framework by acquiring the same lock from your background threads when the collection is about to be modified.
Therefore the steps required for correct operation are:
1. Decide what kind of locking you will be using
This will determine which overload of EnableCollectionSynchronization must be used. Most of the time a simple lock statement will suffice so this overload is the standard choice, but if you are using some fancy synchronization mechanism there is also support for custom locks.
2. Create the collection and enable synchronization
Depending on the chosen lock mechanism, call the appropriate overload on the UI thread. If using a standard lock statement you need to provide the lock object as an argument. If using custom synchronization you need to provide a CollectionSynchronizationCallback delegate and a context object (which can be null). When invoked, this delegate must acquire your custom lock, invoke the Action passed to it and release the lock before returning.
3. Cooperate by locking the collection before modifying it
You must also lock the collection using the same mechanism when you are about to modify it yourself; do this with lock() on the same lock object passed to EnableCollectionSynchronization in the simple scenario, or with the same custom sync mechanism in the custom scenario.
Need Your Help
Is there any disadvantage to returning this instead of void?
Dynamically Bind Style to a StackPanel in Windows Phone 7
silverlight windows-phone-7 windows-phone datatrigger stackpanelI have a ListBox that contains a StackPanel with elements for binding. Based on a value, for instance 'Overdue' = true, the style of the StackPanel and a few elements below should change. The only | http://unixresources.net/faq/2091988.shtml | CC-MAIN-2019-04 | refinedweb | 811 | 51.07 |
Text::TagTemplate
1.82
use Text::TagTemplate qw( :standard ); # Define a single tag to substitute in a template. add_tag( MYTAG => 'Hello world.' ); # Define several tags all at once. The tags() method wipes out # all current tags. tags( +{ FOO => 'The string foo.', # Single-quoted string BAR => "$ENV{ USER }", # Double-quoted string LIST => join( '<LI>', @list ), # Function call # Functions or subroutines that get called each time # the tag is replaced, possibly producing different # results for the same tag if it appears twice or more. TIME => \&time(), # Reference to a function SUB => sub { # Anonymous subroutine my( $params ) = @_; return $params->{ NAME }; } } ); # Add a couple of tags to the existing set. Takes a hash-ref. add_tags( +{ TAG1 => "Hello $ENV{ USER }", TAG2 => rand( 10 ), # random number between 0 and 10 } ); # Set the template file to use. template_file( 'template.htmlt' ); # This is list of items to construct a list from. list( 'One', 'Two', 'Three' ); # These are template-fragment files to use for making the list. entry_file( 'entry.htmlf' ); join_file( 'join.htmlf' ); # This is a callback sub used to make the tags for each entry in a # parsed list. entry_callback( sub { my( $item ) = @_; return +{ ITEM => $item }; } ); # Add a new tag that contains the whole parsed list. add_tag( LIST => parse_list_files ); # Print the template file with substitutions. print parse_file;
This module is designed to make the process of constructing web-based applications (such as CGI programs and Apache::Registry scripts) much easier, by separating the logic and application development from the HTML coding, and allowing ongoing changes to the HTML without requiring non-programmers to modify HTML embedded deep inside Perl code.
This module provides a mechanism for including special HTML-like tags in a file (or scalar) and replacing those tags at run-time with dynamically generated content. For example the special tag <#USERINFO
might be replaced by "green" after doing a database lookup. Usually each special tag will have its own subroutine which is executed every time the tag is seen.
Each subroutine can be basically anything you might want to do in Perl including database lookups or whatever. You simply create subroutines to return whatever is appropriate for replacing each special tag you create.
Attributes in the special tags (such as the FIELD="favorite_color" in the example above) are passed to the matching subroutine.
It is not web-specific, though, despite the definite bias that way, and the template-parsing can just as easily be used on any other text documents. The examples here will assume that you are using it for convential CGI applications.
It provides functions for parsing strings, and constructing lists of repeated elements (as in the output of a search engine).
It is object-oriented, but -- like the CGI module -- it does not require the programmer to use an OO interface. You can just import the ``:standard'' set of methods and use them with no object reference, and it will create and use an internal object automatically. This is the recommended method of using it unless you either need multiple template objects, or you are concerned about namespace pollution.
The structure of templates is as any other text file, but with extra elements added that are processed by the CGI as it prints the file to the browser. These extra elements are referred to in this manual as ``tags'', which should not be confused with plain HTML tags -- these tags are replaced before the browser even begins to process the HTML tags. The syntax for tags intentionally mimics HTML tags, though, to simplify matters for HTML-coders.
A tag looks like this:
<#TAG>
or optionally with parameters like:
<#TAG NAME=VALUE>
or with quoted parameters like:
<#TAG
Tags may be embedded in other tags (as of version 1.5), e.g. <#USERINFO
The tag name is the first part after the opening <# of the whole tag. It must be a simple identifier -- I recommend sticking to the character set [A-Z_] for this. The following parameters are optional and only used if the tag-action is a callback subroutine (see below). They are supplied in HTML-style name/value pairs. The parameter name like the tag name must be a simple identifier, and again I recommend that it is drawn from the character set [A-Z_]. The value can be any string, quoted if it contains spaces and the like. Even if quoted, it may not contain any of:
< > " & =
which should be replaced with their HTML escape equivalents:
< > " & =
This may be a bug. At present, other HTML escapes are not permitted in the value. This may also be a bug.
Tag names and parameter names are, by default, case-insensitive (they are converted to upper-case when supplied). You can change this behaviour by using the auto_cap() method. I don't recommend doing that, though.
There are four special parameters that can be supplied to any tag, HTMLESC and URLESC. Two of them cause the text returned by the tag to be HTML or URL escaped, which makes outputting data from plain-text sources like databases or text files easier for the programmer. An example might be:
<#FULL_NAME HTMLESC>
which would let the programmer simply put the full-name data into the tag without first escaping it. Another might be:
<A HREF="/cgi-bin/lookup.cgi?key=<#RECORD_KEY URLESC>">
A typical template might look like:
<HTML><HEAD><TITLE>A template</TITLE></HEAD> <BODY> <P>This is a tag: <#TAG></P> <P>This is a list:</P> <#LIST> <P>This is a tag that calls a callback: <#ITEM ID=358></P> </BODY></HTML>
Note that it is a full HTML document.
You can supply the tags that will be used for substitutions in several ways. Firstly, you can set the tags that will be used directly, erasing all tags currently stored, using the tags() method. This method -- when given an argument -- removes all present tags and replaces them with tags drawn from the hash-reference you must supply. For example:
tags( +{ FOO => 'A string called foo.', BAR => 'A string called bar.' } );
The keys to the hash-ref supplied are the tag names; the values are the substitution actions (see below for more details on actions).
If you have an existing hash you can use it to define several tags. For example:
tags( \%ENV );
would add a tag for each environment variable in the %ENV hash.
Secondly, you can use the add_tags() method to add all the tags in the supplied hash-ref to the existing tags, replacing the existing ones where there is conflict. For example:
add_tags( +{ FOOBAR => 'A string called foobar added.', BAR => 'This replaces the previous value for BAR' } );
Thirdly, you can add a single tag with add_tag(), which takes two arguments, the tag name and the tag value. For example:
add_tag( FOO => 'This replaces the previous value for FOO' );
Which one of these is the best one to use depends on your application and coding style, of course.
Whichever way you choose to supply tags for substitutions, you will need to supply an action for each tag. These come in two sorts: scalar values (or scalar refs, which are treated the same way), and subroutine references for callbacks.
A scalar text value is simply used as a string and substituted in the output when parsed. All of the following are scalar text values:
tags( +{ FOO => 'The string foo.', # Single-quoted string BAR => "$ENV{ USER }", # Double-quoted string LIST => join( '<LI>', @list ), # Function call } );
If the tag action is a subroutine reference then it is treated as a callback. The value supplied to it is a single hash-ref containing the parameter name/value pairs supplied in the tag in the template. For example, if the tag looked like:
<#TAG
the callback would have an @_ that looked like:
+{ NAME => 'Value' }
The callback must return a simple scalar value that will be substituted in the output. For example:
add_tag( TAG => sub { my( $params ) = @_; my $name = $params->{ NAME }; my $text = DatabaseLookup("$name"); return $text; } } );
You can use these callbacks to allow the HTML coder to look up data in a database, to set global configuration parameters, and many other situations where you wish to allow more flexible user of your templates.
For example, the supplied value can be the key to a database lookup and the callback returns a value from the database; or it can be used to set context for succeeding tags so that they return different values. This sort of thing is tricky to code but easy to use for the HTMLer, and can save a great deal of future coding work.
If no action is supplied for a tag, the default action is used. The default default action is to confess() with an error, since usually the use of unknown tags indicates a bug in the application. You may wish to simply ignore unknown tags and replace them with blank space, in which case you can use the unknown_action() method to change it. If you wish to ignore unknown tags, you set this to the special value ``IGNORE''. For example:
unknown_action( 'IGNORE' );
Unknown tags will then be left in the output (and typically ignored by web browsers.) The default action is indicated by the special value ``CONFESS''. If you want to have unknown tags just be replaced by warning text (and be logged with a cluck() call), use the special value ``CLUCK''. For example:
unknown_action( 'CLUCK' );
If the default action is a subroutine reference then the name of the unknown tag is passed as a parameter called ''TAG''. For example:
unknown_action( sub { my( $params ) = @_; my $tagname = $params->{ TAG }; return "<BLINK>$tagname is unknown.</BLINK>"; } );
You may also specify a custom string to be substituted for any unknown tags. For example:
unknown_action( '***Unknown Tag Used Here***' );
Once you have some tags defined by your program you need to specify which template to parse and replace tags in.
You can supply a string to parse, or the name of file to use. The latter is usually easier. For example:
template_string( 'A string containing some tag: <#FOO>' );
or:
template_file( 'template.htmlt' );
These methods just set the internal string or file to look for; the actual parsing is done by the parse() or parse_file() methods. These return the parsed template, they don't store it internally anywhere, so you have to store or print it yourself. For example:
print parse_file;
will print the current template file using the current set of tags for substitutions. Or:
$parsed = parse;
will put the parsed string into $parsed using the current string and tags for substitutions.
These methods can also be called using more parameters to skip the internally stored strings, files, and tags. See the per-method documentation below for more details; it's probably easier to do it the step-by-step method, though.
One of the things that often comes up in CGI applications is the need to produce a list of results -- say from a search engine.
Because you don't necessarily know in advance the number of elements, and usually you want each element formatted identically, it's hard to do this in a single template.
This module provides a convenient interface for doing this using two templates for each list, each a fragment of the completed list. The ``entry'' template is used for each entry in the list. The ``join'' template is inserted in between each pair of entries. You only need to use a ''join'' template if you, say, want a dividing line between each entry but not one following the end of the list. The entry template is the interesting one.
There's a complicated way of making a list tag and an easy way. I suggest using the easy way. Let's say you have three items in a list and each of them is a hashref containing a row from a database. You also have a file with a template fragment that has tags with the same names as the columns in that database. To make a list using three copies of that template and add it as a tag to the current template object, you can do:
add_list_tag( ITEM_LIST => \@list );
and then when you use the tag, you can specify the template file in a parameter like this:
<#ITEM_LIST
If the columns in the database are "name", "address" and "phone", that template might look like:
<LI>Name: <#NAME HTMLESC><BR> Address: <#ADDRESS HTMLESC><BR> Phone: <#PHONE HTMLESC</LI>
Note that the path to the template can be absolute or relative; it can be any file on the system, so make sure you trust your HTML people if you use this method to make a list tag for them.
The second argument to add_list_tag is that list of tag hashrefs. It might look like:
+[ +{ NAME => 'Jacob', ADDRESS => 'A place', PHONE => 'Some phone', }, +{ NAME => 'Matisse', ADDRESS => 'Another place', PHONE => 'A different phone', }, ]
and for each entry in that list, it will use the hash ref as a miniature set of tags for that entry.
If you want to use the long way to make a list (not recommended; it's what add_list_tag() uses internally), there are three things you need to set:
You set the list of elements that you want to be made into a parsed list using the list() method. It just takes a list. Obviously, the ordering in that list is important. Each element is a scalar, but it can be a reference, of course, and will usually be either a key or a reference to a more complex set of data. For example:
list( $jacob, $matisse, $alejandro );
or list( \%hash1, \%hash2, \%hash3 );
You set the templates for the entry and join templates with the entry_string() & join_string() or entry_file() & join_file() methods. These work in the way you would expect. For example:
entry_string( '<P>Name: <#NAME></P><P>City: <#CITY></P>' ); join_string( '' );
or:
entry_file( 'entry.htmlf' ); join_file( 'join.htmlf' );
Usually the _file methods are the ones you want.
In the join template, you can either just use the existing tags stored in the object (which is recommended, since usually you don't care what's in the join template, if you use it at all) or you can supply your own set of tags with the join_tags() method, which works just like the tags() method.
The complicated part is the callback. You must supply a subroutine to generate the tags for each entry. It's easier than it seems.
The callback is set with the entry_callback() method. It is called for each entry in the list, and its sole argument will be the item we are looking at from the list, a single scalar. It must return a hash-ref of name/action pairs of the tags that appear in the entry template. A callback might look like this:
entry_callback( sub { my( $person ) = @_; # $person is assumed to be a hash-ref my $tags= +{ NAME => $person->name, CITY => $person->city }; return $tags; } );
You then have to make the list from this stuff, using the parse_list() or parse_list_files() methods. These return the full parsed list as a string. For example:
$list = parse_list;
or more often you'll be wanting to put that into another tag to put into your full-page template, like:
add_tag( LIST => parse_list_files );
That example above might produce a parsed list looking like:
<P>Name: Jacob</P><P>City: Norwich</P> <P>Name: Matisse</P><P>City: San Francisco</P> <P>Name: Alejandro</P><P>City: San Francisco</P>
which you could then insert into your output.
If you're lazy and each item in your list is either a hashref or can easily be turned into one (for example, by returning a row from a database as a hashref) you may just want to return it directly, like this:
entry_callback( sub { ( $userid ) = @_; $sth = $dbh->prepare( <<"EOS" ); SELECT * FROM users WHERE userid = "$userid" EOS $sth->execute; return $sth->fetchrow_hashref; } );
or more even more lazily, something like this:
$sth = $dbh->prepare( <<"EOS" ); SELECT * FROM users EOS $sth->execute; while ( $user = $sth->fetchrow_hashref ) { push @users, $user; } list( @users ); entry_callback( sub { return $_[ 0 ] } );
Isn't that easy? What's even easier is that the default value for entry_callback() is
sub { return $_[ 0 ] }, so if your list is a list of hashrefs, you don't even need to touch it.
You have a choice when using this module. You may either use an object-oriented interface, where you create new instances of Text::TagTemplate objects and call methods on them, or you may use the conventional interface, where you import these methods into your namespace and call them without an object reference. This is very similar to the way the CGI module does things. I recommend the latter method, because the other forces you to do a lot of object referencing that isn't particularly clear to read. You might need to use it if you want multiple objects or you are concerned about namespace conflicts. You'll also want to use the object interface if you're running under mod_perl, because mod_perl uses a global to store the template object, and it won't get deallocated between handler calls.
For the OO interface, just use:
use Text::TagTemplate; my $parser = new Text::TagTemplate;
For the conventional interface, use:
use Text::TagTemplate qw( :standard );
and you'll get all the commonly-used methods automatically imported. If you want the more obscure configuration methods, you can have them too with:
use Text::TagTemplate qw( :standard :config );
The examples given here all use the conventional interface, for clarity. The OO interface would look like:
$parser = new Text::TagTemplate; $parser->template_file( 'default.htmlt' ); $parser->parse;
The following are the public methods provided by Text::TagTemplate.
Instantiate a new template object. Optionally take a hash or hash-ref of tags to add initially.
my $parser = Text::TagTemplate->new(); my $parser = Text::TagTemplate->new( %tags ); my $parser = Text::TagTemplate->new( \%tags );
The default pattern for tags is
<#TAGNAME attributes >. This is implemented internally as a regular expression:
(?-xism:<#([^<>]*)) made up from three pieces which you may override using the next three methods tag_start(), tag_end(), and tag_contents().
For example, you might want to use a pattern for tags that does not look like HTML tags, perhaps to avoid confusing some HTML parsing tool.
Examples;
To use tags like this:
/* TAGNAME attribute=value attribute2=value */
Do this:
tag_start('/\*'); # you must escape the * character tag_contents('[^*]*'); # * inside [] does not need escaping tag_end('\*/'); # escape the *
tag_start()or
tag_start( $pattern )
Set and or get the pattern used to find the start of tags.
With no arguments returns the current value. The default value is
<#.
If an argument is supplied it is used to replace the current value. Returns the new value.
See also tag_contents() and tag_end(), below.
tag_contents()or
tag_contents( $pattern )
Set and or get the pattern used to find the content of tags, that is the stuff in between the tag_start and the tag_end.
With no arguments returns the current value. The default value is
[^<>]*.
If an argument is supplied it is used to replace the current value. Returns the new value.
The pattern should be something that matches any number of characters that are not the end of the tag. (See tag_end, below.) Typ[ically you should use an atom followed by *. In the defaul pattern
[^<>]* the
[^<>] defines a "character class" consisting of anything except < or >. The
* means "zero-or-more" of the preceding thing.
Examples:
Set the contents pattern to match anything that is not
--
tag_end()or
tag_end( $pattern )
Set and or get the pattern used to find the end of tags.
With no arguments returns the current value. The default value is
<.
If an argument is supplied it is used to replace the current value. Returns the new value.
tag_patten()
Returns the complete pattern used to find tags. The value is returned as a quoted regular expression. The default value is
(?-xism:<#([^<>]*)).
Equivalant to:
$start = tag_start(); $contents = tag_contents(); $end = tag_end(); return qr/$start($contents)$end/;
auto_cap()or
auto_cap( $new_value )
Returns whether tag names will automatically be capitalised, and if a value is supplied sets the auto-capitalisation to this value first. Default is 1; changing it is not recommended but hey go ahead and ignore me anyway, what do I know? Setting it to false will make tag names case-sensitive and you probably don't want that.
unknown_action()or
unknown_action( $action )
Returns what to do with unknown tags. If a value is supplied sets the action to this value first. If the action is the special value 'CONFESS' then it will confess() at that point. This is the default. If the action is the special value 'IGNORE' then unknown tags will be ignored by the module, and will appear unchanged in the parsed output. If the special value 'CLUCK' is used then the the unknown tags will be replaced by warning text and logged with a cluck() call. (See Carp for cluck() and confess() - these are like warn() and (die(), but with a stack trace.) Other special values may be supplied later, so if scalar actions are require it is suggested that a scalar ref be supplied, where these special actions will not be taken no matter what the value.
tags()or
tags( %tags )or
tags( \%tags )
Returns the contents of the tags as a hash-ref of tag/action pairs. If tags are supplied as a hash or hashref, it first sets the contents to these tags, clearing all previous tags.
add_tag( $tag_name, $tag_action )
Adds a new tag. Takes a tag name and the tag action.
add_list_tag( $tag_name, \@list, $entry_callback, @join_tags )
Add a tag that will build a parsed list, allowing the person using the tag to supply the filename of the entry and join templates, or to supply the strings directly in tag parameters (which is currently annoying given the way they need to be escaped). The tag will take parameters for ENTRY_STRING, ENTRY_FILE, JOIN_STRING or JOIN_FILE.
No checking is currently performed on the filenames given. This shouldn't be a security problem unless you're allowing untrusted users to write your templates for you, which mean it's a bug that I need to fix (since I want untrusted users to be able to write templates under some circumstnaces).
add_tags( %tags )or
add_tags( \%tags )
Adds a bunch of tags. Takes a hash or hash-ref of tag/action pairs.
delete_tag( $name )
Delete a tag by name.
clear_tags()
Clears all existing tags.
list()or
list( @list )
Returns (and sets if supplied) the list of values to be used in parse_list() or parse_list_files() calls.
template_string()or
template_string( $string )
Returns (and sets if supplied) the default template string for parse().
template_file()or
template_file( $file )
Returns (and sets if supplied) the default template file for parse_file().
entry_string()or
entry_string( $string )
Returns (and sets if supplied) the entry string to be used in parse_list() calls.
entry_file()or
entry_file( $file )
Returns (and sets if supplied) the entry file to be used in parse_list_files() calls.
entry_callback()or
entry_callback( $callback )
Returns (and sets if supplied) the callback sub to be used in parse_list() or parse_list_files() calls. If you don't set this, the default is just to return the item passed in, which will only work if the item is a hashref suitable for use as a set of tags.
join_string()or
join_string( $string )
Returns (and sets if supplied) the join string to be used in parse_list() calls.
join_file()or
join_file( $file )
Returns (and sets if supplied) the join file to be used in parse_list_files() calls.
join_tags()or
join_tags( %tags )or
join_tags( \%tags )
Returns (and sets if supplied) the join tags to be used in parse_list() and parse_list_files() calls.
parse()or
parse( $string )or
parse( $string, %tags )or
parse( $string, \%tags )
Parse a string, either the default string, or a string supplied. Returns the string. Can optionally also take the tags hash or hash-ref directly as well.
parse_file()or
parse_file( $file )or
parse_file( $file, %tags )or
parse_file( $file, \%tags )
Parses a file, either the default file or the supplied filename. Returns the parsed file. Dies if the file cannot be read. Can optionally take the tags hash or hash-ref directly.
parse_list()or
parse_list( \@list )
parse_list( \@list, $entry_string, $join_string )
parse_list( \@list, $entry_string, $join_string, $entry_callback, \%join_tags )
Makes a string from a list of entries, either the default or a supplied list.
At least one template string is needed: the one to use for each entry, and another is optional, to be used to join the entries.
A callback subroutine must be supplied using entry_callback(), which takes the entry value from the list and must return a hash-ref of tags to be interpolated in the entry string. This will be called for each entry in the list. You can also supply a set of tags for the join string using join_tags(), but by default the main tags will be used in that string.
You can also optionally supply the strings for the entry and join template. Otherwise the strings set previously (with entry_string() and join_string() ) will be used.
Finally, you can also supply the callback sub and join tags directly if you want.
parse_list_files()or
parse_list_files( \@list )
parse_list_files( \@list, $entry_file, $join_file )
parse_list_files( \@list, $entry_file, $join_file, $entry_callback )
parse_list_files( \@list, $entry_file, $join_file, $entry_callback, %join_tags )
parse_list_files( \@list, $entry_file, $join_file, $entry_callback, \%join_tags )
Exactly as parse_list(), but using filenames, not strings.>
The README file supplied with the distribution, and the example/ subdirectory there, which contains a full CGI application using this module.
The CGI module documentation.
Carp(3) | http://search.cpan.org/dist/Text-TagTemplate/lib/Text/TagTemplate.pm | CC-MAIN-2014-52 | refinedweb | 4,231 | 69.52 |
Digital Editions can't / won't link with my eReader...pearseol Jan 5, 2012 5:11 PM
I have followed the steps in setting up my Sony PRS-T1 - however when I click on Setup Reader for PC, I didn't get any instruction panel, just click and then eggtimer for a couple of seconds and then nothing. Then at the first time I tried to link the eReader to my Adobe Digital Editions, I got an error message and it didnt work and subsequently, when trying to link, I don't get the error message and it doesn't link... Is there an easy solution...?
Thanks, Pearse in Dublin...
1. Re: Digital Editions can't / won't link with my eReader...Frustrated in AZ Jan 6, 2012 7:55 AM (in response to pearseol)
There are a couple of things you can do. First, when you set up your
PRS-T1, the 'Setup Reader for PC' function is intended to link the T1 with
the SONY site. Adobe Digital Editions (ADE) is not part of this process.
When you set up your ereader, you used an ID and password to access the
SONY site. That information was recorded in a small file placed on the
T-1. ADE accesses this information to authorize your ereader, so it can
transfer ebooks to the T1. The normal process is to use your Adobe ID and
password when you set up the T1, and then ADE will recognise the ereader
right off the bat. The alternative is to have your T1 connected and
recognised by your computer (I assume it's a Windows PC), and then bring up
ADE. If the T1 doesn't show up on the bookshelf (left hand panel of the
Library view), you can click on the small arrow icon next to the word
'Library'. A drop-down menu will appear, and then you can choose
'Authorize Computer'. You should be able to find your T1 and authorise it
that way.
Hope this helps!
===========
2. Re: Digital Editions can't / won't link with my eReader...Keninator7 Jan 7, 2012 9:26 PM (in response to Frustrated in AZ)
I tried the method you suggested, and it does not work for me. My T1 is unknown by ADE.
3. Re: Digital Editions can't / won't link with my eReader...wkaan Jan 10, 2012 8:26 PM (in response to pearseol)
This is the same for me. It seems like even though Adobe is happy to take the money for the DRM, they don't actually support it. Or its another hopelessly complicated DRM scene that needs chucking out as did Apple's iTunes DRM.
If the reader isn't registered with Sony, you can't read Google books? Eh, can you explain that to me?
Ripped off. I'm going back to printed books, I can even lend them to my daughter!
4. Re: Digital Editions can't / won't link with my eReader...Frustrated in AZ Jan 11, 2012 1:29 PM (in response to wkaan)
Your comments generate my comments....
The situation ain't perfect. The publishing community formulated the
Digital Millenium Copyright Act of 2000 during the 1990's, when the issues
they were dealing with werent' resolved. Today's issues are somewhat
different, and the impact of what they did back then is frustrating to many
of us, because we see it as overly restrictive and limiting. Adobe had its
Content Server software available at the time of the DMCA, and it was one
of the methods to implement digital rights on digital media. It's become
the predominant method now, as others have not been as effective or popular.
Digital Editions is a product of Adobe, and it uses parts from Content
Server and Reader software that Adobe developed. Whether we like the
product or not, it's become a standard in the epublishing industry, and is
used heavily in transfers from libraries and ebook sources. It is supposed
to be a dynamic product, responding to changes in the marketplace and
implementing new technology along the way. It's current level is 1.7 plus,
indicating that it has done so in the past. However, the marketplace may
be moving more rapidly that Digital Editions is. New devices come on the
market every month, claiming that their owners can read ebooks on them, but
not explaining how that's done. Fixes aren't being implemented rapidly
enough either, according to many of us users. Error code messages are in
programmer-speak, and are not user-friendly. AND, worse of all, Adobe
technical support doesn't support it - because it's a free product.
Many if not nearly all of us who use DE have very few problems. They did
get something right, even if it appears to you from your experience that
they did not. Don't blame DE for its implementation of current practice
and DRM because you don't agree with those practices.
===============
5. Re: Digital Editions can't / won't link with my eReader...Kumabjorn2 Jan 14, 2012 10:38 AM (in response to Frustrated in AZ)
It seems a lot of people have problems getting their PRS-T1 to be recognized.
When I click the arrow next to "Library" and select authorize computer I get a message that my computer is already authorized, but nothing about an E-Reader.
I relize that you are as frustrated in AZ as I am. The problem is that bookstores refer you to Adobe that refer you to these boards, and that makes for even more frustration because nobody seems to be responsible.
6. Re: Digital Editions can't / won't link with my eReader...hmeig Feb 12, 2012 10:54 AM (in response to pearseol)
This has happened to me too!
I have a very old Sony Reader PRS-505 so I can understand why it's probably not working, although I have yet to find a solution.
I used Kobo and WHSmiths and it worked fine so I suggest you use them instead!
7. Re: Digital Editions can't / won't link with my eReader...Keninator7 Feb 12, 2012 11:15 AM (in response to pearseol)
Here is a workaround...hope it helps the frustrated ones! It works well for me.
- Download the files from your xxxxxxxxbook.com Account into Adobe Digital Editions.
- Once you have the files in Adobe, open your Sony Reader Library (the software that comes with your Sony Reader) or use Calibre.
- Click on "File" at the top of your Reader Library screen and select "Import Folder".
- The folder you would like to import is called "My Digital Editions" which can be found within your "Documents" folder on your PC or Mac.
- Single-click on the "My Digital Editions" folder and hit the "Select" button to import this folder into the Reader Library.
- All of the eBooks you have in Adobe Digital Editions will now be imported into the Reader Library so you can now plug in your Sony Reader.
- Select the eBook you'd like to transfer to your sony device by clicking on it. A square box will outline the eBook on your screen.
- Go to the bottom of the screen to More Options
- Select Sync with Reader Device
8. Re: Digital Editions can't / won't link with my eReader...vinnie452 Apr 29, 2012 4:10 PM (in response to Keninator7)
woohoo this solution worked for me thank you very much
9. Re: Digital Editions can't / won't link with my eReader...Chelli2153 May 16, 2012 4:36 PM (in response to Keninator7)
Thank you so much. I have been tearing my hair out trying to work it out and your instructions are so simple.
10. Re: Digital Editions can't / won't link with my eReader...hmeig May 18, 2012 4:52 AM (in response to pearseol)
Still frustrated!
I have a very old Sony eBook Reader (it was released in 2008 I think) and I'm on a Mac computer so I guess that doesn't help either. I think I give up
Think I'm going to invest in a Kindle or something..although the books I downloaded onto my eReader from WHSmiths-Kobo store worked fine and went straight onto it, but I've been having a lot of trouble with Waterstones since the very beginning!
11. Re: Digital Editions can't / won't link with my eReader...Frustrated in AZ May 18, 2012 9:14 AM (in response to hmeig)
It's not the SONY - it's the website. If you go back and try again, make
SURE you specify .epub formats. If the ebook transfer process messes up
again, then I'd contact them and discuss how they've implemented DRM
(digital rights management). They may have messed that part up and that
would cause you problems.
============
12. Re: Digital Editions can't / won't link with my eReader...mishyyyyy Jun 6, 2012 2:49 PM (in response to Keninator7)
Thank you Keninator! I've also been in trouble for hours trying to get an e-book I just bought on my Sony reader, and really couldn't find any help until I read your message, and then it was a matter of seconds. I'm really really grateful. Thanks!!
13. Re: Digital Editions can't / won't link with my eReader...sarjtess Jun 16, 2012 10:53 PM (in response to Keninator7)
Like so many others before me, I have been fighting to load a book on our new Sony ereader, and had no success until I read your instructions. If only the products instructions where so easy. You're a star. Many, many thanks. Cheers.
14. Re: Digital Editions can't / won't link with my eReader...blackstonecat Jul 5, 2012 8:44 PM (in response to pearseol)
On the Sony website I found a page that indicates that Adobe Digital Reader is NOT supported for the Sony PRS-T1. You can read it here...®ion_id= 1
I just bought my reader today. I've had ADR installed on my computer for about a month, and used it to download and read a couple of library books on my PC.
Imagine my frustation when I couldn't get it to recognize my new reader, no matter what I did!
I've been through the process of uninstalling and reinstalling at least 20 times by now. We even tried it on another computer, and still no luck.
I tried all the fixes above, and also cleared my registry before reloading.
After finding the above link, I have followed the recommendations to use the Sony Reader software instead of ADR. It works. You really don't need ADR to download library books to your computer and then to your reader if you don't have WiFi, because the Sony Software will do the job once you sync the new downloads with your reader.
On the link below, which is for downloading the software, the PRS-T1 doesn't even come up.®ion_id= 1
I have tried various methods but ADR will not sync with my new reader. However, it is not needed. Once you have your SONY Reader software enabled, and your eReader is hooked up and data transfer is enabled, you can log into the Overdrive website and download library books directly to your reader, (the choice comes up at checkout. You also have the option to download to your computer if you prefer. You can of course use WiFi and download directly.
I find that its easier to log into my library's collection on my computer, put items in my wish list, then as they become available, I can put them in my cart, log out, and from my eReader, log back in to download. Its faster then hunting for books from the eReader's screen.
It has been an extremely frustrating day trying to get this software to work with my new PSR-T1.
I'm glad that I don't need it after all!
15. Re: Digital Editions can't / won't link with my eReader...Frustrated in AZ Jul 6, 2012 8:10 PM (in response to blackstonecat)
'Frustrating' is in my name. But, you have to realize that you didn't do
much research - you just bulled ahead with trying different
things with ADE (it's not ADR). Your frustration comes from several
sources, not just this software.
SONY Reader software is designed to work with all SONY ereaders, but limits
you to what the SONY ebookstore has to offer. If you want to get ebooks
from other sources, you can use ADE as a download tool to put the ebooks
onto your computer, and then use the SONY software to transfer them to your
ereader. SONY will tell you how to acquire ebooks from other sources and
import them into the Reader library, so it's an easy thing to do.
=======================
16. Re: Digital Editions can't / won't link with my eReader...Potirons World Jul 15, 2012 6:01 AM (in response to Frustrated in AZ)
For a month now, I've been trying to download 4 DRM epub books purchased on Kobo.com onto my SONY PRS-T1 and on my computer. After numerous emails back and forth with Kobo help center, I still cannot download these books. I've installed and re-installed ADE on the computer (and have had it authorized) I have Calibre and the Sony software that accompanies the reader and I even set up the kobo reader app. Nothing doing, the books remain in the kobo library (they can go onto the kobo app, but I want to read my books on my e-reader, not on my computer!!!)... ADE doesn't recognize my e reader, and I'm willing to do what is suggested above, but I can't even get the books through ade.... ANy suggestions???
What can I do???
I've asked KOBO to reimburse me, but they don't seem to be willing.
17. Re: Digital Editions can't / won't link with my eReader...Frustrated in AZ Jul 15, 2012 6:40 AM (in response to Potirons World)
Dealing with multiple environments and vendors can be VERY frustrating.
Trust me on this one. Using ereaders involves a lot of technology.
There could be multiple issues here. The first one is the compatibility of
the T1 with ADE: SONY says it's not compatible, and I have heard from
others also that ADE does not support it. So, you may need to perform some
additional steps to get this going. The first one is to register the
ereader with SONY, which you may have done (using your Adobe ID, so that
you simplify the rest of the process). When you do this, SONY will
download and install their Reader Library software onto your computer.
Your T1 will work with the Reader Library software. If you want to buy
ebooks from SONY, the Reader Library software will handle the transfer,
just as ADE would, and will pass the ebooks onto your ereader.
You mention that your ebooks 'remain in the KOBO library'. I assume that
this means they're still on the KOBO website in your library space. If my
assumtion is wrong, and the ebooks are on your computer, then we're going
to talk about the digital rights assigned to the ebooks.
I use the KOBO ebookstore all the time with ADE, and I don't have issues
with the KOBO-ADE interface at all. So, there has to be something in the
ADE setup or in your environment that's not right. You haven't said what
your environment is, so I will assume Windows. Macs are a different matter.
Let's start with a question: did you obtain an Adobe ID and password before
you downloaded and installed ADE? If you did, is your copy of ADE
authorized to your Adobe ID? (you can check this out easily if you open ADE
in Library mode, and click on the small arrow next to the word 'Library'.
A drop-down menu will appear, and you choose 'Authorize Computer' from it.
If you copy of ADE is authorized, it will display the Adobe ID. Next up:
are you getting any other error messages? If so, it's possible that your
firewall or Windows settings are prohibiting transfer of the material from
the KOBO bookstore to your computer. There are lots of posts on the forum
that discuss what those settings are and how to set them to allow the
ebooks through.
If you've been successful in transferring the ebooks to your computer, DRM
protection on the ebooks may be set to prohibit copying to your ereader,
which will confine them to your computer. You can check on this by putting
your cursor on the ebook entry in ADE. A balloon labelled 'Item Options'
will appear. Click on it, and you'll see a drop-down menu with 'Item
Info'. Click on that, and the digital rights for that ebook will be
displayed. If they're set to deny copying to any device, that means you
can't copy it to your ereader. There is no way you personally can do
anything about this if the permissions are set this way - you have to go
back to the source and get them to unlock the DRM permissions, which they
may - or may not - do for you.
Badk for a moment to the SONY T1. If you can get the ebooks downloaded
into ADE, you can get the Reader Library software to find them and bring
them into the Reader Library. Once there, you can use the Reader Library
software to download them to your T1 (if DRM allows). I don't know whether
you can use Reader Library to download the ebook from KOBO, however.
Hope this helps!
==============
18. Re: Digital Editions can't / won't link with my eReader...Potirons World Jul 15, 2012 7:54 AM (in response to Frustrated in AZ)
Thank you Frustrated. I have authorization everywhere I'm supposed to. The books remain on the Kobo website library as you suppose. Cannot download it through ADE even though I have authorization on my computer and on my e-reader.... The strange thing is, I purchased 2 books on Kobo back in April and had no problem whatsoever. (and those were DRM epub as well). Now even those cannot be downloaded again (but maybe that's normal) and funny enough even the free books i.e. public domain books with the button DRM epub cannot be downloaded.... strange strange. (and public domain books with the button dowload epub I can download without any problem...)
If I could get them through ADE, with Calibre I suppose I could put them on my device.
my environment is Windows as you assume.
everything is pretty straightforward on my computer. I of course have the sony reader set up on the compute too... and it's supposed to work with KOBO... (same ID as Adobe ID) I just don't know what else to do... I've disinstalled and re-installed everything to make sure I have latest versions...
thanks for your help
19. Re: Digital Editions can't / won't link with my eReader...Frustrated in AZ Jul 15, 2012 9:50 PM (in response to Potirons World)
I am beginning to suspect that something's changed in your environment, or
that you used a different Adobe ID when you downloaded the ebooks in
April. I asked if you were getting any messages, but you've not replied to
that portion of my post.
One comment of yours needs clarification: "*If I could get them through
ADE, with Calibre I suppose I could put them on my device." *That's not
the way it works. You won't get them through ADE by using Calibre - at
least not directly. You could try to use any ebook transfer software that
works with DRM-protected files to download the ebooks to your computer, and
then bring them into ADE or into the SONY Reader Library by using the
features of those packages to import files IF the DRM settings will
allow that to happen.....
Sorry!
=========
20. Re: Digital Editions can't / won't link with my eReader...Potirons World Jul 16, 2012 12:40 AM (in response to Frustrated in AZ)
I'm obviously technically challenged!!! ;-)
To break things down, back in April, when I purchased those 2 books from Kobo, it went so fast I don't really remember how they downloaded onto my computer but it wasn't through ADE, that I'm sure, it was either through calibre or the sony reader software. I believe that when I clicked on the download button a little window asked through which one I wanted to download. I probably chose calibre because I like the way things are managed in there... but maybe it was the sony software by default - I really don't remember.
When I purchased the 4 books a month ago (already!!!) from Kobo, when I clicked on the download button (that now reads Adobe DRM epub file) it just ran for a while and then the error message I got was :
La connexion a été réinitialisée
La connexion avec le serveur a été réinitialisée pendant le chargement de la page.
Le site est peut-être temporairement indisponible ou surchargé. Réessayez plus
tard ;
Si vous n'arrivez à naviguer sur aucun site, vérifiez la connexion
au réseau de votre ordinateur ;
Si votre ordinateur ou votre réseau est protégé par un pare-feu ou un proxy,
assurez-vous que Firefox est autorisé à accéder au Web.
(meaning, if you don't speak French, that the server has been reinitialized during the loading of the page and to try again - I've been trying for a month!!!)
- Do you think I should de-install everything (calibre, kobo, ade, sony etc... and the reader) and start all over again?
- If so in which order? and what do I do with the books I already have so as to not lose them???
- you mention forums on which discussions about cheking if my windows has changed since april, can you give me links to that effect?
- I know I have the same IDs for ADE and bookstores (sony and kobo)
I feel like I'm going around in circles...
thanks for all the help you're offering...
21. Re: Digital Editions can't / won't link with my eReader...Chelli2153 Jul 16, 2012 3:39 AM (in response to Potirons World)
I also had purchased a book from Kobo and couldn't get it onto my ereader. I ended up downloading the book onto my computer and then opening Sony ereader program and importing it into the library. I don't have to use ADE at all.
There is nothing more frustrating than not being able to access something you have purchased.
22. Re: Digital Editions can't / won't link with my eReader...Potirons World Jul 16, 2012 3:43 AM (in response to Chelli2153)
chelli, thanks but I can't even get them on my computer... and I agree with your last sentence!!! I believe I have been extraordinarily patient, as I've been in this bind for a month now.................!
There is nothing more frustrating than not being able to access something you have purchased!!!!!!
23. Re: Digital Editions can't / won't link with my eReader...Frustrated in AZ Jul 16, 2012 9:55 AM (in response to Potirons World)
Bien sur que le Francais. Mais, en Anglais....
From the message, it appears your issues are all about security settings.
What you got was a message saying that your connection to the website was
broken by your web browser (Firefox).
ADE has been tested with Firefox, but most of us Windows people use
Internet Explorer. So, I can't help you with the Firefox settings.
However, the error message points specifically to the security settings in
Firefox. I can't say how to do it, but it would appear that there are some
'permissions' in Firefox, where you designate a particular website as 'OK'
for downloads.... I know that these permissions exist in Internet
Explorer. So try the 'help' function in Firefox to see what it tells you -
that's (unfortunately) the best I can do from here.
==============
24. Re: Digital Editions can't / won't link with my eReader...Potirons World Jul 16, 2012 11:45 PM (in response to Frustrated in AZ)
It doesn't work with Internet Explorer either or Google Chrome, tried
them all....
:(((
--
Nathalie
pour
Potiron's World
Le lun 16/07/12 18:55, Frustrated in AZ forums@adobe.com a écrit:
RE: DIGITAL EDITIONS CAN\'T / WON\'T LINK WITH MY EREADER...
created by Frustrated in AZ in Adobe Digital Editions - View
25. Re: Digital Editions can't / won't link with my eReader...Frustrated in AZ Jul 17, 2012 8:36 AM (in response to Potirons World)
Zut!
What anti-virus program do you use? Let's look at its settings.... Also,
let's look at your Windows 7 settings....
============
26. Re: Digital Editions can't / won't link with my eReader...cbirdwatcher Aug 6, 2012 10:33 AM (in response to Keninator7)
Your solution worked like a charm. I have been around and around for 2 weeks and 2 days trying to get my book into me reader. I am so glad I came across your helpful site.
27. Re: Digital Editions can't / won't link with my eReader...rociom12768759 Aug 19, 2015 12:35 PM (in response to Keninator7)
Thank you very much for your answer. Very helpful
28. Re: Digital Editions can't / won't link with my eReader...steveh15430886 Oct 8, 2016 8:38 AM (in response to Potirons World)
Sony readers do not use ADE. You have to down load an e-reader program which KOBO can provide. Then it should work. Be sure to have the ASCM default set to that program. | https://forums.adobe.com/message/4140377 | CC-MAIN-2017-09 | refinedweb | 4,362 | 72.16 |
cache.
- SwiftUI support.
Kingfisher 101King.
It also works if you use SwiftUI:
import KingfisherSwift really a very common situation I can meet in my daily work. Think about how many lines you need to write without Kingfisher. You will fall in love with it if you give it a try!
Learn MoreLearnRequirements
- whenever you may need a more detailed reference.
OtherOther
Future of KingfisherFuture of Kingfisher
I want to keep Kingfisher lightweight. This framework will focus and, just open a ticket. Pull requests are warmly welcome as well.
ContributorsContributors
This project exists thanks to all the people who contribute. [Contribute].
BackersBackers
Thank you to all our backers! Your support is really important for the project and encourages us to continue.
SponsorsSponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
LicenseLicense
Kingfisher is released under the MIT license. See LICENSE for details. | https://libraries.io/carthage/github.com%2Fonevcat%2Fkingfisher | CC-MAIN-2020-34 | refinedweb | 155 | 60.21 |
This blog describes how to use the new XI sender adapter, which will be available for customers with the 10-June-2018 release. It describes the configuration options, size limits and monitoring options of your scenario.
Configuring a Scenario Using the XI Sender Adapter
Many customers run existing on-premise backend systems that can connect using the XI 3.0 protocol to an integration broker. In most cases the broker is an SAP NetWeaver PI (Process Integration) or PO (Process Orchestration) system. Now, with the new XI adapter, customers can also connect their on-premise backends to SAP Cloud Platform Integration using the XI 3.0 protocol. Whereas the XI sender adapter can be used to receive messages via the XI 3.0 protocol, the XI receiver adapter can be use used to send out messages using the XI 3.0 protocol.
In this blog, I focus on the XI sender adapter and continue with the sample scenario started for the XI receiver adapter in blog Configuring Scenario Using the XI Receiver Adapter. In this scenario, we will now consume the asynchronous XI message from the backend system. To follow the whole scenario it’s easiest for you to start with the sample scenario using the XI receiver adapter and then continue with the XI sender scenario. But you can also consume the scenario for the XI sender adapter independently. In that case, you just configure the confirmation message and send it using transaction SPROXY.
To receive a message via XI 3.0 protocol in Cloud Integration, you need to configure an integration flow with an XI sender adapter and you need to configure the sender backend to send the message to the endpoint the XI sender adapter of the deployed integration flow exposes in Cloud Integration.
Configure the Integration Flow Receiving the XI Message
First, we configure the integration flow in the Web UI, Design section. Create an integration flow, connect the sender participant with the start message event and select the XI adapter.
Configure the XI Sender Channel
First, you choose the Connection tab in the XI sender channel. Configure a path in the Address field. This path will be generated into the endpoint URL, which is called from the sender system to trigger the integration flow execution.
In the Delivery Assurance tab, specify the Quality of Service and, in case of At Least Once and Exactly Once, the Retry configuration settings. Let’s check the options in more detail.
To define the Quality of Service, you have the following options: either At Least Once, Exactly Once or Best Effort:
- Best Effort is used for synchronous request-reply scenarios, that means, in case your sender system has a synchronous interface through which you like to send a message to Cloud Integration you use this option. If you select this option, you don’t need to configure any additional settings because the message request and the response are processed immediately in Cloud Integration. Therefore, no temporary storage of the message for later retry is involved.
- Exactly Once and At Least Once are both used for asynchronous one-way scenarios, that means if your sender system has an asynchronous interface through which you like to send a message to Cloud Integration you need to use this option. If you configure this option the message is temporarily stored in the Cloud Integration tenant and, if an error occurs, the message is retried from there. The sender gets the successfully received status as soon as the message is persisted in the temporary storage. The difference is that
- Exactly Once (with version 1.8 or higher of the XI sender adapter in January 2019 release) is ensuring that the XI sender adapter does not process the message if the same XI message ID was already received. It returns a duplicate message back to the sender, but does not process the message in Platform Integration. This is implemented using an Idempotent Repository storing all the received XI message IDs.
- Note, that this option can only be used with Data Store as temporary storage because also the Idempotent Repository is based on the database and Cloud Integration cannot support consistent data between JDBC and JMS resources.
- Also be aware that the performance is not as good as with the At Least Once option because of the additional check against the Idempotent Repository.
- Exactly Once (with version up to 1.7 of the XI sender adapter) processes the same XI message multiple times, if the sender sends it again. With this option the receiver should be able to handle duplicates. This option is equivalent to the At Least Once option available in the 1.8 version.
- At Least Once (with version 1.8 or higher of the XI sender adapter in January 2019 release) processes the same XI message multiple times, if the sender sends it again. With this option the receiver should be able to handle duplicates. Note, that this option has better performance because no check against the Idempotent Repository has to be done.
We configure At Least Once for our sample scenario as we want to receive an asynchronous message. In this case the Temporary Storage needs to be defined. You can select to store the message temporarily either in the Data Store or in JMS Queues:
- When Data Store is selected the message is persisted temporarily in the tenant’s database. The stored message can be monitored in the data store monitor.
- If JMS Queue is selected the message is stored in a JMS queue on the connected JMS broker. Note, that the JMS Queue option is more performant but is only available if you have an Enterprise or Messaging License purchased for the tenant. (You can find more details in the in blog ‘How to activate Message Broker’.)
If Data Store.
- Encrypt Message During Persistence: If this option is selected the message is encrypted in the data store during temporary storage. Note that this is recommended if the message contains sensitive data. However, the drawback is that this setting reduces the performance slightly.
- Note that no configuration option is available for dead-letter queue handling. If the data store is used as temporary storage the out-of-memory handling is always active. Which means that after the 3rd retry caused by an out-of-memory a message is blocked and taken out of further processing.
If JMS Queue.
- Dead-Letter Queue: You should select this option to handle potential out-of-memory situations caused by large messages. If selected, a message is blocked and taken out of further processing after the 3rd retry caused by an out-of-memory. More details about the dead letter queue handling can be found in blog How to configure Dead Letter Handling in JMS Adapter.
- Encrypt Message During Persistence: You define if the message is to be encrypted in the data store during temporary storage. Note that this is recommended for sensitiv data but it reduces the performance slightly.
Starting with version 1.6 of the XI sender adapter, which is available with the 28-October-2018 version, you have the option to define size restrictions for inbound processing. In the Conditions tab adjust the default values for the Body Size, if required:
Configure Transaction Handling
You need to configure the correct transaction manager in the integration process for transactional end-to-end processing. Our process does only contain an XI Sender and no data store flow steps or JMS adapters; so we don’t need a specific transaction handler. Select the integration process and switch to the Processing tab. In Transaction Handling drop down select Not Required.
More details about the different transaction handling options and existing limitations are described in the blog ‘How to Configure Transaction Handling in Integration Flow’.
Configure the Outbound Channel
Configure the integration flow with the outbound channel required by your scenario. For the sample scenario we use the sftp adapter and send the message to a directory on the SFTP server. But you can use any other adapter as well.
Deploy the Integration Flow
Now you can deploy the integration flow. Afterwards, check if the integration flow was started successfully in the Manage Integration Content monitor.
Get the Endpoint URL to be called
To be able to call the integration flow from the sender system, you need to know the endpoint URL to be used. For this check the Endpoints tab in the Manage Integration Content monitor. There the URL is shown and can be copied to the clipboard using the Copy option.
Configure the Sender System to Send the XI Message to Cloud Integration
The next step is to configure the sender backend to send the message to the Cloud Integration tenant. You need to configure the Integration Engine in the backend using transaction SXMB_ADM -> Integration Engine Configuration.
Configure Local Integration Engine
If you did not already configure the local Integration Engine executing the XI Receiver blog you need to configure the Local Integration Engine in the backend using transaction SXMB_ADM -> Integration Engine Configuration. Here the Role of the Business System defined should be Application System.
Configure SLD
To send XI messages you need to make sure the SLD is configured correctly. Execute transaction SLDCHECK in the application backend to verify this.
Define RFC Destination with Integration Server URL
There are different options available to define the integration server URL to send messages to via XI 3.0 protocol, either define it for the whole backend system or interface-specific. You can find detailed information on this in the online help for the application system you are using.
To not interfere with any other scenarios in the backend, we will use the interface-specific configuration and define the XI endpoint URL to be called only for a specific interface.
Use transaction SM59 to create a new HTTP Connection to an external server. Define the target host and path prefix according to the endpoint URL you copied from the Endpoints tab. The path prefix is composed according to the following pattern: /cxf/<address field in XI sender adapter>.
In the Logon & Security tab, define SSL and the SSL Client Certificate to be used for the connection. If Basic Authentication is to be used, enter User and Password.
Test the connection using the Connection Test button. You should get an HTTP 500 with the response that an internal error occurred with reference to an MPL. This is because we did not send a payload along with the request. You should not get any SSL error or HTTP 40* errors, in this case you need to check the certificate setup and potentially the user-certificate mapping in the Cloud Integration tenant or the assignment of the role ESBMessaging.send in Cloud Platform role management for the login user. More details about setting up the inbound authentication can be found in the blog ‘How to Setup Secure HTTP Inbound Connection with Client Certificates’.
Define Sender/Receiver Definition
Use transaction SXMSIF to define a sender/receiver definition for the interface you want to use. Configure * for Service to make sure the configuration is valid for all sender and receiver services.
In the sample scenario we use the interface FlightBookingOrderConfirmation_Out from namespace from the PI Demo Examples as we want to send the confirmation after we got the flight booking configured in the scenario using the XI receiver adapter. But as already mentioned, you can also use any other interface available in your backend to try this out.
Activate Interface-Specific Endpoint
Use transaction SXMB_ADM -> Integration Engine Configuration –> Specific Configuration to define a new parameter with the following settings:
- Category: RUNTIME
- Parameters: IS_URL
- Subparameters: Select the Sender/Receiver ID you defined in the last step.
- Current Value: dest://<name of the RFC destination you defined in SM59>
With this, the system will send XI proxy calls for the interface FlightBookingOrderConfirmation_Out to the Cloud Integration tenant.
Test Sending a Message to the Cloud Integration Endpoint
Now we can test the configuration. The easiest way to do this is using transaction SPROXY. In SPROXY select the Service Interface FlightBookingOrderConfirmation_Out in namespace. In the menu, choose Proxy -> Test. In the Test Service Consumer dialog leave the settings as they are and select Execute:
A screen with a sample test message is opened, press Execute and afterwards select Extras -> Trigger Commit Work. The request is sent to the Cloud Integration tenant. You can now monitor the processing as described in the next section.
Check in transaction SXMB_MONI that the message was sent successfully. Furthermore, check in Cloud Integration monitoring that the two message was processed. More details about the monitoring in Cloud Integration can be found below in the Monitoring section.
Test the Whole E2E Scenario
If you started with the flight booking scenario using the XI receiver adapter, you can now test the whole end-to-end scenario. Trigger the scenario by putting a file into the sftp folder and check the monitoring in your Cloud Integration tenant and in transaction SXMB_MONI in the backend.
In Cloud Integration monitoring you should find two message processing logs for the XI receiver integration flow sending the asynchronous request to the backend and one message processing log for the XI sender integration flow receiving the asynchronous response message:
In transaction SXMB_MONI there should be two XI messages; one for the request received and one for the response sent:
Monitoring
To check the processing in Cloud Integration detail, you can use the monitoring tools provided by Cloud Integration.
Message Monitoring
Message processing can be checked in detail in the section Monitor Message Processing. Select the message you sent and check the processing status. There is one message processing log for the whole processing, containing the inbound messaging that saves the message to the data store/JMS queue and the outbound processing from the data store/JMS queue and sending it to the receiver system.
In the event of a failure the message will go into status Retry. The message will then be retried as configured in the XI sender channel. The detailed error information is available under the link Message Processing Log.
Monitor XI Message ID in Idempotent Repository (For Scenarios using the Exactly Once Option)
For the monitoring of the already received message ID, which are persisted in the Idempotent Repository, an OData API is available. You may use it to find out if a specific XI message was already processed.
For example, you can use the Postman tool to call the OData API for the Idempotent Repository component.
Use the following URL to retrieve the source ID for an XI message ID:
https://<tmn-server>/api/v1/IdempotentRepositoryEntries?id=<xi-message ID>
example:
The call returns 202 if the XI message ID was already processed or 404 if it is not contained in the Idempotent Repository. In case the entry exists in the Idempotent Repository, the Creation and Expiration Times are provided.
Data Store Monitor (For Messages Stored in Data Store)
You can find the messages that are stored temporarily during processing in the Data Stores tile in the Manage Stores section in the monitoring dashboard. During successful processing, the messages are removed immediately after the processing was completed. In case of an error, the messages are kept in the data store to trigger the retry from there.
The used data store name is auto-generated according to the following pattern: <participant name>_< XI channel name>. Below the data store name the <integration flow name>/XI is shown. In the monitor all messages are listed with a status. Two statuses exist:
- Status Waiting means that the message waits for consumption.
- Status Overdue indicates that the message was not consumed and processed in the due time, which is 2 days in case of the XI adapter.
In the monitor the Message ID is shown as a link. If you select the link the respective message processing log is opened in the message monitor.
Note that data stores that do not have messages persisted at the time the monitor is opened are not shown in the monitor. This is because data stores are created on the fly in message processing if required and removed after the last message was removed from data store.
Lock Monitor (For Messages Stored in Data Store)
In case the message was involved in several node outages, for example caused by an out-of-memory, the message gets locked in the Lock Monitor. Those messages are not retried any longer. Notice that you will probably not see any entry in this monitor during testing your sample scenario, as this entry will only be permanently available in case of a runtime node outage. So, see this section more as additional information.
The entry will be generated with the following parameters:
- Component: XI
- Source: XI_<integration flow name>.<participant name>_<channel name>
- Entry ID: corresponds to the ID shown in data store monitor
You need to check if the message was the root cause if the error, maybe it is just too large to be processed. Then you need to ask the sender to send the data in smaller messages. Afterwards you can delete the message in the Data Store monitor and then also delete the lock in the Manage Locks monitor. If you are confident that the message did not cause the outage you can release the lock in the Manage Locks monitor by using the Release button.
Queue Monitor (For Messages Stored in JMS Queue)
You can find the messages that are stored temporarily during processing in the Message Queues tile in the Manage Stores section in the monitoring dashboard. During successful processing the messages are removed immediately after the processing was completed. In case of an error the messages are kept in the JMS queue to trigger the retry from there.
The used JMS queue name is auto-generated according to the following pattern: XI.<Integration Flow Name>.<Channel Name>.<Guid>. In the monitor all messages are listed with a status. Four statuses exist:
- Status Waiting means that the message waits for consumption.
- Status Failed indicates that the last processing or retry of the message ended with an error.
- Status Blocked comes into play if dead-letter queue is configured in XI channel and if the message was involved in several node outages and so is taken out of processing. See dead-letter queue handling above.
- Status Overdue indicates that the message was not consumed and processed in the due time, which is 2 days in case of the XI adapter.
You can see the number of retries that have already been executed and the time of the next retry. You can also trigger an immediate retry of the message or delete specific messages if you no longer want them to be processed.
Queue Deletion
If you do no longer need a specific queue(for example if you un-deploy the integration flow), you have to delete the queue manually in the Queue Monitor if the queue contains messages. The queue cannot be deleted automatically because this could cause data loss. Only the scenario owner knows if the messages can
To find unused queues in the monitor you may use the checks described in the blog ‘Checks in JMS Message Queue Monitor’.
JMS Resource and Size Limits
If you are using JMS for temporary storage you need to keep in mind that the connected JMS messaging instance, that is used has limited resources. The Enterprise or Messaging License sets a limit on the queues, storage and connections that you can use in the messaging instance. The limits are described in more detail in the blog ‘JMS Resource and Size Limits‘.
Important Considerations and Limitations
When using the XI adapter, there are some very important facts you need to be aware of:
Using the Headers set by the XI Sender Adapter Requires to Whitelist the Required Headers
If you want to use the headers set by the XI Sender adapter in the integration flow configuration you need to add the required headers in the Allowed Header(s) field in the Runtime Configuration of the integration flow. For details check the blog Configuring Scenario with XI Sender handling Multiple Interfaces.
Changing Storage Between Data Store and JMS May Cause Data Loss:
As the adapter stores messages for retry in case of an error either in a JMS queue or in the Data Store, you need to keep in mind that changing this setting for an already running scenario may cause loss of data. This is because there can still be messages in the old storage, which this setting.
Changing Participant or Channel Name May Cause Data Loss:
As the data store or JMS queue name for retry is generated based on the participant and channel name, a new data store or JMS queue would be generated if you change one of those names. As there can still be messages in the old storage, these messages participant or channel name. With the 30-September-2018 update you have the option to move all messages from one JMS queue to another, if required. This option would help you in case you urgently need to change the channel or participant name or if you have done it without knowing the constraint that a new queue would be generated.
To move messages from one JMS queue to another use the Message Queues monitor. In the single line actions for the ‘old’ queue select the Move action:
In the Move Messages dialog select the newly generated queue and choose Move. All messages of the old queue are now moved to the new one.
Note that there is currently no such move option for the data store. The blog will be updated as soon as this is available.
Wrong transaction handling configuration may cause inconsistent data and/or data loss:
The two storage options, JMS Queue and Data Store, require different transaction handlers. Because of this it is crucial that you define the correct transaction handler:
- JMS Queue: If a JMS Queue is used for temporary storage in the XI receiver adapter and the XI adapter is used in a sequential multicast or splitter pattern you need to configure the Transaction Handling as Required for JMS.
- Data Store: If the Data Store is used for temporary storage in the XI receiver adapter and the XI adapter is used in a sequential multicast or splitter pattern you need to configure the Transaction Handling as Required for JDBC.
- For the XI sender adapter no transaction handler is required.
- For the XI receiver adapter no transaction handler is required if the XI adapter is not used in a sequential multicast or in a split scenario.
- As there is no distributed transaction support in Cloud Integration you cannot combine JMS and JDBC transactions. This means that you cannot ensure transactional behavior in scenarios using the XI receiver adapter with JMS storage in multicast scenarios together with flow steps that need a JDBC transaction handler, like for example Data Store or Write Variables.
More details about the transaction handling configuration and the constraints in configuration can be found in blog ‘How to configure Transaction Handling in Integration Flow‘.
The XI adapter currently has some limitations:
- No explicit retry handling via Retry Header in Exception Sub-Process possible possible yet. Solved with the 2nd-September-2018 update, see blog Configuring Explicit Retry in Exception Sub-Process for XI Adapter Scenarios.
- MPL status stays in Retry even if the message is deleted from JMS queue or data store. Nevertheless in runtime no retry is executed anymore.
- XI receiver adapter is currently neither allowed in Request-Reply nor in Send step. – Solved with the 28-October-2018 update, see blog Usage of XI Adapter in Send and Request-reply Step.
- Acknowledgements are not supported
- Attachments are not supported
- ExactlyOnceInOrder (EOIO) is not supported.
The blog will be updated regularly with the new features.
Hi Mandy,
thanks a lot for this perfect blog. I’m sure many customers have been waiting for this feature. I have one question regarding the sytstem setup.
Suppose a company has SAP PO and SAP CPI and only wants to set up the RFC connection to the CPI once in addition to the PO destination. I understand that i can decide which middleware should be used using sender/receiver definitions.
But how do we have to specify the CPI endpoint in the RFC destination (is there one general URL for all CPI service interfaces like it is in PI /XISOAPAdapter/MessageServlet?ximessage=true) and how do we distinguish between the different serviceinterfcaces on the CPI side?
Thanks for some more information on how to deal with connectivity setup using two middleware systems in a big interface landscape.
Best Regards,
Manfred
Hi Manfred,
no, there is no central inbound URL for the XI service in CPI. You can configure this as you like, you can have one central XI sender channel in one integration flow that would receive all XI inbound calls and then do routing to different processes/flows based on the payload received.
Or you create different XI sender channels having different URL addresses and then use the interface specific configuration in the backend to call those different URLs.
Best regards,
Mandy
So we seperate RFC destination maintained for every iflow receiver in HCI ?
Is SAP putting anywork into alternative way of configuring connections ? G TYPE connections with the end point URL is much the same as standard SOAMANAGER and SOAP connections, Id love to use the XI adapter but Ill end up with 100 distinct RFC connections – now change the password for the service user (no certificates).
Hello Richard,
you mean XI sender adapter, right?
As stated above you can configure your scenario in a way that you have only one XI sender channel. Then you have to configure the routing based on the payload/interface to further process the message. There are no plans at the moment to change this architecture in Cloud Integration.
Best regards,
Mandy
Thanks Mandy, I implemented a mini Router using XI adapter and Process direct, with some groovy to extract message type and route to the correct end point. I now have a single end point that dynamically routes to the correct integration flow with no other backend configuration.
Great, thank you for the info.
Hello Richard,
I am building the router on CPI for the same purpose. Could you please through some light on how you are dynamically generating the processdirect adapter target URL? I would like to use sender business system, interface and namespace just the way PI uses them in an ICO. However, I see that, those headers are not propagated into the iFlow exchange properties or as header. Any suggestion would be appreciated.
VJ
Hi Mandy
This XI 3.0 protocol support is a much needed functionality for many existing SAP customers that have invested heavily into SAP’s previous de-facto middleware, PI/PRO.
A key feature of this is the single entry point into the middleware for all different interfaces (as you can see from the other comments here). While we can implement a custom router to achieve this, it would be great if such capability be included out-of-the-box. This will prevent unnecessary custom development/configuration each time we need to include a new interface – imagine a company like ours needing to configure such a router for 100+ interfaces that we currently have on PI.
If I’m not mistaken, the AS2 sender adapter has a similar capability, where there is only a single fixed endpoint URL.
Appreciate it if you can bring this feedback/request back to the product development team for it to be included in the roadmap. This will greatly enhance the capabilities of CPI as well as help in its adoption into many company’s landscape.
Thanks and best regards,
Eng Swee
I will bring this request into our development planning, but cannot comment if it will make it to the roadmap.
Best regards,
Mandy
Thanks Mandy, every bit of assistance is much appreciated.
Hi Mandy,
first I want to thank to your great article! I wait now already on new CPI reading material from you 🙂
I want to know about the runtime behaviour of the retry logic in CPI message monitor regarding an IFlow with XI sender adapter in combination with QoS EO. So I built up a PoC XI-to-Mail-IFlow as you can see on the following picture:
As I understand it (from your above “Data Store” section), the PoC IFlow should only retry the message processing two times until it changes the state from “retry” to “error”.
However, when I run a test (provoked error on receiver mail adapter) the retry mechanism repeats in an infinite loop even though the “maximum retry interval” parameter is set.
It seems to me that this parameter doesn’t work.
Is the illustrated XI adapter of my PoC maybe incorrectly configured or could that be a bug?
Best Regards,
Toby
Hello Tobias,
as the parameter says this is only the maximum retry interval meaning the exponential backoff will not increase it further. But the retry will still continue. See also the description of the field and the tooltip.
Taking your sample:
Meaning the 2 minutes is the maximum interval between two retries.
If you set this to 60 minutes, the processing would look like this:
Currently there is no option to stop the retry after a specific number of retries (see also the limitations chapter about explicit retry configuration in exception sub-process). But I can already tell you now that this option will come with the September update in about 5 weeks. I will post a new blog about this feature shortly before it is available.
Best regards,
Mandy
The explicit retry configuration will be available with the 2nd-September-2018 update, see blog Configuring Explicit Retry in Exception Sub-Process for XI Adapter Scenarios.
BR,
Mandy
Hello Mandy,
Thanks for this blog. I an new with HCI and I a little confuse with this.
In a escenario SAP ECC->SAP PI/PO using a XI adapter, first in SAP PI/PO we create the objects Data Type, Message Type an Service Interface and Then in SAP ECC in transacction SPROXY we generate the proxy object with the structure define in the message type.
But in this scenario SAP ECC->SAP HCI using a XI adapter, where do you define the stucture and the service interface to generate in SPROXY transaction?
Thanks,
Regards,
Leonel
There is no ESR or similar tool to create interfaces and generate proxies available yet in Cloud integration. You still have to use the known ESR for this, you can than import the interfaces and mappings into Cloud Integration.
Best regards,
Mandy
Hi Mandy,
Great blog, thank you so much, this really helps. I do have one question, hope you may help.
There is the step to configure the SLD, but I dont have PO or SolMan on my landscape this is a single ECC system on HEC, I would like to leverage XI adapter, how can you configure the SLD?
Any advise.
Best regards,
Ricardo
Hello Ricardo,
here you find more details about SLD and it’s setup:
Best regards,
Mandy
Thanks Mandy, but if I understand correctly I would need to install a SLD, correct?
Currently this would be an impact on costs, basically, is there a way to do fix setup? because there is no SLD in the landscape.
Is there a scenario where this may work without an SLD? Cause at the moment I dont have either the component or the system to support it.
Thank you.
Best regards,
Ricardo
Hello,
actually this would not be a fix in Cloud Integration side. The problem is that the XI engine in the backend requires the SLD, not the Cloud Integration tenant. So, you may contact the PI/PO colleagues for their suggestion. You may open a ticket on BC-XI-IS-IEN.
Best regards,
Mandy
Thank you Mandy, I really appreciate your help.
Best regards,
Hi Mandy,
Appreciate your blog and it really helped in configuring many proxy scenarios and migrating the existing PI interfaces to CPI easily.
But now we are facing a problem with “Proxy with attachments” , when ever there is a message with application attachment in the request ; we observe that in the data store the attachment is being lost and only the main payload is being stored. We need the Application attachment as well ( where we are converting attachment data to main payload in our scenario)
Does the XI sender adapter supports Attachments? If yes, could you please support us if we are missing anything!!
Hello,
The XI adapter currently does not support attachments (I added it now also to the limitations section), neither does the data store.
Best regards,
Mandy
Hi Mandy,
Thank you for your quick response.
One good news though , the XI message along with application attachments is working fine with JMS Queues though.
We are testing multiple cases as well and will post if any issues.
Thanks & Regards,
Ramanji | https://blogs.sap.com/2018/06/04/cloud-integration-configuring-scenario-using-the-xi-sender-adapter/ | CC-MAIN-2019-13 | refinedweb | 5,522 | 60.04 |
When using lint(1), remember that not all problems result in lint(1) warnings, nor do all lint(1) warnings indicate that a change is required. Examine each possibility for intent. The examples that follow illustrate some of the more common problems you are likely to encounter when converting code. Where appropriate, the corresponding lint(1) warnings are shown.
Since
ints and pointers are the same size in the ILP32 environment,
a lot of code relies on this assumption. Pointers are often cast to
int or
unsigned int for address arithmetic. Instead, pointers could be cast to
long because
long and pointers are the same size in both ILP32
and LP64 worlds. Rather than explicitly using
unsigned long, use
uintptr_t because it expresses the intent more closely and makes the code more
portable, insulating it against future changes. For example,
char *p; p = (char *) ((int)p & PAGEOFFSET);
produces the warning:
warning: conversion of pointer loses bits
Using the following code will produce the clean results:
char *p; p = (char *) ((uintptr_t)p & PAGEOFFSET);
Because
ints and
longs were never really distinguished
in ILP32, a lot of existing code uses them indiscriminately while implicitly or explicitly
assuming that they are interchangeable. Any code that makes this assumption must be
changed to work for both ILP32 and LP64. While an
int and a
long are both 32–bits in the ILP32 data model, in the LP64 data model, a
long is 64–bits. For example,
int waiting; long w_io; long w_swap; ... waiting = w_io + w_swap;
produces the warning:
warning: assignment of 64-bit integer to 32-bit integer
Unintended sign extension is a common problem when converting to 64–bits. It is hard to detect before the problem actually occurs because lint(1) does not warn you about it. Furthermore, the type conversion and promotion rules are somewhat obscure. To fix unintended sign extension problems, you must use explicit casting to achieve the intended results.
To understand why sign extension occurs, it helps to understand the conversion rules for ANSI C. The conversion rules that seem to cause the most sign extension problems between 32-bit and 64-bit integral values are:
Integral promotion
A
char,
short, enumerated type, or bit-field, whether signed or unsigned,
can be used in any expression that calls for an
int. If an
int can hold all possible values of the original type, the value is converted
to an
int. Otherwise, it is converted to an
unsigned int.
Conversion between signed and unsigned integers
When a negative signed integer is promoted to an unsigned integer of the same or larger type, it is first promoted to the signed equivalent of the larger type, then converted to the unsigned value.
For a more detailed discussion of the conversion rules, refer to the ANSI C standard. Also included in this standard are useful rules for ordinary arithmetic conversions and integer constants.
When compiled as a 64-bit program, the
addr variable in the following
example becomes sign-extended, even though both
addr and
a.base are
unsigned types. the signed
and unsigned integer promotion rule. The sign extension occurs when it is converted
from an
int to a
long.
When this same example is compiled as a 32-bit program it does not display any sign extension:;
Extra padding may be added to a structure by the compiler to meet alignment requirements as long and pointer fields grow to 64 bits for LP64. For both the SPARCV9 ABI and the amd64 ABI, all types of structures are aligned to at least the size of the largest quantity within them. A simple rule for repacking a structure is to move the long and pointer fields to the beginning of the structure and rearrange the rest of the fields—usually, but not always, in descending order of size, depending on how well they can be packed. For example,
struct bar { int i; long j; int k; char *p; }; /* sizeof (struct bar) = 32 */
For better results, use:
struct bar { char *p; long j; int i; int k; }; /* sizeof (struct bar) = 24 */
The alignment of fundamental types changes between the i386 and amd64 ABIs. See Alignment Issues.
Be sure to check unions because their fields might have changed sizes between ILP32 and LP64. For example,
typedef union { double _d; long _l[2]; } llx_t;
should be:
typedef union { double _d; int _l[2]; } llx_t;
A;
For some compilation modes, the compiler might assume the type
int for
any function or variable that is used in a module and not defined or declared externally.
Any
longs and pointers used in this way are truncated by the compiler's
implicit
int declaration. The appropriate
extern declaration
for a function or variable should be placed in a header and not in the C module. The
header should then be included by any C module that uses the function or variable.
In the case of a function or variable defined by the system headers, the proper header
should still be included in the code.
For example, because getlogin() is not declared, the following code:
int main(int argc, char *argv[]) { char *name = getlogin() printf("login = %s\n", name); return (0); }
produces the warnings:
warning: improper pointer/integer combination: op "=" warning: cast to pointer from 32-bit integer implicitly declared to return int getlogin printf
For better results, use::
#include <unistd.h> #include <stdio.h> int main(int argc, char *argv[]) { char *name = getlogin(); (void) printf("login = %s\n", name); return (0); }
In the LP64 environment, sizeof has the effective type of
size_t which is implemented as an
unsigned long. Occasionally, sizeof is passed to a function expecting an argument of type
int,
or is assigned or cast to an
int. In some cases, this truncation might
cause loss of data. For example,
long a[50]; unsigned char size = sizeof (a);
produces the warnings:.
The); | http://docs.oracle.com/cd/E19120-01/open.solaris/816-5138/6mba6ua5e/index.html | CC-MAIN-2014-52 | refinedweb | 975 | 58.21 |
Lately, I had people asking how can they contribute to open-source projects when the codebase is large, or issues are taken, or good first issues seem difficult.
Initially, I've faced these questions as well and In this article, I will talk about how we can explore repositories, find the right issues to work on, and I will also try to answer some of the questions I just mentioned. 🐨🌻
Let's goooo 🎉
Table of Content
- Finding the Right Repository
- Finding the Right Issue
- Exploring Code
- Some Useful Links
1. Finding the Right Repository 🕵
Contribute to something you use or find something that excites you and play around it before trying to contribute.
I will highly suggest using the tool/library/website, before contributing to it. This will give you a nice overview of what it does and how it works.
If you're uncomfortable with the process of making PR, you can first contribute to First Contributions Repository. You have to add your name to the list and send a PR! They have a nice guide to explain the process.
2. Finding the Right Issue 📚
In the issues section, you will find issues that have
good first issue tag. Though it is not necessary, it is usually a sign from maintainers that 'hey these issues are relatively easy to tackle'. If you find any other issue that excites you more, go for it!
I will suggest trying to find issues related to documentation since they will be easier to get started but if you couldn't find such issues, that's ok as well you can pick whichever you like. As you get comfortable with the repository, you can go on picking more challenging issues.
And before we move forward, I know you might've heard this a lot and I am probably the 1000th person saying this but
🎉 EVERY. CONTRIBUTION. MATTERS 🎉
Even a spelling fix in documentation is a huge help to maintainers and you should totally be proud of such contributions!
Here's something I am proud of:
There was an extra bracket in the editor guide of DEV.to and I removed it :D
PR:
Q. Every issue is taken, how do we find one?
A lot of times in popular open-source projects, you will find that most of the good first issues are taken and someone is already working on them. In this case, you can join their chat channels. Projects use Slack, Discord, Spectrum, GitHub Discussions, or other chat channels where you can ask for help. In those chat channels, you can drop a message asking for help in finding issues. Maintainers will then help you in finding an issue for you.
Q. Did find an issue but it seems difficult...
This is very normal and even if you are experienced in contributing, you will likely find issues difficult in the first look when you're trying to contribute to a new organization.
You can always ask for help in comments of issues. Maintainers will then help you debug the problem and can point you to the right files that need changes but try exploring it yourself before asking for help.
3. Exploring Code 🤠
Before you start exploring the code, always read CONTRIBUTING.md file in the repository (If a repository does not have CONTRIBUTING.md, whoop whoop 🎉 That's your chance to send a Pull Request that adds CONTRIBUTING.md). It usually has a local setup guide and other information that you may need for contributing. You can either set it up locally and then explore, or explore on the GitHub itself and then do a local setup to make changes.
I prefer exploring locally since you get to play around and execute the code.
Awesome so now you've,
🗸 Decided the issue that you want to work on
🗸 Read the CONTRIBUTING.md
Now we exploreeeee yayyyyy!!! oh.. but wait..
Q. CODEBASES ARE HUGEE! How can we understand the whole codebase?
Fun fact, You don't have to understand the whole code 🎉
You will only have to care about the code that is related to the issue you've chosen.
3a. Finding the right files in the code.
Tip: In VSCode, you can CTRL + SHIFT + F to find something in a complete project or On GitHub, you can use the search bar to find the related code.
In websites/frontend repositories
If the project you're contributing to is a website, you can search for the words you see on the interface. E.g. If you want to contribute to the navigation bar of DEV, you can search for "Write a Post" button.
If it is not a website you can start finding the related functions by following the imports starting with an entry file.
In libraries, NPM Packages, and CLIs
In NPM packages, you would find package.json that has
main attribute, the value of the
main is the file that gets imported when you import/require that NPM package.
If you're contributing to a CLI, you would find
bin in package.json that points to the file which is executed when you run a CLI command.
Mono-repos
Some projects like React, Gatsby, Next follow a mono repo. They have all the related projects in the same repository. In such projects, you would most probably find a folder called
packages on root level and inside the
packages you would find a folder with the name of the npm library (e.g
packages/react,
packages/next,
packages/gatsby).
If you see the package.json file inside these packages, you would find the
main key that points to the file which exports the functions that we usually import from these libraries.
Example
If you've used React, we usually import
useEffect and other hooks like this, right?
import { useEffect } from 'react';
Which means the package react must be exporting the
useEffect function 🤔
Let's find out!
As I've mentioned earlier, the mono-repos usually have a
packages folder and inside that there is a package with the name of the NPM library ('react' in this case). So let's go inside
packages/react/ 🚀
Now we want to find the entry file so we will look into
package.json file.
Package.json of React has
{'main': 'index.js'} which means everything that we import from
react package, has to be exported from
index.js. Let's see if it has
useEffect function!
Whoop whoop 🎉 Yes it does!
Now you can follow the imports to that function to find a file that handles useEffect logic.
3b. Projects that require additional knowledge
If you've been building websites and webapps and then see the source code of React, the code will look different. Some repositories require knowledge of few additional topics which you may not come across otherwise.
Some projects are built on top of Abstract Syntax Trees whereas some repositories use a different language/libraries.
It is likely that you will find this code difficult in first look but more than difficult, it is different. It is different from what we JavaScript developers usually come across.
You can spend some time playing around the codebase and if you get stuck, you can always ask questions to the maintainers.
Some Useful Links
GitHub Repositories for Initial Contributions
- First Contributions GitHub Repository - This is great to actually practice sending Pull Request (Fun Fact: I too started here :D)
- Knaxus GitHub Organization - The aim is similar to first contributions but they will let you contribute to actual coding projects.
Resources to learn git and GitHub
- YouTube Video, "Contributing to Open Source on GitHub for Beginners" by Kent C. Dodds
- YouTube Video, "git_basics - The basics that you need for Git & GitHub!" by Harsh Kapadia
- Resources to learn git by GitHub
Thank you for reading this 🎉 If you have any questions about git, GitHub, or contributing, you can ask them in comments or reach out to me on my Twitter DMs @saurabhcodes.
🌻🌻🌻🌻
Discussion (15)
Great post, Saurabh!
I've recently started contributing to OS more frequently and have found a few really friendly repos. My favourite being blitz! a fullstack react framework that aims to be rails for react
If you're familiar with react, next.js, and full-stack concepts, and looking for a super friendly place to start contributing to OS check it out! the whole team is super welcoming and has tonnes of good-first-issue's!
This is amazing! Thanks for sharing :D
One thing many engineers forget when contributing projects (mainly open source) is that behind the project we have people.
We don't know the people who are on the other side (project maintainers), generating the need for communication to be clear, and we don't assume that other people have the same knowledge as us (nobody knows what we have inside our head), even some concepts being obvious I made clear in communication (issue, pull request and so on). Finally, I have no attachment to code - code is a means to get to the solution of a problem.
When we are on the project maintainer's side: consider each (every) contribution as the person's best possible contribution, the contributor has left his or her tasks to contribute to a project that is not his or her own, try to understand why the person had an affinity to the project - this will help him or her to create a community (he or she will help you maintain the project)
good contribution friends, I'm passionate about Open Source project \o/
Yes yes totally agree!
Thank you very much for sharing this awesome post! Contributing to open-sourced projects really is the way to go and I absolutely share your ideas. :))
that looks great! I will give it a read. thank you for sharing!
Thanks, Saurabh for the valuable knowledge. I want to know about code reviews. I don't know how to do code reviews in Github?
Thank you and yes that's a great question, I'll try to write the steps here:
File Changestab where you can see diff of the changes made by the PR.
Review Changesbutton, which has three options. Comment (for casual comments), Approve (to approve the PR), Request Changes (to request any changes from the author of the PR).
Process of Requesting Changes:
+sign left to every line of code in the changes
Finally, your requested changes will be rendered as
Thank you and let me know if you have any other questions
Got it finally, what are code reviews and how to do it, 😃 😃 . Thanks for writing a long comment. I have a question that Is code review only done by repository owner/contributor? or like someone else can do code review in someone's repository. Like If I want to do code review in someone's repo and I have not made any pull request or i am not a contributor to that repo. Then can I do code review?
Yes you can do that as well. In the PR conversation it will be marked with a grey check mark and the owner's review will be marked with a green check mark.
That's great. Thank you
These comments could very well become a standalone article :)
This really is an essential part of oss contribution! I was always afraid of this part in the beginning and probably a lot more I have to know too! This could be a part of the original post as well.
True, I remember contributing to your DEV Widget on a small bug like converting the username to lower cases
yes yes thank you so much and it was a big bug so that contribution was super helpful! thank you so much | https://practicaldev-herokuapp-com.global.ssl.fastly.net/saurabhdaware/a-guide-for-contributing-to-any-open-source-javascript-project-ever-hi | CC-MAIN-2021-25 | refinedweb | 1,956 | 70.63 |
Luke Daly <Luke.Daly at newcastle.edu.au> wrote: >Is there a way i can scan all lists for an email address? the scenario >is i need to remove a user from all our lists (theres lots of them) in >one go. or at the least scan all lists for an email address. I have this script that runs via a cron each hour to produce a list of all Mailman list subscriptions: Mailman# cat mailman_who.exec #!/bin/csh # shell script to extract the subscriber addresses from each list. # 01Feb07 1102AM Barry Finkel # 02Feb07 0821AM Added another "echo" line. # 16Mar07 0940AM Changed "destfileold" to "$destfileold". # Changed "/destfile" to "/$destfile" # 16Mar07 1026AM Changed the format of the destination file # 20Jul07 1028AM Added code to detect a list with no subscribers set destdir = /etc/mailman/list_subscribers set destfile = list_subscriptions set destfilenew = list_subscriptions_new set destfileold = list_subscriptions_old date > $destdir/$destfilenew # We assume that everything in this directory is a listname # subdirectory. If this is not the case, then we have to parse the # "ls -al" output and remove the "." and ".." entries. # echo "----------" >> $destdir/$destfilenew foreach list (`ls /var/lib/mailman/lists`) # In the following do we want "--fullnames"? /usr/lib/mailman/bin/list_members -o $destdir/$list $list if ( -z $destdir/$list ) then echo "NO_SUBSCRIBERS" > $destdir/$list endif cat $destdir/$list | \ sed "s/^/$list /" \ >> $destdir/$destfilenew echo "----------" >> $destdir/$destfilenew end if ( ! -z $destdir/$destfilenew ) then mv $destdir/$destfile $destdir/$destfileold mv $destdir/$destfilenew $destdir/$destfile endif Mailman# I use it to see to what lists a given e-mail address is subscribed. I have not had the need to automate unsubscribes. ---------------------------------------------------------------------- | https://mail.python.org/pipermail/mailman-users/2007-November/059066.html | CC-MAIN-2017-17 | refinedweb | 266 | 55.44 |
There are several different APIs for handling Types in .NET.
Criteria:
For each category I want to call out:
Managed/Unmanaged – is the API managed or unmanaged?
Audience – who uses this API?
Binding – A type is defined within a module. So how does it refer to types in different modules or types that haven’t yet been loaded?
Unloading – can you unload the modules you’re inspecting types in? This is very related to the isolation between the host doing the inspection and the target that’s being inspected.
Generating code – can you use these inspection APIs to generate new code?
Different APIs:
- Metadata: IMetaDataImport and tokens (mdTypeDef).
This is the fundamental API for types in .NET. MSDN has an overview here, and online technical specs are available here.
Unmanaged COM-classic API: This is the low-level unmanaged COM-classic API. You can use COM-interop to import it into managed code, but there are some problems using the metadata APIs from managed code.
Audience: This is what unmanaged tools, such as ILdasm, use; and it forms the basis for describing types in the other unmanaged tool APIs described below. This is pretty much a rocket science API.
Binding: Metadata scopes are explicitly single files and do no resolve across files. Binding is determined at runtime, and since metadata is inspecting raw files and not necessarily executing code, it can’t correctly know how binding across modules will work.
Unloading: Metadata allows inspecting executables without actually executing them or binding them; and so you can unload the files you’re inspecting. You can verify this by loading a file in ildasm and then noticing that the managed dll you’re inspecting is not loaded into the ildasm process.
Generating code: Metadata supports the IMetaDataEmit interfaces for generating new code.
- Reflection: System.Type .
Managed: Reflection is a managed API mostly included the System.Reflection namespace. Unmanaged tools can’t use this (unless they call into managed code, of course).
Audience: Reflection is nicely integrated with languages (eg, C#’s typeof keyword returns a System.Type object) and easy to program against. It’s good for a program inspecting itself. Most tools written in managed code would use this.
Binding: Since Reflection inspects its own process, it knows how the types in other modules could be loaded. Reflection could also eagerly trigger assembly loads to answer binding questions. Ultimately, inspecting via reflection taints the process with the target module being inspected.
Unloading: Currently, the only granularity for unloading managed code is via appdomain unload. Since Reflection actually loads the managed code, it is subject to these restrictions and you must unload the appdomain. This is unfortunately true even for code loaded into the Inspection-Only context.
Generating code: Reflection is very closely tied to Reflection.Emit namespace for generating new code. See an example of emit here.
- Debugging: ICorDebugType.
ICorDebug is the debugging APIs for managed code.
Unmanaged com-classic API: This is an unmanaged COM-classic API, and designed as an extension to the metadata APIs. Although MDbg provides a set of managed wrappers that make it easy to consume from managed code. In .Net 2.0, ICorDebug represents types in the Debuggee as ICorDebugType. Prior to .Net 2.0, it uses ICorDebugClass, which could not represent generics.
Audience: Debugger authors. This is used to inspect types in the debuggee process and is completely isolated fro the debugger process.
Unloading: Debuggers and debuggees are separate processes, so they’re well isolated.
Generating code: The debugging APIs are for debugging existing code, and not targeted at writing new code. As trivia, debugging APIs expose Edit-and-Continue which cooperates extensively with the Metadata APIs to allow debuggers to add and change code on the fly. However, this is not a recommended technique for code generation.
- Profiling: ClassId
The ICorProf APIs supports loading profilers into a CLR process. Profilers are very intimate with the runtime. See comparison of profiler vs. debugging for more details.
Unmanaged COM API: Profilers are unmanaged components that get loaded into the same process as the CLR and receive callbacks directly from the runtime. It’s very coupled to the runtime and thus must be unmanaged code.
Audience: Extreme rocket scientists writing profilers.
Binding: Like debugging, profiling simply describes the current bindings in the process and does not actually force any binding to occur.
Unloading: As of .Net 2.0, neither the runtime nor profilers can be unloaded until the process actually exits. The profiler is inspecting the managed code in the process, which can be unloaded via AppDomain unloading
Generating code: The profiling API supports rejit. See Dave Broman’s blog for more details about writing a IL-rewriting profiler.
Conversions between APIs:
Metadata is the fundamental type description in .NET, so converting between the type APIs will ultimately need to go through metadata. The non-metadata APIs have methods to convert to and from Metadata. For example, reflection exposes the tokens via the MemberInfo.MetadataToken property.
PingBack from
Many of the .NET docs use the phrase "TypeDef or TypeRef". What’s the difference? Both refer to metadata | https://blogs.msdn.microsoft.com/jmstall/2007/03/15/describing-types-in-net/ | CC-MAIN-2016-36 | refinedweb | 851 | 50.43 |
X509_new,
X509_dup,
X509_REQ_to_X509,
X509_free,
X509_up_ref,
X509_chain_up_ref — X.509
certificate object
#include
<openssl/x509.h>
X509 *
X509_new(void);
X509 *
X509_dup(X509 *a);
X509 *
X509_REQ_to_X509(X509_REQ *req,
int days, EVP_PKEY *pkey);
void
X509_free(X509 *a);
int
X509_up_ref(X509 *a);
STACK_OF(X509) *
X509_chain_up_ref(STACK_OF(X509)
*chain);
X509_new()
allocates and initializes an empty X509 object with
reference count 1. It represents an ASN.1 Certificate
structure defined in RFC 5280 section 4.1. It can hold a public key together
with information about the person, organization, device, or function the
associated private key belongs to.
X509_dup()
creates a deep copy of a using
ASN1_item_dup(3), setting the
reference count of the copy to 1.
X509_REQ_to_X509()
allocates a new certificate object, copies the public key from
req into it, copies the subject name of
req to both the subject and issuer names of the new
certificate, sets the notBefore field to the current
time and the notAfter field to the given number of
days in the future, and signs the new certificate with
X509_sign(3) using
pkey and the MD5 algorithm. If
req contains at least one attribute, the version of
the new certificate is set to 2.
X509_free()
decrements the reference count of the X509 structure
a and frees it up if the reference count reaches 0. If
a is a
NULL pointer, no action
occurs.
X509_up_ref()
increments the reference count of a by 1. This
function is useful if a certificate structure is being used by several
different operations each of which will free it up after use: this avoids
the need to duplicate the entire certificate structure.
X509_chain_up_ref()
performs a shallow copy of the given chain using
sk_X509_dup()
and increments the reference count of each contained certificate by 1. Its
purpose is similar to
X509_up_ref(): The returned
chain persists after the original is freed.
X509_new(),
X509_dup(), and
X509_REQ_to_X509() return a pointer to the newly
allocated object or
NULL if an error occurs; an
error code can be obtained by
ERR_get_error(3).
X509_up_ref() returns 1 for success or 0
for failure.
X509_chain_up_ref() returns the copy of
the chain or
NULL if an error
occurs.
AUTHORITY_KEYID_new(3), BASIC_CONSTRAINTS_new(3), crypto(3), d2i_X509(3), PKCS8_PRIV_KEY_INFO_new(3), X509_ALGOR_new(3), X509_ATTRIBUTE_new(3), X509_check_ca(3), X509_check_host(3), X509_check_issued(3), X509_check_private_key(3), X509_check_purpose(3), X509_check_trust(3), X509_CINF_new(3), X509_cmp(3), X509_CRL_new(3), X509_digest(3), X509_EXTENSION_new(3), X509_find_by_subject(3), X509_get0_notBefore(3), X509_get0_signature(3), X509_get1_email(3), X509_get_ex_new_index(3), X509_get_extension_flags(3), X509_get_pubkey(3), X509_get_pubkey_parameters(3), X509_get_serialNumber(3), X509_get_subject_name(3), X509_get_version(3), X509_INFO_new(3), X509_load_cert_file(3), X509_LOOKUP_hash_dir(3), X509_LOOKUP_new(3), X509_NAME_new(3), X509_OBJECT_new(3), X509_PKEY_new(3), X509_policy_check(3), X509_policy_tree_level_count(3), X509_print_ex(3), X509_PUBKEY_new(3), X509_PURPOSE_set(3), X509_REQ_new(3), X509_SIG_new(3), X509_sign(3), X509_STORE_CTX_new(3), X509_STORE_get_by_subject(3), X509_STORE_new(3), X509_TRUST_set(3)
RFC 5280: Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile
X509_new() and
X509_free() appeared in SSLeay 0.4 or earlier,
X509_dup() in SSLeay 0.4.4, and
X509_REQ_to_X509() in SSLeay 0.6.0 . These functions
have been available since OpenBSD 2.4.
X509_up_ref() first appeared in OpenSSL
1.1.0 and has been available since OpenBSD 6.1.
X509_chain_up_ref() first appeared in
OpenSSL 1.0.2 and has been available since OpenBSD
6.3.
The X.509 public key infrastructure and its data types contain too many design bugs to list them. For lots of examples, see the classic X.509 Style Guide that Peter Gutmann published in 2000. | https://man.openbsd.org/X509_new.3 | CC-MAIN-2022-27 | refinedweb | 561 | 55.13 |
The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
A loop enables a programmer to execute a statement or block of statement repeatedly. The need to repeat a block of code arise in almost every program.
There are three kinds of loop statements you can use. They are
In for loop control statement, initialization, condition and increment are all given in the same loop.
#include <stdio.h> int main() { int i; for(i=0; i<10; i++) { printf("%d ",i); } return 0; }
Here, for loop will iterate until the conditional statement at the center of for-loop fails.
In While loop, initialization, condition and increment are all done in different lines.
#include <stdio.h> int main() { int i = 0; while(i<10) { printf("%d ",i); i++; } return 0; }
Here, while condition iterate until the condition inside it become false.
Here, it is same as while loop, but it will execute a block of code once irrespective of condition.
#include <stdio.h> int main() { int i = 0; do { printf("%d ",i); i++; }while(i>10); return 0; }
Though 0 > 10 tends to false block of code following do was executed successfully.
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
We to update you | https://www.2braces.com/c-programming/c-control-loop | CC-MAIN-2017-51 | refinedweb | 229 | 72.87 |
hi,
im looking for something like stringArrayRemoveDuplicates() that works with int / float array. pls help
Remove duplicates from INT/FLOAT array
hi,
global proc int[] intArrayRemoveDuplicates( int $intArr[] ) { int $resuts[]; for( $intAr in $intArr ) { int $isFound = false; for( $resut in $resuts ) { if( $intAr == $resut ) { $isFound = true; break; } } if( $isFound == false ) $resuts[size($resuts)] = $intAr; } return $resuts; }
intArrayRemoveDuplicates( {5, 5, 65, 65, 33, 22, 1} )
global proc float[] floatArrayRemoveDuplicates( float $floatArr[] ) { float $resuts[]; for( $floatAr in $floatArr ) { int $isFound = false; for( $resut in $resuts ) { if( $floatAr == $resut ) { $isFound = true; break; } } if( $isFound == false ) $resuts[size($resuts)] = $floatAr; } return $resuts; }
floatArrayRemoveDuplicates( {1.0, 1.0, 2.5, 3.2, 2.5, 1.0, 58.88} )
Thank You,
nn
nice! could even be more elegant with also useful isInArray functions:
global proc float[] floatArrayRemoveDuplicates( float $array[] ) { float $resuts[]; int $count = 0; for( $item in $array ) if ( !isInFloatArray($item, $resuts) ) $resuts[$count++] = $item; return $resuts; } global proc int isInFloatArray( float $value, float $array[] ) { for ( $item in $array ) if ( $item == $value ) return true; return false; }
Given the limited precision of floats, the == operator on float isn’t always what you want. Adding an optional tolerance value might be useful. I feel like there’s something to that effect already in MEL somewhere, but I can’t recall it.
Edit: Ah yes:
int equivalentTol(float $a, float $b, float $tol)
Examples:
equivalentTol(0.0, 0.0005, 0.001); [i]// Result : 1 //[/i] equivalentTol(0.0, 0.005, 0.001); [i]// Result : 0 //[/i]
hmm … true but I’d rather implement that in an additional function to keep the real thing slim.
maybe like:
global proc float[] floatArrayRemoveDupTol( float $array[] , float $tol ) { float $resuts[]; int $count = 0; for( $item in $array ) if ( !isInFloatArrayTol($item, $resuts, $tol) ) $resuts[$count++] = $item; return $resuts; } global proc int isInFloatArrayTol( float $value, float $array[], float $tol ) { for ( $item in $array ) if ( equivalentTol($item, $value, $tol) ) return true; return false; } floatArrayRemoveDupTol({0.1, 0.10001, 0.2, 0.23}, 0.03); // Result: 0.1 0.2 //
floatArrayRemoveDupTol({0.07, 0.1, 0.04}, 0.03); floatArrayRemoveDupTol({0.04, 0.1, 0.07}, 0.03); // Result: ??? //
i just want to say that the method might be not accurate but it has not to depend on order of array items.
the solution #1 is to sort a float array before the removing duplicates using tolerance.
but the method i use is to ROUND array values using some precision, and collect only unique after that:
global proc float roundFloat (float $f, float $precision) { $f /= $precision; float $f1 = floor($f); float $f2 = ceil($f); float $v = (($f - $f1) > ($f2 - $f)) ? $f2 : $f1; return ($v*$precision); } global proc int findFloatItem (float $item, float $array[]) { for ($k = 0; $k < size($array); $k++) if ($item == $array[$k]) return $k; return -1; }; global proc float[] uniqueRoundFloatArray (float $array[], float $precision) { float $arr[], $i; for ($item in $array) { $i = roundFloat($item, $precision); if (findFloatItem($i,$arr) == -1) $arr[size($arr)] = $i; } return $arr; // return (sort($arr)); // if you like } uniqueRoundFloatArray ({0.1, 0.10001, 0.2, 0.23}, 0.1); // Result:0.1 0.2// uniqueRoundFloatArray ({0.1, 0.10001, 0.2, 0.23}, 0.01); // Result:0.1 0.2 0.23//
Okay, this is maybe a little bit overdone but it works:
global float $ffArray[] = {1.0, 2.3, 4.4, 99, 2.3, 4, 2.3}; float $sorted[] = python("import pymel.core as pm; list(set((pm.getMelGlobal(\"float[]\", \"$ffArray\"))))"); print $sorted;
@denis: true but I wasn’t asking for a uniquifier with tolerance ;] this just was an example for the closest way to go.
@haggi: wow! But this doesn’t fix the tolerance thing or does it? I’m too scared to try
i wasn’t answering to you. i just tried to warn against using a shortest way rather than the right one.
thats right. You qouted me and then said something seeming unrelated ??? Instead of saying what the problem is. Which I understand as well: A tolerance might not be what you want: You might want to truncate the floats decimal places and check against that. Which is a more understandable way indeed!
I’m just saying that It was not my idea but Keiluns. I never needed a function like that.
But as I think about that I remember a very cool function Nathan gave me and I think giving the number of decimals to keep is even more obvious.:
global proc int nRound(float $input) { return trunc($input + (0.5 * sign($input)) ); } global proc float cutFloat(float $float, int $decimals) { int $factor = pow(10,$decimals); return ((float)nRound($float * $factor) / $factor); } global proc int isInFloatArray( float $value, float $array[] ) { for ( $item in $array ) if ( $item == $value ) return true; return false; } global proc float[] floatArrayRemoveDuplicates2( float $array[] , float $decimals ) { float $resuts[], $f; int $count = 0; for( $item in $array ) { $f = cutFloat($item, $decimals); if ( !isInFloatArray($f, $resuts) ) $resuts[$count++] = $f; } return $resuts; } floatArrayRemoveDuplicates2({0.1, 0.10001, 0.2, 0.23}, 1); // Result:0.1 0.2// floatArrayRemoveDuplicates2({0.1, 0.10001, 0.2, 0.23}, 2); // Result:0.1 0.2 0.23//
The sorting thing I’d leave to the user. Putting a sort() around his stuff wouldn’t be too much to ask I guess
$aFloatArray = {0.1, 0.10001, 0.23, 0.2, 0.79, 0.7, 0.71}; floatArrayRemoveDuplicates2($aFloatArray, 1); // Result: 0.1 0.23 0.2 0.79 0.7 // floatArrayRemoveDuplicates2(sort($aFloatArray), 1); // Result: 0.1 0.2 0.7 0.79 // sort(floatArrayRemoveDuplicates2($aFloatArray, 1)); // Result: 0.1 0.2 0.23 0.7 0.79 //
If you wanted to cheat though:
float $floater[] = {12.0, 15.2, 15.21, 22.0, 86.062, 178.0, 12.01, 22.01}; int $precision = 1; string $feeder = ""; int $i = 0; for( $i = 0; $i <=(`size $floater` - 1); $i++) { $feeder += $floater[$i] + ","; } float $result[] = python("list(set( [ round(float(x), " + $precision + ") for x in [" + $feeder + "] ] ) )"); print $result;
Or you could write it simply as straight python.
Cheers.
Possibly? Have you done any python or mixed MEL and Python?
Python is far faster than MEL. We are talking just straight Python, not nessicarily PyMEL (though there is no need for PyMEL here per se).
I’d write this in python in about two lines using generators and / or lamdas.
Yes, tighter code is not always “faster” code, but in this case, it is, and in most scenarios where you shave cycles pushing values to a stack and popping values off, it is.
Cheers.
possibly you did read the thread carefully. I didn't talk about [b][i]straight Python, [/i][/b]I talked just about that very case...
global proc float[] anotherMethod (float $floater[], int $precision) { string $feeder = ""; int $i = 0; for ($i = 0; $i <=(`size $floater` - 1); $i++) { $feeder += $floater[$i] + ","; } float $result[] = python("list(set( [ round(float(x), " + $precision + ") for x in [" + $feeder + "] ] ) )"); return $result; }
here is result of my method (see above):
$t = `timerX`; for ($k=0; $k<10000; $k++) uniqueRoundFloatArray ({0.1, 0.10001, 0.2, 0.23}, 0.1); timerX -st $t; // Result: 0.39 //
here is isoparmB's method (MEL + Python):
$t = `timerX`; for ($k=0; $k<10000; $k++) anotherMethod ({0.1, 0.10001, 0.2, 0.23}, 1); timerX -st $t; // Result: 2.05 //
so... I was wrong. The second method is[b] more than 5 times slower[/b]. Do I have to explain why, or you can guess yourself? If you are so interested you can check the memory usage as well. Hopefully it will not surprise you too much. If you look at original question you will see that it was the MEL question. And I gave the MEL answer. I don't do a lot of Python coding. But I'll never do the MEL-Python mixing the way as in the sample above. Best,
Again, possibly.
def pythonSort(inputArray, precision): ret = [] for x in inputArray: x = round(x, precision) if not x in ret: ret.append(x) return ret import time start = time.time() inputArray = [0.1, 0.10001, 0.2, 0.23] for k in range(0,10000): pythonSort(inputArray, 1) print time.time()-start
and I took it to a rediculous level. This could be further optimized.
The results:
0.06 seconds.
So, yes, slightly faster.
I know this was a “MEL” question, but it doesn’t have to be. This proc/def could be written in a seperate file and CALLED from MEL.
Just to see the time difference there…
python("import sort"); $t = `timerX`; for ($k=0; $k<10000; $k++) python("sort.pythonSort([0.1, 0.10001, 0.2, 0.23], 1)"); timerX -st $t;
Times out at 0.61 seconds. So, yeah, from MEL -> python it takes 10x longer to push the stack, and pop the stack. We know this.
I was not attacking your solution, or complaining that it should be only ever in python! I have plenty of legacy to maintain in both. I simply wanted to add, for completeness, that MEL and python dont have to be bastard children of each other.
Python IS faster. MEL only solutions do not have to be MEL only solutions. It depends on what you want.
As for memory usage, if someone wanted to write the python as a generator (i.e. via yield) I can guarentee that would reduce overhead since only one element would ever be on the stack.
Cheers
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum. | http://forums.cgsociety.org/t/remove-duplicates-from-int-float-array/1484496 | CC-MAIN-2018-43 | refinedweb | 1,596 | 73.07 |
JavaScript happiness style linter
Opinionated but configurable ESLint wrapper with lots of goodies included. Enforces strict and readable code. Never discuss code style on a pull request again! No decision-making. No
.eslintrc or
.jshintrc to manage. It just works!
Uses ESLint underneath, so issues regarding rules should be opened over there.
JSX is supported by default, but you'll need eslint-config-xo-react for React specific linting.
unicorn,
import,
ava, and more.
$ xo --init.
$ xo --fix.
$ xo --open.
$ npm install --global xo
$ xo --helpUsage$ xo [<file|glob> ...]Options--init Add XO to your project--fix Automagically fix issues--reporter Reporter to use--env Environment preset [Can be set multiple times]--global Global variable [Can be set multiple times]--ignore Additional paths to ignore [Can be set multiple times]--space Use space indent instead of tabs [Default: 2]--no-semicolon Prevent use of semicolons--plugin Include third-party plugins [Can be set multiple times]--extend Extend defaults with a custom config [Can be set multiple times]--open Open files with issues in your editor--quiet Show only errors and no warnings--extension Additional extension to lint [Can be set multiple times]--no-esnext Don't enforce ES2015+ rules--cwd=<dir> Working directory for files--stdin Validate/fix code from stdin--stdin-filename Specify a filename for the --stdin optionExamples$ xo$ xo index.js$ xo *.js !foo.js$ xo --space$ xo --env=node --env=mocha$ xo --init --space$ xo --plugin=react$ xo --plugin=html --extension=html$ echo 'const x=true' | xo --stdin --fixTipsPut options in package.json instead of using flags so other tools can read it.
Note that the CLI will use your local install of XO when available, even when run globally.
Any of these can be overridden if necessary.
if (condition) {}
===instead of
==
The recommended workflow is to add XO locally to your project and run it with the tests.
Simply run
$ xo --init (with any options) to add XO to your package.json or create one.
Then just run
$ npm test and XO will be run before your tests.
You can configure some options in XO by putting it in package.json:
Globals and rules can be configured inline in files.
Type:
Array
Default:
['node']
Which environments your code is designed to run in. Each environment brings with it a certain set of predefined global variables.
Type:
Array
Additional global variables your code accesses during execution.
Type:
Array
Some paths are ignored by default, including paths in
.gitignore. Additional ignores can be added here.
Type:
boolean,
number
Default:
false (tab indentation)
Set it to
true to get 2-space indentation or specify the number of spaces.
This option exists for pragmatic reasons, but I would strongly recommend you read "Why tabs are superior".
Type:
Object
Override any of the default rules. See the ESLint docs for more info on each rule.
Please take a moment to consider if you really need to use this option.
Type:
boolean
Default:
true (semicolons required)
Set it to
false to enforce no-semicolon style.
Type:
Array
Include third-party plugins.
Type:
Array,
string
Use one or more shareable configs or plugin configs to override any of the default rules (like
rules above).
Type:
Array
Allow more extensions to be linted besides
.js and
.jsx. Make sure they're supported by ESLint or an ESLint plugin.
Type:
Object
Shared ESLint settings exposed to rules. For example, to configure the
import plugin to use your webpack configuration for determining search paths, you can put
{"import/resolver": "webpack"} here.
Type:
string
ESLint parser. For example,
babel-eslint if you're using language features that ESLint doesn't yet support.
Type:
boolean
Default:
true
Enforce ES2015+ rules. Disabling this will make it not enforce ES2015+ syntax and conventions.
*ES2015+ is parsed even without this option. You can already use ES2017 features like
async/
await.
XO makes it easy to override configs for specific files. The
overrides property must be an array of override objects. Each override object must contain a
files property which is a glob string, or an array of glob strings. The remaining properties are identical to those described above, and will override the settings of the base config. If multiple override configs match the same file, each matching override is applied in the order it appears in the array. This means the last override in the array takes precedence over earlier ones. Consider the following example:
The base configuration is simply
space: 2,
semicolon: false. These settings are used for every file unless otherwise noted below.
For every file in
test/*.js, the base config is used, but
space is overridden with
3, and the
esnext option is set to
false. The resulting config is:
test/foo.js, the base config is first applied, followed the first overrides config (its glob pattern also matches
test/foo.js), finally the second override config is applied. The resulting config is:
If you have a directory structure with nested
package.json files and you want one of the child manifests to be skipped, you can do so by setting
"xo": false. For example, when you have separate app and dev
package.json files with
electron-builder.
Put a
package.json with your config at the root and add
"xo": false to the
package.json in your bundled packages.
It means hugs and kisses.
The Standard style is a really cool idea. I too wish we could have one style to rule them all! But the reality is that the JS community is just too diverse and opinionated to create one code style. They also made the mistake of pushing their own style instead of the most popular one. In contrast, XO is more pragmatic and has no aspiration of being the style. My goal with XO is to make it simple to enforce consistent code style with close to no config. XO comes with my code style preference by default, as I mainly made it for myself, but everything is configurable.
XO is based on ESLint. This project started out as just a shareable ESLint config, but it quickly grew out of that. I wanted something even simpler. Just typing
xo and be done. No decision-making. No config. I also have some exciting future plans for it. However, you can still get most of the XO benefits while using ESLint directly with the ESLint shareable config.
Show the world you're using XO →
[]()
MIT © Sindre Sorhus | https://www.npmjs.com/package/xo | CC-MAIN-2017-39 | refinedweb | 1,073 | 66.74 |
It's been a long time since I've done much work with windows management but
here is part of a script that I used to gather window information on open
processes:
import win32gui
def get_all_windows():
"""Returns dict with window desc and hwnd,
don't ask me how it works!"""
def _MyCallback( hwnd, extra ):
"""Helper function for above??"""
hwnds, classes = extra
hwnds.append(hwnd)
classes[win32gui.GetClassName(hwnd)] = hwnd
windows = []
classes = {}
win32gui.EnumWindows(_MyCallback, (windows, classes))
return classes
There may be a way to do this with pywinauto, but I don't have any scripts
that use it in that way. I'd imagine something like this would get you
started, but I don't have a way to test it at the moment.
from pywinauto.application import Application
from pywinauto import findwindows
app = Application()
# get a list of our open windows as processes
dlg_list= findwindows.find_windows(title_re = ".*", top_level_only = False)
# connect to a dialog using it's process id
dlg = app.connect_(process = dlg_list[0])
# get some information about the process we are connected to
app.dlg.control
app.dlg.print_control_identifiers()
On Wed, Nov 16, 2011 at 9:24 AM, Sajid <sajid@...> wrote:
>
>
> ------------------------------------------------------------------------------
> RSA(R) Conference 2012
> Save $700 by Nov 18
> Register now
>
> _______________________________________________
> Pywinauto-users mailing list
> Pywinauto-users@...
>
>
>
--
- Ken | https://sourceforge.net/p/pywinauto/mailman/pywinauto-users/thread/CAJ6XMEvV5cLfqNPeU43=Ov1vr2yBBmQbix5kuOB2x3bfXiWUiw@mail.gmail.com/ | CC-MAIN-2017-43 | refinedweb | 212 | 54.52 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.