text
stringlengths 454
608k
| url
stringlengths 17
896
| dump
stringlengths 9
15
⌀ | source
stringclasses 1
value | word_count
int64 101
114k
| flesch_reading_ease
float64 50
104
|
---|---|---|---|---|---|
GCC Bugzilla – Bug 22252
[4.0 Regression] pragma interface/implementation still break synthesized methods
Last modified: 2007-01-18 11:42:56 UTC
This is similar to bug 21280, but it is _not_ fixed by the patches therein.
In fact it still happens with current 4.0 branch as of 2005-06-30.
Compile these files:
% cat a.h
#include <vector>
#pragma interface
struct A {
std::vector<char> vc;
};
% cat use.cc
#include "a.h"
A a;
int main() {}
% cat a.cc
#include <vector>
#pragma implementation
#include "a.h"
% g++ -W -Wall -O2 a.cc use.cc
a.h:3: warning: inline function ‘A::A()’ used but never defined
a.h:3: warning: inline function ‘A::~A()’ used but never defined
/tmp/ccuIwMBN.o: In function `__static_initialization_and_destruction_0(int,
int)':
use.cc:(.text+0x31): undefined reference to `A::A()'
collect2: ld returned 1 exit status
This is because A::A() is not synthesized, although it should happen in file
a.cc (which contains the pragma implementation).
So, something still is wrong (this actually breaks building lyx btw.) after
21280 was fixed.
Andrew: that's not a diagnostic issue. While the diagnostic (the warning)
indeed is wrong and misleading (and probably points to the underlying cause
of this issue), the actual error I'm complaining about is
the link error, due to not emitting an out-of-line copy of A::A() in a.cc as
it would be required.
(In reply to comment #1)
Yes which is why I did not confirm it yet because I did not look at fully. I just added the diagnostic
keyword because it is still a wrong warning. I am adding wrong-code also.
Reduced testcase:
---- a.ii ----
# 1 "a.cc"
# 0 "<built-in>"
# 1 "<command line>"
# 1 "a.cc"
#pragma implementation
# 1 "a.h" 1
struct B
{
B(){};
~B(){}
};
#pragma interface
struct A {
B a;
};
# 3 "a.cc" 2
---- use.ii ----
# 1 "use.cc"
# 0 "<built-in>"
# 1 "<command line>"
# 1 "use.cc"
# 1 "a.h" 1
struct B
{
B(){};
~B(){}
};
#pragma interface
struct A {
B a;
};
# 2 "use.cc" 2
A a;
int main() {}
Ah, I see. Note that you must compile the reduced testcase (thanks for
that) with -O0, or with -fno-inline, otherwise the A::A ctor will be inlined
in use.cc (making the warning about the non-availability of it even more
funny ;-) ), and not lead to the link error.
Fixed in 4.1.
Subject: Bug 22252
CVSROOT: /cvs/gcc
Module name: gcc
Changes by: [email protected] 2005-09-09 18:56:16
Modified files:
gcc/testsuite : ChangeLog
gcc/cp : ChangeLog decl.c decl2.c pt.c semantics.c
Added files:
gcc/testsuite/g++.dg/ext: interface1.C interface1.h
interface1a.cc
Log message:
PR c++/22252
* decl.c (start_preparsed_function): Do not pay attention to
#pragma interface for implicitly-defined methods.
* decl2.c (cp_finish_file): Do not complain about uses of inline
functions that have bodies, even if we decided not to emit the
body in this translation unit.
* semantics.c (note_decl_for_pch): Do not mess with linkage.
(expand_or_defer_fn): Make inline, non-template functions COMDAT
at this point.
PR c++/22252
* g++.dg/ext/interface1.C: New test.
* g++.dg/ext/interface1.h: Likewise.
* g++.dg/ext/interface1a.cc: Likewise.
Patches:
*** Bug 24421 has been marked as a duplicate of this bug. ***
*** Bug 24248 has been marked as a duplicate of this bug. ***
*** Bug 24852 has been marked as a duplicate of this bug. ***
Created attachment 10401 [details]
preprocessed output that causes ICE
This patch seems to cause another ICE. I applied the patch on gcc-4.0 to fix this bug, and now the attached output causes an ICE with >= -O1 (the same seems to be true on gcc-4.1 as well). Reverting the patch seems to stop the new ICE.
The claim in Comment #9 is that this is a 4.1 regression as well as a 4.0 regression, so I've udpated the subject line. It would be interesting to know if this affects mainline as well.
(In reply to comment #10)
> The claim in Comment #9 is that this is a 4.1 regression as well as a 4.0
> regression, so I've udpated the subject line. It would be interesting to know
> if this affects mainline as well.
Actually that was a different bug. That was PR 25010 so this was fixed also in 4.1 fully. Tested on the mainline and the 4.1 branch to confirm that.
not release critical for GCC-4.0.x | http://gcc.gnu.org/bugzilla/show_bug.cgi?id=22252 | CC-MAIN-2014-15 | refinedweb | 756 | 70.29 |
import "github.com/jteeuwen/go-bindata"
bindata converts any file into managable Go source code. Useful for embedding binary data into a go program. The file data is optionally gzip compressed before being converted to a raw byte slice.
The following paragraphs cover some of the customization options which can be specified in the Config struct, which must be passed into the Translate() call.
When used with the `Debug` option,.
The `NoMemCopy` option will alter the way the output file is generated. It will employ a hack that allows us to read the file data directly from the compiled program's `.rodata` section. This ensures that when we call call our generated function, we omit unnecessary memcopies. }
The NoCompress option indicates that the supplied assets are *not* GZIP compressed before being turned into Go code. The data should still be accessed through a function call, so nothing changes in the API.
This feature is useful if you do not care for compression, or the supplied resource is already compressed. Doing it again would not add any value and may even increase the size of the data.
The default behaviour of the program is to use compression.
With the optional Tags field,.
asset.go bytewriter.go config.go convert.go debug.go doc.go release.go restore.go stringwriter.go toc.go
Translate reads assets from an input directory, converts them to Go code and writes new files to the output specified in the given configuration.
type Asset struct { Path string // Full file path. Name string // Key used in TOC -- name by which asset is referenced. Func string // Function name for the procedure returning the asset contents. }
Asset holds information about a single asset to be processed.
Implement sort.Interface for []os.FileInfo based on Name()
func (w *ByteWriter) Write(p []byte) (n int, err error)
type Config struct { // Name of the package to use. Defaults to 'main'. Package string // Tags specify a set of optional build tags, which should be // included in the generated output. The tags are appended to a // `// +build` line in the beginning of the output file // and must follow the build tags syntax specified by the go tool. Tags string // Input defines the directory path, containing all asset files as // well as whether to recursively process assets in any sub directories. Input []InputConfig // Output defines the output file for the generated code. // If left empty, this defaults to 'bindata.go' in the current // working directory. Output string // Prefix defines a path prefix which should be stripped from all // file names when generating the keys in the table of contents. // For example, running without the `-prefix` flag, we get: // // $ go-bindata /path/to/templates // go_bindata["/path/to/templates/foo.html"] = _path_to_templates_foo_html // // Running with the `-prefix` flag, we get: // // $ go-bindata -prefix "/path/to/" /path/to/templates/foo.html // go_bindata["templates/foo.html"] = templates_foo_html Prefix string // NoMemCopy will alter the way the output file is generated. // // It will employ a hack that allows us to read the file data directly from // the compiled program's `.rodata` section. This ensures that when we call // call our generated function, we omit unnecessary mem copies. // // // } NoMemCopy bool // NoCompress means the assets are /not/ GZIP compressed before being turned // into Go code. The generated function will automatically unzip // the file data when called. Defaults to false. NoCompress bool // Perform a debug build. This generates an asset file, which // loads the asset contents directly from disk at their original // location, instead of embedding the contents in the code. // // This is mostly useful if you anticipate that the assets are // going to change during your development cycle. You will always // want your code to access the latest version of the asset. // Only in release mode, will the assets actually be embedded // in the code. The default behaviour is Release mode. Debug bool // Perform a dev build, which is nearly identical to the debug option. The // only difference is that instead of absolute file paths in generated code, // it expects a variable, `rootDir`, to be set in the generated code's // package (the author needs to do this manually), which it then prepends to // an asset's name to construct the file path on disk. // // This is mainly so you can push the generated code file to a shared // repository. Dev bool // When true, size, mode and modtime are not preserved from files NoMetadata bool // When nonzero, use this as mode for all files. Mode uint // When nonzero, use this as unix timestamp for all files. ModTime int64 // Ignores any filenames matching the regex pattern specified, e.g. // path/to/file.ext will ignore only that file, or \\.gitignore // will match any .gitignore file. // // This parameter can be provided multiple times. Ignore []*regexp.Regexp }
Config defines a set of options for the asset conversion.
NewConfig returns a default configuration struct.
type InputConfig struct { // Path defines a directory containing asset files to be included // in the generated output. Path string // Recusive defines whether subdirectories of Path // should be recursively included in the conversion. Recursive bool }
InputConfig defines options on a asset directory to be convert.
func (w *StringWriter) Write(p []byte) (n int, err error)
Package bindata imports 13 packages (graph) and is imported by 92 packages. Updated 2020-08-31. Refresh now. Tools for package owners. | https://godoc.org/github.com/jteeuwen/go-bindata | CC-MAIN-2020-45 | refinedweb | 881 | 57.16 |
.
Your declaration of MallList should have parentheses around the names of the arrays, not brackets ... new MallList( names, costs, stores );
I interpret your description as requiring that the MallList class is supposed to take the data in the arrays which are passed as parameters and hold that data in a linked list. Please correct me if that interpretation is wrong.
These three parallel arrays hold the information which, when put together, describes each store of the mall. You refer to the combination of information by the index they share.
If the MallList is supposed to be a linked list, and linked lists hold data and a link, you can create a Node class for your list which holds, as data, one tuple of data indexed by "0", another by "1", and another by "2" from names, costs, stores. It also holds a link to the next Node.
So, node0.name = name[0], node0.cost = costs[0], node0.store = stores[0].
Iterate through your arrays, populating the current node with the values stored there, and add the resulting nodes, in turn, to the list.
Thank for the help. I did gain a better understanding, unfortunately nodes were not required for this program. I'm hoping if I put up the code I have so far my question would be better understood. I do apologize for the format in advance as well.
//This program will take 3 arrays and make them into a list
//Depending of the type of item, its cost, and its store number
import java.io.*;
public class TestListStudent
{
public static void main(String[] args)
{
String[] names = {"jeans", "shirt", "boots"}; //array for items
double[] costs = {39.99, 24.75, 105.00}; //array for their costs
int[] stores = {16, 29, 3}; //store number that they are at
MallList listOne = new MallList(names,costs,stores);
System.out.println("Is the list full" + listOne.isListFull());//check to see if list is full
listOne.printFowards(); //Print the list
listOne.Insert("socks" + 5.64 + 80); //add socks and its variables to the list
System.out.println("The list in reverse");
listOne.printBackwards(); //Print the list backwards
System.out.println("Is the list full" + listOne.isListFull());//check to see if list is full again
listOne.Insert("necklace" + 12.5 + 3); //add another item
listOne.printFowards(); //print again
System.out.println("Is the list full" + listOne.isListFull());//is list full
}
}
public class ItemList //Class that holds methods to print the list
{
public int listOne = new MallList[maxSize];
public int maxSize = 5;
public int length = 0;
public ItemList(int maxS, int length, int[] MallList)
{
listOne = MallList[];
TotalLength = length;
maxSize = maxS;
}
public boolean isListFull() //checks to see if the list is full
{
return (TotalLength == maxSize);
}
public void printBackwards(int listOne[]) //method to print list backwards by recursion
{
if(int i <= TotalLength)
{
System.out.println(listOne[i]);
i--
backwards(i);
}
}
public void Insert(int Item) //method to put an item into the list
{
int length = 0;
int maximum = 5;
int Item = 0;
if(length == 0)
listOne[length++] = insertItem;
else
if(length == maximum)
System.out.println("The list is full");
else
listOne[length++] = Item;
}
public void printFowards(int listOne[]) //method to print list fowards
{
for(int i = 0; i < TotalLength; i++)
System.out.println(listOne[i]);
}
}
public class Item //Base class
{
private String type;
private int cost;
public Item(String itemType, int amount) //constructor with type of item and amount it costs
{
type = itemType;
cost = amount;
}
public void List() //Prints the list
{
super(List);
System.out.print(type + " " + cost);
}
}
public class MallItem extends Item //Derived class from Item
{
private int Store;
public MallItem(int storeNumber)//Constructor
{
Store = storeNumber;
}
public void Printitems() //Prints the store number with respect to the list
{
System.out.println(" "+Store);
}
}
I think you need to put some time into organizing your project. It is time to put pencil to paper and chart out what class structure you are creating, what methods and data in each, and the interaction of classes. What is your program supposed to be doing?
What does your MallList class look like?
In ItemList you seem to declare the object "listOne" (which has all sorts of methods being called in your method main) as an int but then define it as an array of MallList elements.
Why would you assign values to data members of your ItemList class and then have a constructor which takes arguments which redefines these data members?
What is the List() method supposed to be doing in your Item class? (remember the naming pattern - methods are supposed to start with a lower case letter). What is the call to super(List) supposed to do?
I don't understand the relationship of Item and MallItem: can you explain it to me? It does not make sense to me that one derives from the other. You make no apparent use of the inherited data members in the child class.
Forum Rules
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center | http://forums.devx.com/showthread.php?150895-Array-Based-List-questions&p=449320 | CC-MAIN-2014-42 | refinedweb | 826 | 63.39 |
From: Greg Colvin (gcolvin_at_[hidden])
Date: 1999-07-29 09:30:48
Sorry to be nitpicking so much here. It may not be that important what
convention Boost uses, but it is important to follow a convention, or
else some combination of command line switches, environment variables,
and where you compile from could suck in an inconsistent set of Boost
headers.
From: Beman Dawes <beman_at_[hidden]>
> ....
>
> I went back and read both the C standard and C rationale, and there
> is no indication that <...> is for system files, and "..." is for
> user files unless you want to deduce that from some rationale
> discussion of early C implementation search paths.
Yep -- its a strrtch I know. From K&R, first edition, page 86:
To facilitate handling collections of #defines and declarations
(among other things) C provides a file inclusion feature. Any
line that looks like
#include "filename"
is replaced by the contents of the file filename. (The quotes
are mandatory.) ...
No mention in this section of angle brackets, which appear on page
143 in the Input and Output chapter:
Each source file that refers to a standard library function must
contain the line
#include <stdio.h>
somewhere near the beginning. ... Use of the angle brackets < and >
instead of the usual double quotes directs the compiler to search
for the file in a directory containing standard header information
(on Unix, typically /usr/include).
So users are taught to use the quoted for their own files and the
bracketed form for standard files. And despite the name usr,
users typically do not copy their own files into /usr/include,
since it is shared by other users of the system.
> > I had thought that the intent was
> >that:
> > <name> forms were intended for standard and system C++ headers;
> > <name.h> forms were intended for standard and system C headers;
> > "whatever" forms were intended for user source files;
> >where "headers" need not be files at all.
>
> Well, neither standard says anything about "intended for standard and
> system headers" or "intended for user source files".
I see the Standard's careful use of the term "file" for the quoted
form and "header" for the bracketed form as hinting back at this
convention, while struggling not to actually require a file system.
If anyone has access to an OS 360/370 compiler I'd be interested in
what the rules are there, since as I recall that system has a notion
"file" very different from the Unix/CPM/MSDOS tradition.
> The convention I have seen used a lot is that <...> is for headers
> that contain public interfaces to a library, while "..." is for
> headers which are part of the library's implementation and not part
> of its public interface. That, coupled with the implementation
> directory not being in the <...> path, keeps a user from
> inadvertently including an implementation header which isn't part of
> the public interface.
Yes, this is a reasonable convention, to the extent that a library is
seen as "system" code.
> Don't take my word of it. Look at various public libraries. I just
> grepped SGI's STL library, and it uses the <...> form for all
> headers, system or otherwise.
As does Oracle's C source code. But before Oracle I never used angle
brackets to include any source written by me or my company.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/1999/07/0454.php | CC-MAIN-2022-05 | refinedweb | 574 | 64.51 |
extensions/auth/nsAuthSSPI.cpp We probably shouldn't ever make synchronous DNS resolution calls, and we definitely shouldn't do it on the main thread. Removing this stuff is a high priority.
The bad call is: extensions/auth/nsAuthSSPI.cpp: 94 static nsresult 95 MakeSN(const char *principal, nsCString &result) [...] 121 rv = dns->Resolve(Substring(buf, index + 1), 122 nsIDNSService::RESOLVE_CANONICAL_NAME, 123 getter_AddRefs(record));
nsAuthSSPI is an implementation of nsIAuthModule which has only a synchronous interface. fixing this bug will require making nsIAuthModule asynchronous and breaking out of tree users. The goal is to remove the synchronous DNS resolve API so there is no point in adding a second interface concurrently.
As mentioned in comment 2, nsIAuthModule is a synchronous API and there are a bunch of implementors of it. To make it async would require converting all of those callers even though only one implementation (nsAuthSSPI) is engaging in janky behavior, and even then only in one of the two paths it implements (kerberos SSPI, not NTLM). Even after changing those implementations the callers would need to be updated, and if that level was synchronous the process would need to be repeated until we hit an existing body of code that code go async. That stopping point turns out to be nsIHttpChannelAuthProvider<-nsIHttpAuthenticator<-nsIAuthModule Instead of changing all of that code, I took advantage of the fact that we know we need to do this blocking DNS call well before it is currently being done. So I put a property on the particular kerberos code that requires it and let nsIHttpChannelAuthProvider query that property at an early point that is already potentially asynchronous. (I use the point where we might pop up a credential dialog, that blocks for user input). Its convenient to do the non blocking DNS at that stage and then just feed the nsIAuthModule the canonicalized version of the hostname as usual in a synchronous way because the lookup was already completed. the result is still annoying, but not nearly as bad as making nsIAuthModule async. As for testing - I don't have kerberos setup and don't think I even have the right OS pieces to get SSPI/Negotiate/Kerberos running. I have tested this with windows NTLM (forcing the canonicalization to happen with the flag for that (which is wrong per the comments - so I have removed the flag before submitting the patch) and that's going to exercise all of the relevant code paths.. its the closest I could come. I'll post the patch after try-server approves.
Created attachment 644703 [details] [diff] [review] patch 0 not the prettiest thing..
Comment on attachment 644703 [details] [diff] [review] patch 0 Review of attachment 644703 [details] [diff] [review]: ----------------------------------------------------------------- r- for two reasons. This doesn't look that bad, IMO, it appears to be a good idea to use the async mechanism we already have got. Except the forwarder class. I think it is not necessary to have that little "monster". See the comments in the code. But, there are another major issues with this patch. 1. nsHttpChannelAuthProvider is AddRef'ed on one of the resolver threads. But it is not implemented as thread-safe: > xul.dll!nsHttpChannelAuthProvider::AddRef() Line 1409 + 0x93 bytes C++ xul.dll!nsCOMPtr<nsIDNSListener>::nsCOMPtr<nsIDNSListener>(nsIDNSListener * aRawPtr=0x0bae7df8) Line 537 C++ xul.dll!`anonymous namespace'::DNSListenerProxy::OnLookupCompleteRunnable::OnLookupCompleteRunnable(nsIDNSListener * aListener=0x0bae7df8, nsICancelable * aRequest=0x0b843f4c, nsIDNSRecord * aRecord=0x0b30da58, unsigned int aStatus=0x00000000) Line 515 + 0x27 bytes C++ xul.dll!`anonymous namespace'::DNSListenerProxy::OnLookupComplete(nsICancelable * aRequest=0x0b843f4c, nsIDNSRecord * aRecord=0x0b30da58, unsigned int aStatus=0x00000000) Line 545 + 0x33 bytes C++ This is causing an assertion failure. Thus you should have an extra class to use as a resolver listener that would be thread safe, or turn the authprovider to be thread-safe. I personally would prefer the former, otherwise we can loose a way to detect that authprovider is being used on more then one thread in the future.". ::: netwerk/protocol/http/nsHttpChannel.cpp @@ +4252,5 @@ > + rv = GetURI(getter_AddRefs(uri)); > + if (NS_FAILED(rv)) > + return rv; > + return uri->GetAsciiHost(host); > +} This should just forward to nsHttpChannelAuthProvider, if any, to pick the auth host: if there is a canon host resolved, return it, otherwise return mAuthChannel->GetURI->GetAsciiHost. ::: netwerk/protocol/http/nsHttpChannelAuthProvider.cpp @@ +1081,5 @@ > static_cast<nsAuthInformationHolder*>(aAuthInfo); > + if (holder) > + ident->Set(holder->Domain().get(), > + holder->User().get(), > + holder->Password().get()); In braces please. ::: netwerk/protocol/http/nsIHttpAuthenticableChannel.idl @@ +73,5 @@ > > /** > + * The host portion of the URI, possibly canonicalized > + */ > + readonly attribute ACString asciiHost; Rename this to asciiHostForAuth.
Created attachment 645024 [details] [diff] [review] patch 1 Thanks Honza, your comments made this better. I didn't set the r? flag on the update (which should have all the review comments) because I can't reproduce the problem you described starting with "I presume".. more on that later. But in any event - lets use this version of the patch moving forward.
(In reply to Honza Bambas (:mayhemer) from comment #5) > >". > hmm.. I tested almost exactly like that. 1] setup a samba PDC that does ntlm 2] have apache require ntlm for access 3] force ntlm in nsAuthSSPI to do canonical resolution (which it shouldn't..) 4] confirm via debug output that the resolution didn't actually change the name 5] login (or be denied based on bad credentials) other than the fact I was using apache/samba does that sound the same? Obviously if the additional name resolution didn't result in a change it shouldn't break anything. (and if it did result in a change the test is invalid). can you privately send me a url (probably tunneled through a nat?) and credentials I can try with? maybe retest with the new patch?
Comment on attachment 645024 [details] [diff] [review] patch 1 Review of attachment 645024 [details] [diff] [review]: ----------------------------------------------------------------- r=honzab except some referencing issues. This patch version works in my local test environment for direct NTLM (IIS 7.5 w/ extended val) and proxy NTLM (ISA 2006 configured to let all users auth). ::: netwerk/protocol/http/nsHttpChannelAuthProvider.cpp @@ +247,5 @@ > + if (mDNSQuery) { > + mDNSQuery->Cancel(status); > + mDNSQuery = nsnull; > + } > + mDNSCallback = nsnull; Why do you actually need to hold the callback? @@ +783,5 @@ > + nsresult rv = ResolveHost(); > + if (NS_SUCCEEDED(rv)) > + return NS_ERROR_IN_PROGRESS; > + return rv; > + } Hmm.. when the auth method changes you should truncate mCanonicalizedHost. Followup bug is probably OK to do that. @@ +1378,5 @@ > + nsIDNSRecord *record, > + nsresult rv) > +{ > + nsCString cname; > + mAuthProvider->SetDNSQuery(nsnull); Most elegant (also according a need for this particular method) would be to let all this code live in some semi-private method of nsHttpChannelAuthProvider that DNSCallback::OnLookupComplete would call with necessary args. ::: netwerk/protocol/http/nsHttpChannelAuthProvider.h @@ +148,5 @@ > PRUint32 mTriedProxyAuth : 1; > PRUint32 mTriedHostAuth : 1; > PRUint32 mSuppressDefensiveAuth : 1; > + > + PRUint32 mResolvedHost : 1; No new blank line before this line. @@ +161,5 @@ > + : mAuthProvider(authProvider) > + { } > + > + private: > + nsHttpChannelAuthProvider *mAuthProvider; // weak ref This can live potentially longer then the provider. Since you don't need to ref callback from the provider, I think it would be better to have this as a strong ref.
Thanks honza. fyi mResolvedHost was uninitialized - I fixed that too. (In reply to Honza Bambas (:mayhemer) from comment #8) > > Hmm.. when the auth method changes you should truncate mCanonicalizedHost. > Followup bug is probably OK to do that. do you think its sufficient to just truncate (and set mresolvedhost to false) in processauthentication()? That looks like it would do it, if so we can do it in this patch.
.
(In reply to Honza Bambas (:mayhemer) from comment #10) > . as long as its ok by you, I'm going to check it in as part of processauthentication() because I think there's a potential bug there without it. (you get a ssspi auth challenge and do the c14n, the subsequent auth fails because user provided bogus creds, and now you get challenged with basic ntlm.. we would reuse the c14'd name there which isn't right and could lead to login failure..) we can optimize that in another bug, but I think its not really necessary - we're basically talking about taking an extra dns lookup that probably hits the cache in a very edge case anyhow, right?
if I wasn't clear - I meant every time processauthentication was called truncate mc14n.
Yes, that is probably the right place, but I cannot confirm it right now. If we need to canon the name again then the lookup will be with high probability satisfied from the cache.
(In reply to Honza Bambas (:mayhemer) from comment #13) > Yes, that is probably the right place, but I cannot confirm it right now. I stepped through it in the windows debugger - watched it get cleared after a bad auth attempt and then all reset with a cache hit the next time.
backout of 767158 and 785050 from ff17 beta
due to 804605 backed out of ff18 beta. | https://bugzilla.mozilla.org/show_bug.cgi?id=767158 | CC-MAIN-2017-17 | refinedweb | 1,467 | 54.42 |
Everything You Need To Know About Expenses
- Samson Wilkins
- 1 years ago
- Views:
Transcription
1 presents Everything You Need To Know About Expenses An income tax guide for self-employed people by Sunny Widerman
2 Table of Contents Introduction 3 Is this booklet for you? 3 What this booklet covers 3 What this booklet does not cover 3 About the workbook 3 Disclaimer 3 Feedback 3 Reporting expenses on your tax return 4 First step: organize your receipts 4 The Gist of GST 5 Do you need to include GST in your expenses? 5 To exclude the GST from expenses and calculate the GST paid 5 Using the workbook 7 Adding another row to the spreadsheet 7 What expense goes where 8 Look out for the 'exceptions and exclusions' symbol 8 Capital Expenses 8 Business-use-of-home expenses 8 Last check before you begin 9 Government Expense Categories 10 Conclusion 14 If you still don't know where an expense goes 14 A final note 14 Who to contact for help 14 About Sunny Widerman 15 and Personal Tax Advisors 15
3 Introduction Is this booklet for you? This booklet is for anyone who earns self-employment income and pays taxes in Canada, and is designed to help them fill out the Expenses portion of the form T2125 Statement of Business or Professional Activities in their tax returns. The booklet is particularly aimed at people involved in the arts, because their needs and special expenses aren't usually covered in the standard materials produced by the Canada Revenue Agency (CRA). It is not for incorporated individuals. What this booklet covers By the time you have used this booklet and completed the Expenses Workbook, you will have totals to put into each of the expense categories given on the T2125, except for Motor Vehicle Expenses, capital cost allowance (CCA) and Business-Use-of-Home. What this booklet does not cover This booklet does not cover CCA (Capital Cost Allowance), Motor Vehicle Leasing Costs, or the GST return. Motor Vehicle Expenses and Business-Use-of-Home are reasonably self-explanatory on the form, and Capital Cost Allowance would be a whole other book. It also does not cover Part 4 of the T2125 form, Cost of Goods Sold. This section refers to inventory, and is for individuals whose main business is selling a product. About the workbook You should have received a workbook along with this booklet, either in electronic or in print form. The electronic version is an Excel spreadsheet that calculates totals for each category. Be sure when using the workbook that you include or exclude the GST as necessary (see The Gist of GST, later in this booklet). If you do not have the workbook, you can request one by sending an to. Disclaimer Personal Tax Advisors has made every effort to ensure that the information contained in this booklet is accurate according to Canadian tax laws as of January We cannot be held liable for inaccuracies in tax returns filed using this information, or for changes in tax law that may occur in the future. This book is a guideline only, and does not replace the advice of a qualified tax preparer or advisor. When in doubt, consult your Tax Advisor. Feedback This guide is designed to be easy to use, easy to understand, and reasonably fun to read. We appreciate any feedback on how to make it better. Please send your comments, questions and suggestions to
4 Reporting expenses on your tax return This portion of the booklet outlines the various expense categories included in Part 5 of the government form T2125 Statement of Business or Professional Activities, which self-employed people must complete. CRA materials are generalized for people with more common businesses like doctors and limousine drivers, and often don't include types of expenses unique to professionals who work in the arts. Part of the purpose of this booklet is to provide guidance as to how those unique expenses can be included in the Statement of Business or Professional Activities. T2125 Statement of Professional Activities This booklet covers the highlighted part of this form. First step: organize your receipts The first step in preparing your expenses it organize your receipts into your own personal categories. Later we'll translate and group these personal categories into government categories so they can be easily listed in your tax return. Every business has its own set: a singer might have CDs and a performance wardrobe, while a painter might have paints and smocks. None of these categories show up on the T2125, of course. Figuring out how to turn personal categories into government categories is what this booklet is all about.
5 The Gist of GST Before you start adding up your personal categories and filling out your workbook, you may need to take out the GST from your expenses. Do you need to include GST in your expenses? If you are not registered to collect the GST include the GST in all your expenses If you are registered to collect the GST and are on the quick method include the GST in all your expenses not on the quick method exclude the GST from your expenses using one of the charts below. If you're not sure whether or not you're on the quick method If you have a GST number and don't know what the quick method is, assume you're not on it. When you registered for your GST number you were put on the long method by default; to be on the quick method you have to ask for it. If you're still not sure, call the Canada Revenue Agency's GST and self-employed department at and ask. To exclude the GST from expenses and calculate the GST paid The charts on the following page show the formulas you use to calculate the cost of an item before GST, which you will need to fill out your Expense Workbook. They also show you how to calculate how much GST you paid for that item, which you will need to complete your GST return (not covered in this booklet).
6 Table 1: GST rate of 5% For expenses incurred on or after 2: GST rate of 6% For expenses incurred on or after July 1, 2006 but before 1: GST rate of 7% For expenses incurred before July 1, 2006 0.065
7 Using the workbook The workbook provides space to enter your expenses in each of the categories listed in the CRA's form. All you need to do is enter the type of expense and the amount, and the workbook will add up your totals automatically. Enter each amount in dollars and cents, without the dollar sign. Do not use dollar signs ($), letters, commas, or any punctuation (other than the decimal point) in the 'amount' column, or the workbook won't add the numbers up properly. The workbook will add dollar signs and thousands separators (commas) as necessary. Example: Advertising Can include: ads, business cards, flyers, website maintenance, etc. type amount Business cards$60.00 Promotional pens$ Yellow Pages ad$1, Total for this category: $ Adding another row to the spreadsheet If you need more space in a category, you can another row to the spreadsheet. 1. Right click (Mac users: hold down the " " key and click) on one of the rows where you have entered expenses. 2. Select 'Insert' from the menu. 3. A new, empty row will appear above the one you selected. When you type a dollar value into the 'amount' column of the new row, it will be added to the total for the category.
8 What expense goes where Now we're getting to the meat of the matter. Each Expense category on the government's T2125 Statement of Business or Professional Activities form is summarized in the next section, with tips on what you can include there. Look out for the 'exceptions and exclusions' symbol Be sure to pay attention to this symbol:. That symbol warns you that there are some important exclusions coming up things you might think you can include in a category, but which don't belong there. Capital Expenses Speaking of exclusions, this one applies to every category. Do not include capital expenses in any of the categories outlined below. They're handled differently, with calculations you do on page 3 of the T2125 Statement of Business or Professional Activities. What is a Capital Expense? A capital expense is money you spend on an item that provides lasting value, beyond the current tax year. Non-capital items only have value for the current year. To figure out if something is a capital expense, ask yourself: is it something that I use up, or that expires regularly, or that has to be bought or renewed every year? If the answer to any of those questions is 'yes', then it's not a capital expense. Examples: Item Computer Postage stamp Hammer Professional membership Is it a Capital Expense? Yes you keep using it year after year. No once it's used, it's gone. Every year you have to buy more. Yes you keep using it year after year. No you have to renew it every year. Capital expenditures have special rules. To learn how to handle them, read the government guide to the T2125 Statement of Business or Professional Activities, or consult your Tax Advisor. Business-use-of-home expenses Business-use-of-home expenses are expenses paid for a portion of your home, if you use it as a workspace. Some of those types of expenses rent and property taxes, for example seem to have their own category on the first page of T2125 Statement of Business or Professional Activities. However, those are reserved for workspaces outside the home. Business-use-of-home expenses, just like motor vehicle expenses and capital expenses, are handled on their own. This booklet doesn't explain these expenses, because the T2125 Statement of Business or Professional Activities and its guide are quite detailed and selfexplanatory.
9 Last check before you begin Make sure you've completed the following steps before you move on: 1. Organize your receipts into your categories, separating out capital expenses 2. Add up each of your categories, making sure to include or exclude the GST as outlined in the section The Gist of the GST 3. Take a deep breath Okay, you're ready! Let's get started.
10 Government Expense Categories Advertising line 8521 There are many forms of advertising. Some common ones are: Business cards Brochures, posters, flyers Website hosting and domain names Listings in directories such as the Yellow Pages or Casting Workbook Bad debts line 8590 This is where you include amounts that you billed people and included as income, but ultimately never got paid for. Most people use the 'accrual method' for calculating their income and expenses. That means that for tax purposes you record income when you bill someone, and expenses when you are billed even if you weren't paid on time, or if you waited to pay the other person. What can happen is that you bill someone, include the amount of that bill in your tax return and pay taxes on it, but later realize that they're never going to pay you. Since you never got the income, you really shouldn't have to pay the income tax. Bad Debts is where you get that tax back. By including here the money you billed for but were never paid, you subtract the income from this year's return, thereby getting the tax back. Business tax, fees, licenses, dues, memberships and subscriptions line 8760 Include fees for all your professional memberships, registration of business name, etc. If you are an actor, your ACTRA fees go here. Do not include payments to medical plans here, even if they're required for your membership (e.g., ACTRA Fraternal medical benefits); they are a medical expense. Consult your Tax Advisor to learn more about where those go. Delivery, freight and express line 9275 This category is for people who ship out a product. Enter the amounts you paid to send out your product here. This category is not for the usual postage or courier charges on letters or small packages you sent out those are Office Expenses (see below). Fuel costs (except for motor vehicles) line 9224 Like Delivery, freight and express (above), this category is for people who ship out a product. Do not include the gas you put in a vehicle in order to get yourself from place to place. That is a Motor Vehicle Expense (line 9281, below).
11 Insurance line 8690 Insurance you pay on things you own for your business (your computer or special wardrobe, for example), or for products you ship out. This category is not for house, apartment or contents insurance, even if you work at home. Such so-called business-use-of-home expenses go in the Business-Use-of-Home category, which is calculated on page 2 of the government's form T2125 Statement of Business or Professional Activities. Interest line 8710 This category includes interest on loans, lines of credit, and credit cards. Don't forget the credit cards! If you're not sure how much was interest on business expenses and how much was personal, you can go through your bills month by month or just figure out a percentage that seems reasonable. You can also consult your Tax Advisor for help with figuring out a percentage. Maintenance and repairs line 8960 This category if for maintenance and repairs for equipment or other items related to your business. Do not include maintenance and repairs on your home in this category, even if you work there. Such so-called business-use-of-home expenses are calculated on page 2 of the government's T2125 Statement of Business or Professional Activities form. Management and administration fees line 8871 This category includes agent's commissions and managers' fees. It also includes bank fees, but only if you have a separate account for your business. If you manage your business money out of your personal bank account, you shouldn't write off those bank fees as an expense. Meals and entertainment (allowable part only) line 8523 This category is for meals and/or events you attended as part of a business or client meeting. As of January 2007, you can write off only 50% of your business meals and entertainment (that's what they mean by 'allowable part'). If you have to travel for your business, even if it's overnight, the meals you have while away from home also go here, and are also only 50% deductible. Remember, this category is only for meals and entertainment that were part of client or business meetings. If you're a performer or a film or theatre critic and must therefore attend theatre or films as part of your research, don't include those expenses here. Put them with your research expenses under 'Other expenses' (line 9270, below) so that you write them off entirely. Similarly, if you have some people working for you and you treat them to a meal as a thank you or as a benefit of working for you, the cost of that meal doesn't go in this category. Put it in 'Salaries, wages and benefits' (line 9060, below) instead so you can write the whole thing off. Motor vehicle expenses (not including CCA) line 9281 This booklet and workbook doesn't cover Motor vehicle expenses, as the government's own form is quite detailed and self-explanatory. See page 4 of T2125 Statement of Business or Professional Activities. Office expenses line 8810 Use this category for office supplies, postage, courier, etc.
12 This category does not include calculators, computers or peripherals, furniture, which are capital expenses (see Capital Expenses in the previous chapter). Supplies line 8811 This category is for items you buy and use in the manufacture of the product that you sell. A photographer could include frames and film in this category; a luthier could include wood and strings. This category does not include office supplies (see 'Office expenses', above), because they're not physically incorporated into a product. Legal, accounting and professional fees line 8860 This category is for lawyers', bookkeepers', accountants' and tax preparers' fees. Property taxes line 9180 Use this category only if you have a workspace that's not part of your home. This category does not include taxes paid on your home, even if you work there. Such socalled business-use-of-home expenses go in the Business-Use-of-Home category, which is calculated on page 2 of the government's form T2125 Statement of Business or Professional Activities. Rent line 8910 In this case, 'rent' is only for workspaces or storage that is not part of your home. If you work from home, you can write off a portion of your home rent; but not here. This category does not include rent paid on your home, even if you work there. Such so-called business-use-of-home expenses go in the Business-Use-of-Home category, which is calculated on page 2 of the government's form T2125 Statement of Business or Professional Activities. Salaries, wages and benefits (including employer's contributions) line 9060 Use this category for amounts paid to someone else who helped you earn income, who isn't covered under 'professional fees' above. Note that you can pay a spouse or a child if they do necessary work for your business. If you paid your employees or helpers with gifts and/or meals instead of (or in addition to) money, include the cost of those here. Remember, it's to your tax advantage to include meals here rather than in Meals and Entertainment, because in this category you get to write them off in their entirety. If you ate the meal yourself, it must go in Meals and Entertainment. If your employee ate it, it can go here. Travel line 9200 This category is for costs incurred while on business and/or professional development trips. Includes plane/bus/train fare, accommodations, rental car & expenses, public transit while there. It is supposed to be for out-of-town travel. But if you travel by public transit and taxis, you can include those costs here since there's no better place to put them. This category does not include meals you eat while travelling, even if you're gone overnight. Those expenses must go in Meals and Entertainment, above.
13 Telephone and utilities line 9220 If you have a workspace that is not part of your home, you can include heat, electricity, local phone and water for that workspace here. You can also include the business portion of your cell phone, internet access, long distance phone, pager, and fax line here. If your residential phone line is also your business line, include the business portion of the expense, prorated by the amount of time you spend on business calls. For example, half the time you spend on your residential phone line is for business purposes, you can deduct half the phone bill. Other expenses line 9270 This is the dumping ground for every business expense that (a) doesn't fit anywhere else or (b) you're not sure about. Some examples are: performance wardrobe, professional development courses and seminars, conferences (maximum of two per year), and CDs, DVDs, theatre tickets and books if they're legitimate research materials, and promotional gifts. Buying a bottle of wine for your agent is an example of a promotional gift. Private Medical Insurance: This is also where you deduct the cost of private health services plan (PHSP) premiums. If you pay into a health plan for yourself, your spouse or common-law partner, or any member of your household, AND if you earn at least 50% of your income through your freelance business, you can deduct those premiums here (within proscribed limits). While these expenses can also qualify as medical expenses, which can be claimed on a separate form, it is usually preferable to deduct them here. This is because PHSP premiums provide a greater tax deduction as business expenses than as medical expenses.
14 Conclusion We hope this guide has been a help to you. We've done our best to make the government's rules reasonably clear, and to cover the most common types of expenses our clients encounter. If you have any more questions, contact us to arrange your own tax advisor to work with you, or refer to the government's own site and materials. If you still don't know where an expense goes Sometimes categorizing your expenses is an art rather than a science, and there's room for a lot of personal interpretation. For example, you might pay a web developer a fee to build and maintain your promotional website. Is that payment an advertising expense (line 8521), a professional fee (line 8861), or a salary (line 9060)? The answer: it's your call. Many expenses have one definite place on the form, while others can be interpreted various ways. Some won't fit anywhere, and just have to go into Other expenses (line 9270). A final note When calculating and categorizing your expenses for your taxes, try to be as logical as you can. But don't get tied up in knots if you're not sure exactly where a particular expense goes. With the exception of Motor vehicle expenses, meals and entertainment, and Business-use-of- Home expenses, the precise placement of an expense doesn t make any difference to your bottom line; so long as no one number is particularly irregular or high, it's unlikely to attract negative attention from the Canada Revenue Agency. If you do get audited, your task is to convince the auditor that your expenses are 'reasonable'. So long as you've been honest and feel you can confidently argue the reasonableness of your expenses, go ahead and file your return without fear. Who to contact for help Personal Tax Advisors phone: Canada Revenue Agency Visit the Canada Revenue Agency at For individual, non-business enquiries: Hours: Monday to Friday 8:15 am - 10:00 pm; 9:00 a.m. to 1:00 p.m. on weekends. For self-employed, GST and business information: Hours: Monday to Friday 8:15 am - 10:00 pm; 9:00 a.m. to 1:00 p.m. on weekends.
15 About Sunny Widerman and Personal Tax Advisors Personal Tax Advisors offers tax preparation, advice, and planning strategies for individual taxpayers, with a particular focus on the needs of self-employed or freelance clients. Sunny Widerman has been preparing tax returns for clients since 2002, and offers knowledgeable information and service in plain language and without judgement. Call (416) or to discuss your tax situation or set up an appointment.
Tax Issues. for self-employed members
Tax Issues for self-employed members C A N A D I A N A C T O R S E Q U I T Y A S S O C I A T I O N This briefing was developed in discussions with professional tax preparers who are experienced in performing
DEDUCTING EXPENSES AS AN EMPLOYEE
DEDUCTING EXPENSES AS AN EMPLOYEE Employees are very limited in the expenses that they can deduct in calculating the tax they owe to the Canada Revenue Agency ( CRA ). Self-employed individuals have much
An Overview of Recordkeeping for Sole Proprietors
An Overview of Recordkeeping for Sole Proprietors (and a companion spreadsheet for tracking income & expenses) Here's a guide to help you track your business income and expenses. It is designed to help
Part 5. Employment Expenses
0 Part 5 Employment Expenses The Tax Shelter Training 1 PART V EMPLOYMENT EXPENSES Refer to Guide T4044 - Employment Expenses. A taxpayer may be able to deduct certain expenses paid to earn employment Expenses Guide
Business Expenses Guide Sole Trader What is this about? Each year, your business must prepare a set of accounts for HM Revenue & Customs (HMRC). These accounts calculate the business profits on which you
How to Use the Cash Flow Template
How to Use the Cash Flow Template When you fill in your cash flow you are trying to predict the timing of cash in and out of your bank account to show the affect and timing for each transaction when it
Double Entry Accounting Workbook. Erin Lawlor
Double Entry Accounting Workbook Erin Lawlor Double Entry Accounting Workbook Table of Contents Introduction... 2 Financial Statement Introduction... 3 Financial Transactions... 4 Debits and Credits...
Small Business Income Tax
Small Business Income Tax Forms of Business & how their taxes are paid. Keeping Records Legal requirements. Bringing Assets into a business. Fair market value. Earnings Fiscal period Income Expenses What
PROJECTING YOUR CASH FLOW
THE BUSINESS ENTERPRISE CENTRE S GUIDE TO PROJECTING YOUR CASH FLOW The Business Enterprise Centre is a member of Last updated 16 Jan 2015 TD Page 1 of 26 Preface A cash flow statement reports the outflow
TAX GUIDE FOR THE TAXI AND SHUTTLE INDUSTRIES
TAX GUIDE FOR THE TAXI AND SHUTTLE INDUSTRIES Information to help your business IR 135 October 2010 Help is at hand This tax guide gives you, as a self-employed person, an overview of your tax entitlements
Tips for filling out the Self-Employment Tax Organizer (SETO)
Tips for filling out the Self-Employment Tax Organizer (SETO) Who is eligible for self-employment services at Prepare and Prosper? We serve sole proprietors, independent contractors, or single member LLC
Collins Barrow. Chartered Accountants
Income Tax for Small Business Presented by Jason Timmermans, BA, CA Partner KMD Introduction Information package What are you hoping to get out of today s session? Agenda Basics of Canadian income tax.
CLAIMING BUSINESS EXPENSES WHAT S DEDUCTIBLE AND WHEN?
CLAIMING BUSINESS EXPENSES WHAT S DEDUCTIBLE AND WHEN? Every business incurs and pays a wide variety of business-related expenses on a day-to-day basis, ranging from employee payroll to advertising costs
BUSINESS EXPENSES AND DEDUCTIONS
03 BUSINESS EXPENSES AND DEDUCTIONS Claim deductions for your business expenses when you lodge your income tax return, see page 18. To claim deductions for your business expenses when you lodge your income
How to Categorize Common ecommerce Expenses on the Schedule C. Expenses Included
How to Categorize Common ecommerce Expenses on the Schedule C Advertising Capital Expenditures Commissions and fees Don't track Insurance Keep in own category Expenses Included Website Creation Domain
Getting and Keeping A Checking Account
Getting and Keeping A Checking Account You've decided to get a checking account. That's a good idea. Your money will be safe and you'll have a record of what you've paid for. You'll know how much you
Page 1 OLSON CPAs, PLLC CERTIFIED PUBLIC ACCOUNTANTS 2015 INCOME TAX ORGANIZER ********************************************************
Page 1 OLSON CPAs, PLLC CERTIFIED PUBLIC ACCOUNTANTS 2015 INCOME TAX ORGANIZER ******************************************************** Client Name: E-mail: Telephone: Day Evening NOTES: If we DID NOT
IR 261 August 2014. Direct selling. Tax facts for people who distribute for direct selling organisations
IR 261 August 2014 Direct selling Tax facts for people who distribute for direct selling organisations 3 Contents Introduction 4 4 How to get our forms and guides 4 Part
Personal Information. Name Soc. Sec. No. Date of Birth Occupation Work Phone Taxpayer: Spouse: Street Address City State Zip
Paid to Taxpayer Paid to Spouse Client Tax Organizer Please complete this Organizer before your appointment. Prior year clients should use a personalized Organizer. To request a personalized Organizer,
BOY SCOUTING AND TAXES
BOY SCOUTING AND TAXES This document describes the types of expenses a Boy Scout Adult Leader can and cannot deduct for tax purposes under the current U.S. tax laws. These expenses can be deducted under
AUTOMOBILE EXPENSES & RECORDKEEPING
February 2015 CONTENTS Who should keep records? Expenses to track Deductible expenses Keeping a kilometre log Business vs. personal Other motor vehicles The standby charge GST/HST and QST considerations
MONEY MANAGEMENT WORKBOOK
MICHIGAN ENERGY ASSISTANCE PROGRAM MONEY MANAGEMENT WORKBOOK Life is a challenge. As the saying goes, just when you're about to make ends meet, someone moves the ends. While it can be a struggle to pay
Understanding Financial Statements. For Your Business
Understanding Financial Statements For Your Business Disclaimer The information provided is for informational purposes only, does not constitute legal advice or create an attorney-client relationship,
DEDUCTING EXPENSES AS AN EMPLOYEE
July 2015 CONTENTS When are expenses deductible? What s deductible? Office rent/home office expenses Special considerations for ownermanagers Planning to maximize tax breaks Special situations Documentation
BALANCED MONEY WORKBOOK
BALANCED MONEY WORKBOOK 2 Why live in balance? Welcome to the balanced money approach to budgeting! Balance is a concept we hear a lot about eat a balanced diet, keep balance between work and the rest
Tax Return Questionnaire - 2015 Tax Year
SPECTRUM Spectrum Financial Resources LLP FINANCIAL 15021 Ventura Boulevard #341 310.963.4322 T RESOURCES Sherman Oaks, CA 91403 303.942.4322 F Tax Return Questionnaire - 2015 Tax
Handout # 2: Allocating Fundraising Expenses to the T3010
Handout # 2: Allocating Fundraising Expenses to the T3010 The following information is organized to assist a charity in allocating fundraising expenses to the appropriate reporting line on the T3010 Information
Guidelines for Self-Employed Persons
INLAND REVENUE DEPARTMENT Saint Lucia Guidelines for Self-Employed Persons Our Mission The Inland Revenue Department stands committed in its impartial treatment of its customers. We aim to provide efficient,
THINGS TO THINK ABOUT BEFORE YOU DEPLOY
THINGS TO THINK ABOUT BEFORE YOU DEPLOY As military members in general we all recognize that we face the possibility of being deployed. But have you really planned for deployment and for the effect.
TAXES: BUDGETING MADE EASY:
TAXES: BUDGETING MADE EASY: WHAT YOU NEED TO KNOW SAVE MONEY, SOLVE PROBLEMS A free publication provided by Consolidated Credit Counseling Services of Canada, Inc., This complimentary a registered publication
Review of a Company s Accounting System
CHAPTER Review of a Company s Accounting System Objectives After careful study of this chapter, you will be able to: 1. Understand the components of an accounting system. 2. Know the major steps in the
Preparing a budget template and presenting financial graphs using Excel
Preparing a budget template and presenting financial graphs using Excel KLA: STAGE: UNIT: Topic: HSIE Stage 5 Commerce Personal Finance Budgeting, loans and insurance Outcomes: 5.1 Applies consumer, financial,
Self-Employed Earnings Information Form
1 Claim reference number Self-Employed Earnings Information Form Please fill in this form if you or your partner is self-employed. If you are both self-employed in different businesses you should each
LEGAL & GENERAL HOME FINANCE. Guide to Lifetime Mortgages
LEGAL & GENERAL HOME FINANCE Guide to Lifetime Mortgages A lifetime mortgage could give you the freedom to really enjoy your retirement. We re delighted you re finding out more about lifetime mortgages.
Financial Planning. Introduction. Learning Objectives
Financial Planning Introduction Financial Planning Learning Objectives Lesson 1 Budgeting: How to Live on Your Own and Not Move Home in a Week Prepare a budget and determine disposable income. Identify
Limited Company Guide
Limited Company Guide A complete accountancy service for the small business across the United Kingdom What is a limited company? A limited company is a type of business whereby the owner s liability
Individual Income Tax Return Checklist
Individual Income Tax Return Checklist Income PAYG Summary Statement Deductions Motor Vehicle & Travel Expenses Appendix A Lump Sum Payments Receipts of work related expenses (eg. Employment Termination
Designing Your Budget
2 Designing Your Budget Budgeting is needed to get the most mileage out of your income. It is your road map for managing your money. Planning your spending is called Budgeting. Smart investing@your library
2015 PERSONAL INCOME TAX WORKSHEET
2015 PERSONAL INCOME TAX WORKSHEET TAXPAYER DETAILS Title Tax File Number Surname of Birth First Name Best Contact Number ( ) Other Name/s Or Mobile Telephone Occupation (not Title) Residential Address
General Ledger Account Explanations
General Ledger Account Explanations 1040 Exchange - This account is used as a holding For example: when having to make a manual debit & credit to two accounts to offset each other, this account is used.
Schedule C Line by Line. Self-Employment Tax Preparation Training
Schedule C Line by Line Self-Employment Tax Preparation Training Celebrating 39 years of providing free tax preparation and financial services to low and moderate income taxpayers in the Twin Cities and
Chapter 5 Business Expenses
Chapter 5 Business Expenses Key Concepts Trade or business expenses must be ordinary, necessary, and reasonable in amount to be deductible. Accrual-basis taxpayers deduct their expenses when the all-events
This guide explains the basics of how VAT works. It tells you where you can find more information and advice. On this page:
Introduction to VAT Value Added Tax (VAT) is a tax that's charged on most goods and services that VAT-registered businesses provide in the UK. It's also charged on goods and some services that are imported
SELF-EMPLOYMENT: IS IT FOR YOU?
July 2015 CONTENTS The advantages and disadvantages of being your own boss Can I become an independent contractor? Improving your chances The tax advantages of being self-employed Deducting expenses Selecting
3Budgeting: Keeping Track of Your Money
This sample chapter is for review purposes only. Copyright The Goodheart-Willcox Co., Inc. All rights reserved. 3Budgeting: Keeping Track of Your Money Chapter 3 Budgeting: Keeping Track of Your Money
Self-Employed Persons
Self-Employed Persons Deductible Expenditure 168 Broadway Avenue Phone (06) 357 6006 PO Box 788 Fax (06) 358 4716 PALMERSTON NORTH Web Self-Employed Persons Deductible Expenditure
Audience: Audience: Tim Sain: Audience:
My name is Tim Sain, and you guys are in a budgeting workshop. Has anyone ever done any kind of financial literacy? No. Budgeting? Workshop? Talked about money? Has anybody ever showed you how to spend
Expenses Procedure Guide
Expenses Procedure Guide racsgroup.com [email protected] Expenses Team The expenses team helps contractors submit their legitimately-incurred business expenses efficiently either online, by fax or by
Do you know where your money
Manage Your Money Lesson 2: Where Does Your Money Go?. Do you know where your money goes? You may say, House payments, car loan, utility bills, and food. But after that, things begin to get a bit fuzzy.
Grade 11 Essential Mathematics. Unit 2: Managing Your Money
Name: Grade 11 Essential Mathematics Unit 2: Page 1 of 16 Types of Accounts Banks offer several types of accounts for their customers. The following are the three most popular accounts used for everyday
Budgeting: Managing Your Money with a Spending Plan
Budgeting: Managing Your Money with a Spending Plan Budgeting: Managing Your Money with a Spending Plan Are you making the best use of your money? Do you have a handle on how much comes in each month and
Client Tax Organizer
Client Tax Organizer Please complete this Organizer before your appointment. Prior year clients should use the proforms Organizer provided. 1. Personal Information Name Soc. Sec.. Date of Birth Occupation
THINKING ABOUT STARTING YOUR OWN BUSINESS?
THINKING ABOUT STARTING YOUR OWN BUSINESS? Start-up Checklist 1. WHY DO YOU WANT TO BE IN BUSINESS? 2. IS YOUR IDEA VIABLE? 3. ARE YOU PREPARED FOR SELF-EMPLOYMENT? Self Analysis Questions 4. DO YOU NEED
Using Your Home for Daycare
Using Your Home for Daycare P134(E) Rev. 11 Is this booklet for you? I f you run a daycare in your home, you may be able to deduct business expenses from the income you report on your income tax return..
What You Need To Know. Trent s Student Guide to Financial Literacy 2012-13
What You Need To Know Trent s Student Guide to Financial Literacy 2012-13 Welcome to Trent University. In addition to the academic challenges students encounter in university, there are financial challenges
Section 1. Reimbursement Policy TRAVEL EXPENSES
Orthotics Prosthetics Canada (OPC) Travel & Expense Policy Dec. 2015 Policy It is the policy of the Corporation to reimburse employees and other officials and volunteers of the Corporation for certain
Completing the Accounting Cycle
Chapter 9 Completing the Accounting Cycle ANSWERS TO SECTION 9.1 REVIEW QUESTIONS (text p. 307) The Adjustment Process 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 218 Accounting 1 Student | http://docplayer.net/1435513-Everything-you-need-to-know-about-expenses.html | CC-MAIN-2017-04 | refinedweb | 6,086 | 50.26 |
The path to understanding ASP.NET’s process lies in examining the underlying infrastructure and observing how ASP.NET interacts with the .NET Framework base-class libraries and namespaces. The Framework supports web services and web forms through namespaces that host classes, such as System.Web.UI and System.Web.UI.WebControls. The System.Web.UI namespace contains classes and interfaces that allow you to create controls and pages that appear in your web applications as user interfaces on a web page. A major advantage offered by ASP.NET is running the controls on the server rather than on the client so you can programmatically control them at runtime.
The System.Web.UI namespace hosts the classes and interfaces especially designed for rendering elements on a web form. You can view all classes in the System.Web.UI namespace as a hierarchical tree beginning with the Control class. This is the mother of all controls. Buttons, text boxes, drop-down list boxes, and so on, derive from the Control class. It encapsulates both functionality and user interface properties for all member controls residing in this namespace. Class properties include Controls, Context, ClientID, EnableViewState, ID, NamingContainer, Parent, Site, TemplateSourceDirectory, UniqueID, Visible, and ViewState.
A collection of classes, interfaces, enumerations, and delegates makes up the namespace and are essential for developers to understand so that they can take full advantage of ASP.NET.
This table provides a complete list of System.Web.UI classes:
The following table contains the list of System.Web.UI interfaces:
The following table provides a list of System.Web.UI enumerations used when enumerating more than one item.
The final item in the System.Web.UI namespace, delegates, contains one item. It describes the method that handles any events raised when a user clicks on an image-based ASP.NET server control. Also, a delegate is a reference type that encapsulates a method that contains a specific signature and return type. | https://flylib.com/books/en/4.237.1.50/1/ | CC-MAIN-2020-45 | refinedweb | 324 | 51.44 |
Up to Design Issues
There is a common requirement for the design of a language on the web that it should allow for extensions, but it must allow a clear declaration as to whether understanding of an extension is a requirement to understanding of the document or whether it may be ignored. (See Evolvability)
Historically the lack of such a "mandatory field" has led to a complete inabaility to get any particular guaranteed behaviour be clients on the web.
This is essential for partial understanding and the smooth evolution of the web.
A simple requirement on a language is that it not only provide for its own extension, but provides for a way to explain whether a given extension is optional or not. This is a fundamental key to smooth evolution from the language to a new version.
There are manyways in which it can be done. It can be done term by term, or in bulk about a whole new language. It can be specified in the new document, in the schema for the new language.
XML provides in Namespaces a standard way of extending languages. It should also, in my opinion, provide a standard way to specify mandatopry or optional extensions.
I propose two things:
The simple assertion that language A is a sublanguage of language B means that the writer's intent is preserved if a dpcument in language A is converted into a document in language B just by relabelling every term as being from langauge B. For XML, this means that a receiver of namespace A can simply process it as though the namespace had been delcared as B.
This assertion has got to be simple enough to put into a document for cases where the functionality is needed without the receiver having to dereference a schema.
In XML there are three simple thiong you can do with an element you don't understand.
The schema langauge needs to be able to specify these very simply, and indeed it would be neatto be able to do it in a document for a given elemnt, or in one fell swoop for all the elements in a given namespace.
Languages which donot use XML should attend to these needs in their own way!
Up to Design Issues
Tim BL | http://www.w3.org/DesignIssues/Mandatory | crawl-002 | refinedweb | 382 | 57.2 |
This Akka stream sometimes doesn't finish
I have a graph that reads lines from multiple gzipped files and writes those lines to another set of gzipped files, mapped according to some value in each line.
It works correctly against small data sets, but fails to terminate on larger data. (It may not be the size of the data that's to blame, as I have not run it enough times to be sure - it takes a while).
def files: Source[File, NotUsed] = Source.fromIterator( () => Files .fileTraverser() .breadthFirst(inDir) .asScala .filter(_.getName.endsWith(".gz")) .toIterator) def extract = Flow[File] .mapConcat[String](unzip) .mapConcat(s => (JsonMethods.parse(s) \ "tk").extract[Array[String]].map(_ -> s).to[collection.immutable.Iterable]) .groupBy(1 << 16, _._1) .groupedWithin(1000, 1.second) .map { lines => val w = writer(lines.head._1) w.println(lines.map(_._2).mkString("\n")) w.close() Done } .mergeSubstreams def unzip(f: File) = { scala.io.Source .fromInputStream(new GZIPInputStream(new FileInputStream(f))) .getLines .toIterable .to[collection.immutable.Iterable] } def writer(tk: String): PrintWriter = new PrintWriter( new OutputStreamWriter( new GZIPOutputStream( new FileOutputStream(new File(outDir, s"$tk.json.gz"), true) )) ) val process = files.via(extract).toMat(Sink.ignore)(Keep.right).run() Await.result(process, Duration.Inf)
The thread dump shows that the process is
WAITING at
Await.result(process, Duration.Inf) and nothing else is happening.
OpenJDK v11 with Akka v2.5.15
See also questions close to this topic
- StreamingKMeans setSeed()
I need to train StreamingKMeans with a specific value for seed. When I run
val km = new StreamingKMeans(3, 1.0, "points") km.setRandomCenters(10, 0.5) val newmodel = km.latestModel.update(featureVectors, 1.0, "points") val prediction3 = id_features.map(x=> (x._1, newmodel.predict(x._2)))
it works fine. But when I am trining to use sedSeed:
km.setRandomCenters(10, 0.5).setSeed(6250L)
I am getting an error:
value setSeed is not a member of org.apache.spark.mllib.clustering.StreamingKMeans
How can I set the seed in this case?
- How do I take a list of keys that contains the value of the inputted key in the table in Scala
Given the following immutable Map("CAT" -> "ET", "BAT" -> "ET", "DIAMOND" -> "AHND", "HAT" -> "ET"), how do I take a list of keys that contains the value of the inputted key in the table in Scala? If inputted key is not in table, return an empty list.
My Attempt:
val word = "CAT" val table = Map("CAT" -> "ET", "BAT" -> "ET", "DIAMOND" -> "AHND", "HAT" -> "ET") if (table.get(find).isDefined) { List(table.get(find)) }
Input: "CAT"
Output: List("CAT", "BAT", "HAT")
//"CAT" has value "ET" //Return list of keys that contains the value of the inputted key in the table
- Sum vector columns in spark
I have a dataframe where I have multiple columns that contain vectors (number of vector columns is dynamic). I need to create a new column taking the sum of all the vector columns. I'm having a hard time getting this done. here is a code to generate a sample dataset that I'm testing on.
import org.apache.spark.ml.feature.VectorAssembler val temp1 = spark.createDataFrame(Seq( (1,1.0,0.0,4.7,6,0.0), (2,1.0,0.0,6.8,6,0.0), (3,1.0,1.0,7.8,5,0.0), (4,0.0,1.0,4.1,7,0.0), (5,1.0,0.0,2.8,6,1.0), (6,1.0,1.0,6.1,5,0.0), (7,0.0,1.0,4.9,7,1.0), (8,1.0,0.0,7.3,6,0.0))) .toDF("id", "f1","f2","f3","f4","label") val assembler1 = new VectorAssembler() .setInputCols(Array("f1","f2","f3")) .setOutputCol("vec1") val temp2 = assembler1.setHandleInvalid("skip").transform(temp1) val assembler2 = new VectorAssembler() .setInputCols(Array("f2","f3", "f4")) .setOutputCol("vec2") val df = assembler2.setHandleInvalid("skip").transform(temp2)
This gives me the following dataset
+---+---+---+---+---+-----+-------------+-------------+ | id| f1| f2| f3| f4|label| vec1| vec2| +---+---+---+---+---+-----+-------------+-------------+ | 1|1.0|0.0|4.7| 6| 0.0|[1.0,0.0,4.7]|[0.0,4.7,6.0]| | 2|1.0|0.0|6.8| 6| 0.0|[1.0,0.0,6.8]|[0.0,6.8,6.0]| | 3|1.0|1.0|7.8| 5| 0.0|[1.0,1.0,7.8]|[1.0,7.8,5.0]| | 4|0.0|1.0|4.1| 7| 0.0|[0.0,1.0,4.1]|[1.0,4.1,7.0]| | 5|1.0|0.0|2.8| 6| 1.0|[1.0,0.0,2.8]|[0.0,2.8,6.0]| | 6|1.0|1.0|6.1| 5| 0.0|[1.0,1.0,6.1]|[1.0,6.1,5.0]| | 7|0.0|1.0|4.9| 7| 1.0|[0.0,1.0,4.9]|[1.0,4.9,7.0]| | 8|1.0|0.0|7.3| 6| 0.0|[1.0,0.0,7.3]|[0.0,7.3,6.0]| +---+---+---+---+---+-----+-------------+-------------+
If I needed to taek sum of regular columns, I can do it using something like,
import org.apache.spark.sql.functions.col df.withColumn("sum", namesOfColumnsToSum.map(col).reduce((c1, c2)=>c1+c2))
I know I can use breeze to sum DenseVectors just using "+" operator
import breeze.linalg._ val v1 = DenseVector(1,2,3) val v2 = DenseVector(5,6,7) v1+v2
So, the above code gives me the expected vector. But I'm not sure how to take the sum of the vector columns and sum
vec1and
vec2columns.
I did try the suggestions mentioned here, but had no luck
- Get the original ActorRef or path from a PromiseActorRef
How can I get the original
ActorReffrom a
PromiseActorRef(created by
akka.pattern.ask) when overriding
Actor#aroundReceive? I'm trying to add some instrumentation to trace messages in my actor system.
override def aroundReceive(receive: Actor.Receive, msg: Any): Unit = { sender().path // This is something starting with "/temp/..." since it // references the PromiseActorRef created by an ask, // instead, I would like to get a reference or path // to the actor invoking ask originally super.aroundReceive(receive, msg) }
- Get reference of router from routee-Akka
This question is a follow up to: Akka Routing: Reply's send to router ends up as dead letters
I'm facing the same problem. It is given in the answer that
"Note that different code would be needed if the routees were not children of the router, i.e. if they were provided when the router was created."
I want to know What is that different code and how does it work? And is there any other way to communicate with the Router other than this method?
It'd be good if exlpained with code snippets or links to projects where it is used.
- Simple server-push broadcast flow with Akka
I am struggling to implement a - rather simple - Akka flow. Here is what I think I need:
I have a single server and n clients and want to be able to react to external events by broadcasting messages (JSON) to the clients. The clients can register/deregister at any time.
So for example:
- 1 client is registered
- server throws an event ("Hello World!")
- server broadcasts a "Hello World!" to all clients (one client)
- a new client opens a websocket connection
- server throws another event ("Hello Akka!")
- server broadcasts a "Hello Akka!" to all clients (two clients)
Here is what I have so far:
def route: Route = { val register = path("register") { // registration point for the clients handleWebSocketMessages(serverPushFlow) } } // ... def broadcast(msg: String): Unit = { // use the previously created flow to send messages to all clients // ??? } // my broadcast sink to send messages to the clients val broadcastSink: Sink[String, Source[String, NotUsed]] = BroadcastHub.sink[String] // a source that emmits simple strings val simpleMsgSource = Source(Nil: List[String]) def serverPushFlow = { Flow[Message].mapAsync(1) { case TextMessage.Strict(text) => Future.successful(text) case streamed: TextMessage.Streamed => streamed.textStream.runFold("")(_ ++ _) } .via(Flow.fromSinkAndSource(broadcastSink, simpleMsgSource)) .map[Message](string => TextMessage(string)) }
- shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for ActorSystem[mpe] java.lang.StackOverflowError: null
I am working on a fix which needs to accept a SOAP XML Request which is less than 1,00,000 threshold value. So that we can validate large xml documents before processing.
Now, I am confused about the error reporting by akka when the threshold value is less than 1,00,000. I noticed the if the elements under one parent is more than 2000 I am getting this error. if the elements are divided with multiple parent elements we are not getting the error. Please help me to figure out the below the error from akka.
I have also to tried with disabling "akka.jvm-exit-on-fatal-error" in the configuration. akka { jvm-exit-on-fatal-error = off actor { provider = "akka.remote.RemoteActorRefProvider" } remote { enabled-transports = ["akka.remote.netty.ssl"] . . . } }
Example of Soap Request Body:
<soapenv:Body> <cai3:Create> <cai3:Attributes> <CreateAttributes attributeId="1"> <attributeId>12345678</attributeId> <!--Zero or more repetitions:--> <node1 attributeId="12345678"> <node1>12345678</node1> <node1/> </node1> ....... ....... ....... ....... ....... ....... ....... on so on upto 3000 same elements </CreateAttributes> </cai3:Attributes> </cai3:Create> </soapenv:Body>
Exception Log
Module 2019-02-13 17:07:20,669+0800 [t-dispatcher-16] ERROR [akka.actor.ActorSystemImpl] Uncaught error from thread [mpe-akka.remote.default-remote-dispatcher-6]: null, shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for ActorSystem[mpe] java.lang.StackOverflowError: null at java.lang.Exception.<init>(Exception.java:76) [na:1.8.0_172] at java.lang.ReflectiveOperationException.<init>(ReflectiveOperationException.java:89) [na:1.8.0_172] at java.lang.reflect.InvocationTargetException.<init>(InvocationTargetException.java:72) [na:1.8.0_172] at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source) [na:na] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [na:1.8.0_172] at java.lang.reflect.Method.invoke(Method.java:498) [na:1.8.0_172] at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1128) [na:1.8.0_172] at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) ]
- Howto integrate akka streams Websocket with Actor to support backpressure
I want to achieve an integration between Akka Streams Websocket and an Actor that supports back-pressure.
My websocket protocol supports:
- Request/Response pattern where each Request results exactly in one Response
- Event pattern where an Event can be published to the WS at any time
Because of the Event pattern I cannot use a simple
Flowbut need to split into
Sinkand
Sourceso that I can send an Event without receiving a Message via the WS, at least this is how I understand it.
In the future the Requests which are received on the WS are forwarded via grpc to some service and when this services responds then this Response shall be also returned via WS. Ideally I want to have backpressure through this whole chain.
My current implementation of just a simple Ping/Pong protocol looks like this but
- I am not sure if this is the best way to implement it.
- I am not sure what to do in the error cases of the
offermethod in the Actor
- I am not sure if
flatMapConcatthe
TextMessage.textStreamis the way to go when I want to deserialize a
TextMessage
- I am not sure if later on I can support backpressure when I send messages further on from the Actor via grpc to some other service
I would really appreciate if somebody could review my code and tell me what I can do better here.
def wsFlow:Flow[Message, Message, NotUsed] = { // the actor that is used to handle a single WS val ws:ActorRef = system.actorOf(WebSocketActor.props()) // used to send messages via the WS to the client val wsSender:Source[Message, NotUsed] = Source .queue(bufferSize = 500, overflowStrategy = OverflowStrategy.backpressure) .map { response:Response => response match { case pr:PingResponse => TextMessage(pr.toJson.compactPrint) } } .mapMaterializedValue { wsQueue => // the wsQueue is used to send messages to the client ws ! WsConnect(wsQueue) NotUsed // dont expose the wsQueue, change materialized value to NotUsed } // used to receive messages via the WS from the client val wsHandler:Sink[Message, NotUsed] = Flow[Message] .flatMapConcat { case tm:TextMessage => tm.textStream case bm:BinaryMessage => // ignore binary messages but drain content to avoid the stream being clogged bm.dataStream.runWith(Sink.ignore) Source.empty } .map(text => JsonParser(text).convertTo[Request]) .to(Sink.actorRef(ws, WsDisconnect)) Flow.fromSinkAndSource(wsHandler, wsSender) }
class WebSocketActor(implicit ec:ExecutionContext) extends Actor { private var wsQueue:Option[SourceQueueWithComplete[Response]] = None override def receive: Receive = { case WsConnect(ref) => wsQueue = Some(ref) case WsDisconnect => wsQueue.foreach(_.complete()) wsQueue = None case ping:PingRequest => val response = PingResponse(200, ping.clientRequestId, Version(1)) wsOffer(response) } private def wsOffer(msg:Response):Unit = wsQueue.foreach(queue => { queue.offer(msg).foreach { case QueueOfferResult.Enqueued ⇒ () case QueueOfferResult.Dropped ⇒ ??? case QueueOfferResult.Failure(ex) ⇒ ??? case QueueOfferResult.QueueClosed ⇒ ??? } }) } | http://quabr.com/52849433/this-akka-stream-sometimes-doesnt-finish | CC-MAIN-2019-09 | refinedweb | 2,131 | 50.33 |
XML: Definition from Answers.com
[3]. XML's set of tools helps developers in creating web pages but its
usefulness goes well beyond that. XML, in combination with other standards, ...
Category:User xml-3 - Wikipedia, the free encyclopedia
Feb 15, 2006 ... Pages in category "User xml-3". The following 123 pages are in this category,
out of 123 total. This list may not reflect recent changes ...
en.wikipedia.org/wiki/Category:User_xml-3
XML-RPC: Information from Answers.com
Oct 9, 2008 ... XML-RPC ( XML R emote P rocedure C all) A message-based protocol based ... The
patent is assigned to webMethods, located in Fairfax, VA. ...
Namespaces in XML 1.0 (Second Edition)
Relative URI deprecation: Results of W3C XML Plenary Ballot on relative URI
References In namespace declarations 3-17 July 2000 , Dave Hollander and C. M.
...
XML schema: Information from Answers.com
3, page 76-87, September 2000; Taxonomy of XML Schema Languages using Formal
Language Theory by Makoto Murata, Dongwon Lee, Murali Mani, Kohsuke Kawaguchi,
...
Social Panorama
The most significant decreases (of over 3 percentage points per year) .....
represents a decline of barely 3%, which can by no means be interpreted as a ... 34733/PSI2008-SintesisLanzamiento.pdf
Standard Generalized Markup Language: Definition from Answers.com
2.1 Markup Minimization. 3 Derivatives. 3.1 XML. 4 Applications. 4.1 HTML; 4.2
DocBook; 4.3 Other. 5 See also; 6 References; 7 External links ... standard-generalized-markup-language-1
Thinking XML: XML meets semantics, Part 3
Uche Ogbuji discusses several recent events in XML semantic transparency and XML
knowledge management, including new developments in ebXML and RosettaNet.
Ajax: Information from Answers.com
[3]; XML is not required for data interchange and therefore XSLT is not required
for the manipulation of data. JavaScript Object Notation (JSON) is often ...
The "3DM" XML 3-way Merging and Differencing Tool
Aug 18, 2006 ... The 3DM tool is a tool for performing 3-way merging and differencing of XML
files. Unlike line-based tools, such as diff and diff3, ... | http://www.answers.com/topic/xml-3 | crawl-002 | refinedweb | 336 | 52.56 |
vincent juma1,159 Points
hello everyone, am quite stuck on the below datetime code. kindly help me complete it.. def timestamp_oldest():
1 Answer
Jeff MudayTreehouse Moderator 24,401 Points
POSIX Timestamps are really big numbers which represent date/time. See the example below for two friends, Justin and Hannah. Justin was born December 4, 1992. Hannah was born February 12, 1995. Who is older? Justin, of course! But he will have a smaller number for a timestamp because he was born before her. See below.
import datetime import time # suppose two friends birthdays... Justin and Hanna # make datetime objects justin_dt and hannah_dt justin_dt = datetime.datetime(1992,12,04) hannah_dt = datetime.datetime(1995,2,12) # convert into timestamps justin_ts and hannah_ts justin_ts = time.mktime(justin_dt.timetuple()) hannah_ts = time.mktime(hannah_dt.timetuple()) # print these out to see what they look like print("Justin's birthday = {}".format(justin_dt)) print("Justin's timestamp = {}".format(justin_ts)) print("Hannah's birthday = {}".format(hannah_dt)) print("Hannah's timestamp = {}".format(hannah_ts))
Justin is older, and his timestamp for his birthday is a SMALLER number
Justin's birthday = 1992-12-04 00:00:00 Justin's timestamp = 723445200.0 Hannah's birthday = 1995-02-12 00:00:00 Hannah's timestamp = 792565200.0
Now... we can exploit that these are numbers to easily sort them with this function...
def oldest_timestamp(*args): # this uses args, so we have to convert it to a list ts_list = list(args) # sort the list ts_list.sort() # return the first element in the list return ts_list[0]
finally, we can do some testing to see if Justin is indeed older!
# find the older timestamp older_ts = oldest_timestamp(hannah_ts, justin_ts) print("The older timestamp is {}".format(older_ts)) # make the timestamp a date_object older_dt = datetime.datetime.fromtimestamp(older_ts) print("The older datetime object = {}".format(older_dt))
Success! Justin's smaller timestamp can be back-converted to show his original birthday.
The older timestamp is 723445200.0 The older datetime object = 1992-12-04 00:00:00 | https://teamtreehouse.com/community/hello-everyone-am-quite-stuck-on-the-below-datetime-code-kindly-help-me-complete-it | CC-MAIN-2020-34 | refinedweb | 327 | 62.24 |
, 10 months ago.
GR_Peach libraries broken?
I updated my offline libraries for GR_Peach today (to mbed V134 and mbed-rtos V123) and found that just adding hardware declarations to a simple threaded example will break the code. This happens with both the online compiler and the GCC EABI offline compiler.
I strongly suspect this is caused by a lack of destructors, since I have to remove the _ _wrap_ _free_r sections from LD_FLAGS to get it to link in the offline version.
The following code does not run, but it will if you comment out the declarations for InterruptIn, SPI, and RawSerial. The main function will run, but the thread won't if you take out the last two but leave the InterruptIn line in.
Note that these are just declarations and don't do anything but initialize hardware (I'm not trying to use the hardware in the code). Yes, I'm positive this code would run correctly under mbed V113 (except for the new thread.start() functions).
Here's the code:
#include "mbed.h" #include "rtos.h" Serial pc(USBTX, USBRX); DigitalOut redled(LED_RED); DigitalOut greled(LED_GREEN); DigitalOut bluled(LED_BLUE); DigitalOut useled(LED_USER); InterruptIn irq_data(P2_14); // <--- Leave this line, blink_thread() won't run SPI spi_data(P10_14, P10_15, P10_12, P10_13); // SPI0 // <--- Leave these two lines, nothing runs RawSerial uart_data(P8_14, P8_15); // UART4 // <-' Thread h_task1_thread (osPriorityRealtime, 20480L, NULL); Thread h_task2_thread (osPriorityHigh, 20480L, NULL); Thread h_task3_thread (osPriorityNormal, 20480L, NULL); Thread h_task4_thread (osPriorityLow, 20480L, NULL); Thread h_blink_thread (osPriorityNormal, 20480L, NULL); void blink_thread () { useled = 1; while (true) { Thread::signal_wait(0x1); useled = !useled; } } int main() { h_blink_thread.start(blink_thread); while(1) { bluled = 1; wait(0.2); bluled = 0; wait(0.2); h_blink_thread.signal_set(0x1); } }
Import programpeach_blink
This program does *not* run correctly if declarations are left in.
As always, thanks in advance for any help or suggestions.
1 Answer
2 years, 10 months ago.
You don't need to have both mbed and mbed-rtos. You should just import, then you should have this as the top of your program:
#include "mbed.h
I don't remember the details now, but I thought I started that way and it didn't recognize the thread declaration. Maybe I still had the #include "rtos.h" line in, which would have made it mad.
Thanks!posted by 03 Feb 2017
Well, thread declaration has changed a bit in the past year. I am seeing your issue though. I believe the InterruptIn line is the actual culprit. This needs investigation.posted by 03 Feb 2017\ I've created an issue that you can track here.posted by 03 Feb 2017
I'm Renesas mbed team.
Sorry for this late reply. I identified the cause for issue 3694. I will PR against this issue soon, contact you after I PR.posted by 20 Feb 2017 | https://os.mbed.com/questions/76869/GR_Peach-libraries-broken/ | CC-MAIN-2019-51 | refinedweb | 465 | 66.94 |
Surface material definition node. More...
#include <Inventor/nodes/SoMaterial.h>
Surface material definition node.
This node defines the current surface material properties for all subsequent shapes. SoMaterial sets several components of the current material during traversal. The ambientColor, diffuseColor, emissiveColor, specularColor and shininess fields are interpreted according to the classic OpenGL lighting model. The transparency field is effectively the inverse of "opacity" or "alpha value".
If lighting is turned off (SoLightModel set to BASE_COLOR), only the diffuse color and transparency fields are used to render geometry.
Multiple values can be specified for the diffuseColor and transparency fields. Different shapes interpret materials with multiple values differently. To bind materials to shapes, use an SoMaterialBinding node.
Several other nodes can be used to set diffuse color and transparency.
Lighting and material RGB values:
Override material:
Transparency:
SoBaseColor, SoLightModel, SoMaterialBinding, SoPackedColor, SoVertexProperty, SoDirectVizManager
Creates a material node with default settings.
Set the state of the override field.
see SoNode::setOverride doc.
Reimplemented from SoNode.
Ambient color of the surface.
Default is 0.2 0.2 0.2.
Ambient reflectance affects the overall color of the object. Because diffuse reflectance is brightest where an object is directly illuminated, ambient reflectance is most noticeable where an object receives no direct illumination. An object's total ambient reflectance is affected by the global ambient light (see SoEnvironment) and ambient light from individual light sources. Like diffuse reflectance, ambient reflectance is not affected by the position of the camera.
Diffuse color(s) of the surface.
Default is 0.8 0.8 0.8.
Diffuse reflectance plays the most important role in determining the appearance of an object. It's affected by the color of the incident light(s) and the angle of each incident light relative to the object's normal direction. (It's most intense where the incident light falls perpendicular to the surface.) The position of the camera doesn't affect diffuse reflectance at all.
Emissive color of the surface.
Default is 0 0 0.
Emissive color makes an object appear to be giving off light of that color, independent of any lights (or lack of lights) in the scene. It can be useful for highlighting selected objects in the scene.
DirectViz rendering only.
Specifies that all the shapes using this material node will receive shadows from other shapes when rendering using DirectViz.NOTE: field available since Open Inventor 6.1
DirectViz rendering only.
Specifies the reflective color of the shape. When set to black (0,0,0), the object is not reflective. To simulate a perfect mirror, the reflectiveColor should be set to white (1, 1, 1), and all other color field values to black (0, 0, 0). The reflective component is added to the overall color of the object.NOTE: field available since Open Inventor 6.1
Shininess coefficient of the surface.
Values can range from 0.0 to 1.0. Default is 0.2.
The dot product of the vector reflected by the surface normal and the inverted light vector is raised to the "Shininess" power. The higher the shininess number, the smaller the resulting specular highlight turns out to be.
Specular color of the surface.
Default is 0 0 0.
Specular reflection from an object produces highlights. Unlike ambient and diffuse reflection, the amount of specular reflection does depend on the location of the camera - it's brightest along the direct angle of reflection. To see this, imagine looking at a metallic ball outdoors in the sunlight. As you move your head, the highlight created by the sunlight moves with you to some extent. However, if you move your head too much, you lose the highlight entirely.
This field specifies the color of the reflected light. The shininess field controls the size and brightness of the highlight.
Transparency value(s) of the surface.
Values can range from 0.0 for opaque surfaces to 1.0 for completely transparent surfaces. Default is 0 (opaque).
If the transparency type is SoGLRenderAction::SCREEN_DOOR then only the first transparency value will be used (See SoGLRenderAction::SCREEN_DOOR description). With other transparency types, multiple transparencies will be used, if the SoMaterial node contains as many transparencies as diffuse colors. If there are not as many transparencies as diffuse colors, only the first transparency will be used.
Transparency is the inverse of "opacity" or "alpha" value. | https://developer.openinventor.com/refmans/9.9/RefManCpp/class_so_material.html | CC-MAIN-2020-16 | refinedweb | 718 | 52.15 |
Lite.)
The primary benefits of these 2 DLLs are as follows:
The same applies to creating a zip archive. You can create the zip archive on disk, in memory, or to a pipe. And, the contents of this zip archive can come from diskfiles, memory-buffers, pipes, or even a combination of any/all of the preceding.
Given this flexibility, you're not required to write out your files to a temporary directory before using them. One noteworthy feature is that you can unzip directly from an embedded resource into a memory buffer or into a diskfile, which is great for installers. Another useful feature is the ability to create your zip in dynamically growable memory backed by the system pagefile (i.e., you don't need to guess the allocation size of a memory buffer before zipping some stuff into that memory buffer. You can let the DLL grow the memory buffer on-the-fly, as needed, on your behalf).
And an update to the DLL means that all programs using it automatically obtain the update without needing to be recompiled.
The limitation of these DLLs is:
To allow your C/C++ code to create a zip archive, add the file litezip.lib to your project, and #include "LiteZip.h" to your source code.
#include "LiteZip.h"
To allow your C/C++ code to unzip an archive, add the file liteunzip.lib to the project and #include "LiteUnzip.h" to your source code.
Zip and unzip can co-exist happily in a single application. Or, you can use only the one you need if you're trying to reduce size.
Of course, you must distribute LiteZip.dll and/or LiteUnzip.dll with your application.
The following code snippets show how to use zip/unzip. They use ANSI, but #define'ing UNICODE will use the Unicode version of the functions instead. Error checking has been omitted for brevity.
Here's an example of the above. Assume that we have two files on disk, named "simple.bmp" and "simple.txt". We wish to zip them up into a zip archive named "simple1.zip".
#include <Windows.h>
#include "LiteZip.h"
HZIP hz;
ZipCreateFile(&hz, "simple1.zip", 0);
ZipAddFile(hz, "simple.bmp");
ZipAddFile(hz, "simple.txt");
ZipClose(hz);
The downloaded example zip file contains a similar example, with error-checking, and also dynamic linking to LiteZip.dll. (With dynamic linking, you don't add LiteZip.lib to your project. And LiteZip.dll is not loaded when your app first starts. It is loaded only when you call LoadLibrary).
Pass your ZIPENTRY, and the HUNZIP handle supplied by UnzipOpenFile, to UnzipGetItem. UnzipGetItem will fill in the ZIPENTRY with information about that item. This includes its name, its uncompressed size, its modification date, etc. If you want to extract only a particular item, rather than calling UnzipGetItem, you can fill in your ZIPENTRY's Name field with the desired item's name, and pass your ZIPENTRY to UnzipFindItem to fill in your ZIPENTRY with other information about that item.
Name
UnzipFindItem
Finally, call UnzipItemToFile to extract that item to a disk file. Pass your ZIPENTRY, the HUNZIP handle supplied by UnzipOpenFile, and the filename you wish the item to be saved to. (You can use the ZIPENTRY's Name field if you want to use the same name it had within the archive). UnzipItemToFile will extract the item and save it to disk, creating any needed directories.
UnzipClose
ZipOpenFile
Here's an example of the above. Assume that we have a zip archive on disk named "simple1.zip". We'll extract all its items, using the same filenames as within the archive. No encryption is used.
#include <Windows.h>
#include "LiteUnzip.h"
HUNZIP huz;
ZIPENTRY ze;
DWORD numitems;
ZipOpenFile(&huz, "simple1.zip", 0);
ze.Index = (DWORD)-1;
UnzipGetItem(huz, &ze);
numitems = ze.Index;
for (ze.Index = >0; ze.Index < numitems; ze.Index++)
{
UnzipGetItem(huz, &ze);
UnzipItemToFile(huz, ze.Name, &ze);
}
UnzipClose(huz);
The downloaded example UnzipFile contains a similar example, with error-checking, and also dynamic linking to LiteUnzip.dll. (With dynamic linking, you don't add LiteUnzip.lib to your project. And LiteUnzip.dll is not loaded when your app first starts. It is loaded only when you call LoadLibrary).
UnzipFile
Here's an example of extracting only the item named "readme.txt" from the same zip archive:
HUNZIP huz;
ZIPENTRY ze;
ZipOpenFile(&huz, "simple1.zip", 0);
lstrcpy(ze.name, "readme.txt");
UnzipFindItem(huz, &ze, 0); // Pass a 1 for case-insensitive find
UnzipItemToFile(huz, ze.Name, &ze);
UnzipClose(huz);
This technique is useful for small games, where you want to keep all data files bundled up inside the executable, but reduce their size by zipping them first. It may also be useful for an installer, where the files to be installed are zipped into an archive that is embedded in the installer EXE's resource.
Assume our project has a .RC file with the line
1 RCDATA "file.zip"
to embed the zipfile as a resource. Let's also assume that this zip archive contains an item named "sample.jpg", and we wish to unzip that one item into a memory buffer.
The technique is very similar to the above unzip example, except:
UnzipOpenBuffer
RCDATA
UnzipItemToBuffer
UnzipItemToFile
UncompressedSize
GlobalAlloc
new
HUNZIP huz;
ZIPENTRY ze;
char *buffer;
UnzipOpenBuffer(&huz, 0, 1, 0)
lstrcpy(ze.name, "sample.jpg");
UnzipFindItem(huz, &ze, 0);
buffer = (char *)GlobalAlloc(GMEM_FIXED, ze.UncompressedSize);
UnzipItemToBuffer(huz, buffer, ze.UncompressedSize, &ze)
UnzipClose(huz);
// Here you would do something with the contents of buffer.
GlobalFree(buffer);
The downloaded example UnzipResource shows how an installer EXE may unzip the entire contents of an archive embedded in its resources.
UnzipResource
You can also zip up some existing file into an archive that is created in a memory buffer. You can either supply your own memory buffer (and make sure it's big enough to accommodate the resulting archive), or you can simply let LiteZip.dll allocate the buffer from system paged memory. In the latter case, the DLL can automatically grow the buffer on-the-fly as needed.
Furthermore, you can add the contents of some memory buffer.
The downloaded example ZipMemory shows the zipping the contents of a memory buffers into an archive created in memory. The example lets the DLL allocate system paged memory for the resulting archive. It's similar to the zip example above except:
ZipMemory
zipCreateBuffer
ZipAddBuffer
ZipAddFile
ZipGetMemory
Sometimes, you may need to zip up some data with the resulting archive not having a ZIP header, nor ZIP "central directory" in it. I'll refer to this as a "raw" zip. For example, this is the case with a compressed ID3 tag. For this purpose, LiteZip offers a few functions to add data to a raw archive: ZipAddFileRaw, ZipAddHandleRaw, ZipAddPipeRaw, and ZipAddBufferRaw. Only one item can be added to such an archive. To later unzip the data item from this archive, you will need to use one of LiteUnzip's functions to open a raw archive: UnzipOpenFileRaw, UnzipOpenBufferRaw, or nzipOpenHandleRaw. You can then unzip the one item by calling UnzipGetItem, but first you will have to know both the compressed size of the archive, and also the size of the item when it is compressed. You stuff these two values in the ZIPENTRY's CompressedSize and UncompressedSize fields, respectively, before you call UnzipGetItem. The example ZipMemoryRaw shows how to create a raw archive. And the example UnzipMemRaw shows how to extract the one item from that same raw archive.ir
This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)
exactly
#ifdef WIN32
...
#ifndef CP_UTF8
#define CP_UTF8 65001
#define DIRSLASH_CHAR
#endif
#else
...
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.
News on the future of C# as a language | http://www.codeproject.com/Articles/13370/LiteZip-and-LiteUnzip?fid=278047&df=90&mpp=10&noise=1&prof=True&sort=Position&view=None&spc=None&fr=11&PageFlow=FixedWidth | CC-MAIN-2014-10 | refinedweb | 1,321 | 58.89 |
#TODOs Never Get To-Done
Posted on
by
Jared Carroll in Process
Over time all software begins to rot. At first a young codebase is small and lean, it’s a pleasure to work on, a single developer may even be able to understand the entire codebase. However, iteration after iteration time constraints and poorly specified features begin to manifest themselves in the codebase. TODOs are everywhere, tests are pending, waiting on unanswered questions related to their pending functionality, half-baked ideas remain commented out so we won’t “lose” them, new developers join the team and contribute to the rot – the broken window theory is in full swing.
Uncle Bob tells us that our goal as developers is “not just working code but clean code” and that we should “always check in code better than you found it”. As professional developers it’s our responsibility to take the initiative in keeping our software maintainable. Let’s take a closer look at some of the above smells.
TODOs
# TODO: Update protected instance variables list # TODO: Validate that the characters are UTF-8. If they aren't, # you'll get a weird error down the road, but our form handling # should really prevent that from happening # TODO: button_to looks at this ... why? # TODO: Remove these hacks
Your codebase is not the place for TODOs. The problem with TODOs is that most developers quickly just glance over them, ignoring them because they didn’t write them. Sadly version control often reveals that they’ve been around for quite some time. Is a TODO even still applicable? Was it fixed and someone forgot to remove the TODO? Is there an existing ticket for this TODO?
Move this “necessary” work where it belongs; to your project management/bug tracking tool with the rest of your codebase’s features and bugs. Do the same to FIXMEs, REFACTORs and WTFs.
Pending Tests
describe '.recent' do it 'does NOT find admins' end describe '#save' do it 'normalizes its website URL' do pending end end
Every testing tool seems to have the ability to mark a test as pending; RSpec has
#pending, Cucumber has @wip, JUnit and NUnit have ignore. These pending tests appear in the output on every test run. Despite this very visible characteristic developers often will let pending tests live on for ages. Test run after test run the same pending tests are output and over time the team learns to live with it.
Pending tests are useful as a kind of TODO list of tests during TDD. And it’s fine to use them while developing a feature in a topic branch but make sure they’re no longer pending when you finish your work and its time to merge it into an integration branch (e.g. master, develop/next, staging, production, etc).
Commented Out Code
def save kick = super_save # message = { ball => self }.to_json # $kicks_machine.publish message kick end
Comments in code are distracting, commented out code is even more distracting. It often sits there for days, weeks, or even months; each passing developer scared to delete it. Even though we’re using version control and we know that every modification made to every file is completely recoverable for some reason we still don’t delete commented out code.
What to Do
Use the following steps to deal with all this cruft, your codebase will thank you for it.
git blame file
- Contact the author to discover why
- Create a story/ticket for the TODO/pending test/commented out code
- Delete the code
Clean Code
Taking the initiative and raising the standard of code cleanliness is contagious. Suddenly your teammates will notice the increase in quality and start to adopt the same techniques. Slowly the codebase improves; there are less distractions, it appears more focused, it starts to look like it was written by developers who take pride in their work. Addressing the above smells are the kind of small changes that individually might not seem like much but over time can make a big difference.
Feedback
Your feedback
Christian Bradley
January 26, 2011 at 9:58 am
I’d also suggest adding ‘grep todo -ir .’ to the default rake task. Those TODOs being printed out on every run *have* to get annoying after awhile
Christian Bradley
January 26, 2011 at 10:00 am
By the way, I agree fully with using pending specs as TODOs… the added context helps a ton, and – like grep’ing TODOs in code, these are displayed on every rake as well.
Christian Bradley
January 26, 2011 at 10:06 am
I would disagree, however, that comments in code are distracting. If the comments are sparse but placed for readability… I actually find it very helpful for developers to comment blocks of code so that I do not have to run them through my own internal parser.
Ruby reads much more like the English language than most others, but I still find that when picking up stories it can be very time consuming to scan through lines of code where a single well placed comment would give me the gist.
Commented-out code has a place within a temporary workflow but never within a master commit. If it’s something you want to know how to do later, create a gist or email it to yourself for God’s sake. I’m with you on that one.
Anonymous
January 26, 2011 at 12:46 pm
Show me the evidence.
It’s really simple. There’s already a theory, now show me the evidence. If you can’t do that don’t bother to write a blog post and act like you’re an authority.
Michael Wynholds
January 26, 2011 at 2:33 pm
What do you mean: “the evidence”? This post is not a theory predicting future behavior, it’s one developer’s opinion of the value of TODOs in the codebase. If you disagree with it, then that’s great – I’d like to hear your opinions as well, and we can have a useful dialog via these comments.
I am curious, do you think the codebase is the right place for TODOs, as opposed to a project management or bug tracking system? If so, is there a timeframe along which a TODO becomes less useful?
Give us your opinion.
Rob Pak
January 26, 2011 at 5:16 pm
# TODO: Gather and show evidence to Anonymous
# TODO: Act like an authority
# TODO: Wear sunglasses at night
Jared Carroll
January 27, 2011 at 8:45 am
@anonymous – I don’t have any empirical evidence that the above smells cause code rot. However in my experience these smells are exactly the kind of poor code that because they are never addressed, replicate and worsen throughout a codebase.
dude
August 10, 2011 at 7:44 am
WHOOSH! Where do you work, Anonymous? We can make sure to avoid it like the plague.
Werehamster
January 26, 2011 at 4:50 pm
Sorry Anonymous , but I’d have to agree with the original post.
Surely all you’d have to do is look in your own code and see how many TODOs are present and then use the version control to see how long they have been there. If any of them are more than a month or so old then you know you’ve got a problem because now there’s two places you need to look to get a list of what needs to be done.
I for one know that there’s a bunch of them in my latest project (a quick check reveals one from 22nd of July), and they should indeed be put into the ticketing system, because I have obviously forgotten about them.
If you are not using a ticketing system, then I don’t see any problems with just using a todo list inside the code. But the important thing is that the list should be in one place, and one place only.
Pafcio00
January 27, 2011 at 12:29 am
//TODO is a great thing to use as a bookmark in code so you wont miss a thing when you must jump to another task leaving something unfinished.
I use TODO’s sometimes in setters to bookmark those that need additional validation (but I don’t want to write it just yet).
Thanks to IDE’s those TODO’s are easy to find and it makes work easier sometimes.
Of course before version release all TODO’s must be removed.
Christian Bradley
January 27, 2011 at 12:21 pm
Santosh Kumar
February 4, 2011 at 8:35 am
Completely agree, #TODO’s are a sign of the ‘refactor’ step being skipped in red-green-refactor. Contacting devs who wrote the #TODO’s and figuring out if a story needs to be created is a great idea.
I do like having comments though. I find that there are times, when using local vars to self document steps leads to long’ish variable names and that kind of gets in the way of readability. A couple of comments above a block of code, that has terse local variable names, I feel reads better.
Georg Ledermann
August 10, 2011 at 7:45 am
Nice to read this. I was thinking the same three years ago:
Ken Collins
August 10, 2011 at 7:49 am
Great article. I have never allowed #TODO’s in my large legacy day job app. I even set a rule that they must be cleared out before each release cycle and always be scoped to an issue/ticket. If not, then they must be deleted or transferred to said issue/ticket system.
On another note, we use #CHANGED a lot. And always scope them to a particular component/gem. So whenever we upgrade a gem dep or library, we checked all the #CHANGED notes to see what we need to re-monkey patch and/or totally remove. A few working examples.
# CHANGED [Rails3] This monkey patch is no-longer needed.
# CHANGED [FactoryGirl] Version 2.0.4 should have this fix in issue #140, remove then.
Albert Chyickenstok
August 6, 2015 at 5:50 pm
We ban the word todo in our code. Banning a word instantly improves the code base, because it makes some things impossible! For example, we banned the word “bug” when speaking about our code, and instantly the bug count dropped to zero and we all got raises.
It’s so obvious, I don’t know why more people haven’t done it. Next up I’m going to lobby dictionary writers, and the ministry of information to ban the word TODO. It’s just so icky and unprofessional. | http://blog.carbonfive.com/2011/01/26/todos-never-get-to-done/ | CC-MAIN-2016-07 | refinedweb | 1,778 | 69.52 |
This is a consolidation of stuff on Stackoverflow. It works with Django 1.7.
The goal, format floats, with 2 decimal places and commas every three digits to the left of the decimal:
- Add {% load humanize %} to the top of the template
- {{ my_float_var|floatformat:”2″|intcomma }}
On Stackoverflow, some posts tell you to add humanize to your installed apps in settings. I suspect that sometime in the past, humanize was not part of the Django standard library. I am using Django 1.7 and it was not necessary.
Add $ Prefix
If you want to add a prefix such as $ when there is an amount, but not when the field is blank, then a custom template is the way to go. First, read the Django docs for the basics of creating custom template tags. Then make this tag:
from django import template from django.contrib.humanize.templatetags.humanize import intcomma register = template.Library() @register.filter def prepend_dollars(dollars): if dollars: dollars = round(float(dollars), 2) return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:]) else: return ''
Now in your template, put:
{{ my_float_var | prepend_dollars }}
Advertisements
Here’s a better alternative that is more generic and handles multiple currencies:
Thanks! I will give it a try. | https://snakeycode.wordpress.com/2014/10/26/django-template-filter-for-formating-currency/ | CC-MAIN-2017-43 | refinedweb | 204 | 57.06 |
Concatenate Arrays is very practical in real time environment. It is easy to copy one array into another, or clubbing both array elements. To make programming easy, the designers included arraycopy() static method in System class.
Concatenate Arrays: Following code concatenates two string arrays in three ways. Java comes with still many more ways using collection classes.
import java.util.*; public class Concatenation { public static void main(String args[]) { // two strings arrays String names[] = {"Rao", "Pillai", "Raman", "Hegde"}; String states[] = {"Andhra", "Kerala", "Tamilnadu", "Karnataka"}; // first way, Java style using System.arraycopy() method String bigArray[] = new String[names.length+states.length]; System.arraycopy(names, 0, bigArray, 0, names.length); System.arraycopy(states, 0, bigArray, names.length, states.length); for(String str : bigArray) { System.out.print(str + " "); } // second way, C/C++ style, round about process using String concat() method String s1="", s2=""; for(String str : names) { s1 += str + ", "; } for(String str : states) { s2 += str + ", "; } String s3 = s1.concat(s2); System.out.println("\n\n"+s3); // third way, using Collections framework classes, not preferred ArrayList al2 = new ArrayList(); Collections.addAll(al2, names); Collections.addAll(al2, states); System.out.println("\nArrayList elements with addAll(): " + al2); // if desired, convert array list to array back Object mix[] = al2.toArray(); System.out.print("\nmix elements: " ); for(Object str : mix) { System.out.print(str + " : "); } } }
Two string arrays names and states are initialized with four string elements each. Now it is required to concatenate them into one array. states is copied into names. That is, names contains states elements also after concatenation. Here, we use the static method arraycopy() defined in System class. states.length gives the size of the array or length of the array; that is, number of elements present in the array.
System.arraycopy(names, 0, bigArray, 0, names.length);
System.arraycopy(states, 0, bigArray, names.length, states.length);
It may be confusing to see the arraycopy() parameters. Once you know the method signature, everything will be clear.
System.arraycopy(source array, position in the source array, destination array, position in the destination array, number of elements to copy);
source array: The array into which other array elements are to be copied
position in the source array: To what position in the source array the other array (destination array) elements are to be copied. You can prescribe the index number.
destination array: The array whose elements are to be copied
position in the destination array: From what position the elements are to be copied
number of elements to copy: Write the number of elements from destination array to copy.
From the above explanation of arraycopy(), understand the above two statements. It takes sometime to you. If still unable, pass a comment available at the end of the notes; you will get the replay next day.
The other way is each element of the array is read into a string. Two strings s1 and s2 contains the elements of names and states. The two strings s1 and s2 are concatenated to a third string, s3.
ArrayList al2 = new ArrayList();
Collections.addAll(al2, names);
Collections.addAll(al2, states);
An ArrayList object is al2 created and all the elements of the two arrays are added to ArrayList with Collections.addAll() method. java.util.Collections class comes with a number of methods to manipulate DS elements. Similarly, java.util.Arrays comes with many methods to operate on array elements.
java.util.Collections and java.util.Arrays are really two gifts gifted by the Designers to the programmers with which the programmers can forget the long laborious code of C/C++ to manipulate elements.
You can have: All Array Operations at a Glance | https://way2java.com/java-general/java-concatenate-arrays/ | CC-MAIN-2022-33 | refinedweb | 602 | 50.43 |
Are you sure?
This
Python is my major programming language for daily simulation and research job. which are achieved by my new 'zhpy' (python in chinese) project (launch from Aug 07).I am a postgraduate at Wireless Telecommunication Graduate School. The recent chinese traditional version also featured with executable chinese python sources. but as you can see. It's clear and effective to lead you into a world of Python in the shortest time. China PR. Fred Lin .H. what . I think 'A Byte of Python' should be strongly recommendable for newbies as their first Python tutorial. This project is mainly aimed for education. please see the list of volunteers and languages below and decide if you want to start a new translation or help in existing translation projects.I'm working as a network firmware engineer at Delta Network. easy-to-use and productive. google. it's really easy-understanding. Just dedicate my translation to the potential millions of Python users in China. zhpy(pronounce (Z. I learned Python just half a year before. 'A Byte of Python' is my tutorial to learn Python. An exciting feature of this translation is that it also contains the executable chinese python sources side by side with the original python sources. It is available at http:/ / code. but efficiently covers almost all important things in Python. If you plan to start a new translation. thanks to many tireless volunteers! If you want to help these translations. 'A Byte of Python' elaborates the python essentials with affordable size.Python en:Translations 7 Python en:Translations There are many translations of the book available in different human languages. or zippy) build a layer upon python to translate or interact with python in chinese(Traditional or Simplified). Chinese Traditional Fred Lin (gasolin-at-gmail-dot-com) has volunteered to translate the book to Chinese Traditional. actually. I found 'A Byte of Python' hit the sweet point for both newbies and experienced programmers. com/ p/ zhpy/ wiki/ ByteOfZhpy (http:/ / code. please read the Translation Howto. com/ p/ zhpy/ wiki/ ByteOfZhpy). Beijing University of Technology. and I'm also a contributor of TurboGears web framework. I need some material to promote python language. channel estimation and multi-user detection of multicarrier CDMA system. It's not too long. and soon a lot of rewrite were made to fit the current wiki version and the quality of reading. with the help of Python Numeric. 'It's my favorite programming language now'. Just as what is ensured in Swaroop's book. My current research interest is on the synchronization. . Chinese Juan Shen (orion-underscore-val-at-163-dot-com) has volunteered to translate the book to Chinese. As a python evangelist (:-p).?. google. The translation are originally based on simplified chinese version.
gentoo.it (now under construction) for Nuclear Magnetic Resonance applications and Congress Organization and Managements. Besides this. I've searched for some kind of introduction to programming. Enrico as service engineer and system administrator for our CED and parallel / clustered systems. That's all! We are impressed by the smart language used on your Book and we think this is essential for approaching the Python to new users (we are thinking about hundred of students and researcher working on our labs). and 'Dive into Python'. I think 'A Byte of Python' falls nicely between these. . it/ Programmazione/ byteofpython).Chemistry Department. The main language I use as a professional is Java.gentoo. and at the same time verbose enough to teach a newbie. we had experience working with Linux platforms since ten years.Python en:Translations 8 Italian Enrico Morelli (mr-dot-mlucci-at-gmail-dot-com) and Massimo (morelli-at-cerm-dot-unifi-dot-it) have volunteered to translate the book to Italian. I've found the book 'How to Think Like a Computer Scientist: Learning with Python'. Especially text analysis and conversion is very easy with Python. berlios. I'm not very familiar with GUI toolkits. where the user interface is build using Java frameworks like Struts. written to the point. but I try to do as much as possible with Python behind the scenes.it web site for Gentoo/Linux distrubution and www. Currently I try to make more use of the functional programming features of Python and of generators.nmr. since most of my programming is about web applications.it/Programmazione/byteofpython (http:/ / www. Massimo Lucci and Enrico Morelli . de (http:/ / abop-german. After taking a short look into Ruby. Lucci The Italian translation is present at are working at the University of Florence (Italy) . which makes translating the text a generation the output in various formats a charm. German Lutz Horn (lutz-dot-horn-at-gmx-dot-de). The second is not suitable for beginners. The new translation is in progress and start with "Prefazione". since it is not too long. I (Massimo) as service engineer and system administrator for Nuclear Magnetic Resonance Spectrometers. Germany. Lutz Horn : I'm 32 years old and have a degree of Mathematics from University of Heidelberg. I like the simple DocBook structure. In Italy we are responsible and administrator for www. de).gentoo. Generally I like the dynamic nature of languages like Python and Ruby since it allows me to do things not possible in more static languages like Java. suitable to teach a complete non-programmer. We are programming on python since about seven years. Bernd Hengelein (bernd-dot-hengelein-at-gmail-dot-com) and Christoph Zwerschke (cito-at-online-dot-de) have volunteered to translate the book to German. The first is good for beginners but to long to translate. berlios. Their translation is located at http:/ / abop-german. Currently I'm working as a software engineer on a publicly funded project to build a web portal for all things related to computer science in Germany. I was very impressed with the use of blocks in this language.
because the code looks so beautiful. Lutz had the same idea and we can now divide the work. When I came across your book the spontaneous idea of a german translation crossed my mind. Last year I fell in love with Python. In my opinion he's absolutly right. which is a wonderful language. When I discovered this book. I noticed that there is very little good documentation in german available. We just started with the intro and preface but we will keep you informed about the progress we make. Most tutorials and books are written in very technical English. mercury.Python en:Translations Bernd Hengelein : Lutz and me are going to do the german translation together. Eirik Vågeskar: I have always wanted to program. com/ ) and currently translating the book to Norwegian (bokmål). Dominik Kozaczko . "A Byte of Python" used simple non-technical language to explain a programming language that is just as simple. wikipedia. I hope the translation will help people who have found themself in the same situation as me (especially young people). The translation is in progress. both for its possibilities and its beauty. and maybe help spread interest for the language among people with less technical knowledge. id/ moin. and these two things make learning Python fun. org/ wiki/ Sandvika_videregÃ¥ende_skole) in Norway. but because I speak a small language. a blogger (http:/ / forbedre. . At the time I decided to learn python. I am constantly looking for new things to learn. I read somewhere in the net about a guy who said that he likes python. bielsko. I am 34 years old and playing with computers since the 1980's. After reading half of the book. all my problems were solved. cgi/ ByteofPython Polish Dominik Kozaczko (dkozaczko-at-gmail-dot-com) has volunteered to translate the book to Polish. After studying computer science I started working as a software engineer. Luckily. and you can check the table of contents for more details. now some personal things about me. when the "Commodore C64" ruled the nurseries. I decided that the book was worth translating.I'm a Computer Science and Information Technology teacher. or. so most high school graduates will not even have the vocabulary to understand what the tutorial is about. Although C++ is the main language I (have to) use for my daily work. Ok. I am looking forward to a good cooperation! 9. the learning process was much harder. pl/ index. php/ UkÄ Å_Pythona). lo5. Currently I am working in the field of medical imaging for a major german company. Translation is in progress and it's main page is available here: Ukąś Pythona (http:/ / wiki. blogspot.
I am a developer and also a teacher of programming (normally for people without any previous experience). Just what I needed. and Swaroop's work was really helpful. has French Gregory (coulix-at-ozforces-dot-com-dot-au) has volunteered to translate the book to French. I my country there are two official languages. Some time ago I needed to learn how to program in Python. I started liking Python so I decided to help translate the latest version of Swaroop's book in Romanian.. . I'm just one volunteer so if you can help. swaroopch. The translation is being done here (http:/ / www. please join me. Brazilian Portuguese Rodrigo Amaral (http:/ / rodrigoamaral. why not try to translate it? And I did for a previous version of BoP. That's how popular this book is (congratulations to the author for writing such an easy to read book). The translation is in progress.. I thought some other people in my country could take benefit from it too. After this experience. net) (rodrigoamaral-at-gmail-dot-com) volunteered to translate the book to Brazilian Portuguese. But English language can be a barrier. concise.Python en:Translations 10 Catalan Moises Gomez (moisesgomezgiron-at-gmail-dot-com) has volunteered to translate the book to Catalan. Python. I selected the Catalan language assuming that others will translate it to the more widespread Spanish. Romanian Paul-Sebastian Manole (brokenthorn-at-gmail-dot-com) has volunteered to translate this book to Romanian. Moisès Gómez . Danish Lars Petersen (lars-at-ioflux-dot-net) has volunteered to translate the book to Danish. here in Romania. The web told me there was no better way to do so but read A Byte of Python. I'm more of a self-taught programmer and decided to learn a new language.I'm a second year Computer Science student at Spiru Haret University. So. and complete enough. Paul-Sebastian Manole . com/ notes/ Python_ro). Although I could be the one with the first initiative. Clear. Portuguese Fidel Viegas (fidel-dot-viegas-at-gmail-dot-com) has volunteered to translate the book to Portuguese. and starts with the chapter "Taula de continguts".
Russian and Ukranian Averkiev Andrey (averkiyev-at-ukr-dot-net) has volunteered to translate the book to Russian. Gustavo Echeverria: I work as a software engineer in Argentina. Dashes in other places in the email address remain as-is. Swedish Mikael Jacobsson (leochingkwake-at-gmail-dot-com) has volunteered to translate the book to Swedish. '-dot-' with '.Net technologies at work but strictly Python or Ruby in my personal projects. Now. you can read the spanish (argentinian) translation starting by the table of contents (tabla de contenidos). The translation is in progress. and perhaps Ukranian (time permitting). Mongolian Ariunsanaa Tunjin (tariunsanaa-at-yahoo-dot-com) has volunteered to translate the book to Mongolian. 11 Arabic Alaa Abadi (alaanassir-at-gmail-dot-com) has volunteered to translate the book to Arabic.Python en:Translations Spanish. I've begun to translate "A Byte of Python" with the help of Maximiliano Soler. I use mostly C# and . Note Replace '-at-' with '@' . I knew Python many years ago and I got stuck inmediately. . Not so long after knowing Python I discovered this book and it helped me to learn the language.. after receiving some requests. ISA .' and '-underscore-' with '_' in the email addresses mentioned on this page.
Python en:Translations 12 Previous Next Source: http:/ / www. Then. then you can also learn Python from this book. com/ mediawiki/ index. 20 anonymous edits Python en:Preface Python is probably one of the few programming languages which is both simple and powerful. I couldn't find any! I did find some O'Reilly books but they were either too expensive or were more like a reference manual than a guide. If you do have previous programming experience. I consider this book to be my contribution and tribute to the open source community. Then. is fun to program with.echeverria. This book aims to help you learn this wonderful language and show how to get things done quickly and painlessly . it has reached a stage where it has become a useful guide to learning the Python language. I settled for the documentation that came with Python. The aim is that if all you know about computers is how to save text files. However. I got excited about it and suddenly got the idea of writing some stuff on Python. It is useful for experienced programmers as well. A little warning though. I managed with it since I had previous programming experience.in effect 'The Perfect Anti-venom to your programming problems'. Raymond. So. This is good for both and beginners as well as experts. Rodrigoamaral. After a lot of rewrites. I started searching for a good book on Python. Gustavo. I installed the (then) latest Red Hat 9. It is mainly targeted at newbies. Leochingkwake. Who This Book Is For This book serves as a guide or tutorial to the Python programming language. the famous and respected hacker. swaroopch. php? oldid=2278 Contributors: Geopop65. I started writing a few pages but it quickly became 30 pages long. I had to choose between Python and Perl bindings for the Qt library. Vages. It did give a good idea about Python but was not complete. and more importantly. Thorns.0 Linux and I was playing around with KWord. it was too brief and small. Python is soon going to become your favorite programming language! History Lesson I first started with Python when I needed to write an installer for a software I had written called 'Diamond' so that I could make the installation easy. Waterox888. I decided that Python was the language for me. About six months after my first brush with Python. Moises. you will be interested in the differences between Python and your favorite programming language . then you can learn Python from this book. I also found out that the PyQt bindings were more mature compared to Perl-Qt. I became serious about making it more useful in a book form. Swaroop. . but it was unsuitable for newbies.I have highlighted many such differences. If you have previous programming experience. talked about how Python has become his favorite programming language. Morellik. So. I did some research on the web and I came across an article where Eric S.
com/ buybook). 13 Status Of The Book Changes since the last major revision in March 2005 is updating for the Python 3. swaroopch. distribute and transmit this book • You are free to Remix i.0 language itself is still not finalized/released. not comprehensible or are simply wrong. swaroopch. Since the Python 3. to adapt this book • Under the following conditions: • Attribution. transform. the updated book has been released and is constantly being updated. or build upon this work. Attribution must be shown by linking back to http:/ / www. It's a constant tussle to balance this book between a beginner's needs and the tendency towards 'completeness' of information. . Please write to the main author (http:/ / www. and also send me feedback. • This means: • You are free to Share i. License 1. • Share Alike. this book is constantly undergoing changes. I have received lots of constructive suggestions. Release Often". although I've taken a lot of effort to make it more palatable to others :) In the true spirit of open source.e. com/ contact/ ) or the respective translators with your comments and suggestions. to copy. • For any reuse or distribution.0 Unported (http:/ / creativecommons. The book needs the help of its readers such as yourselves to point out any parts of the book which are not good. • Any of the above conditions can be waived if you get permission from the copyright holder. 2. buy a printed hard copy (http:/ / www. com/ notes/ Python and clearly indicating that the original text can be fetched from this location.0 release (expected in August/September 2008). you must make clear to others the license terms of this book. 0/ ) license. download the latest versions of the book. It would be helpful if readers also gave feedback on how much depth this book should go into. Official Website The official website of the book is http:/ / www. in the spirit of the open source philosophy of "Release Early. org/ licenses/ by-nc-sa/ 3.e. criticisms and feedback from enthusiastic readers which has helped me improve this book a lot. swaroopch. If you alter. This book is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3. • Nothing in this license impairs or restricts the author's moral rights. swaroopch. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of this book). com/ notes/ Python where you can read the whole book online. you may distribute the resulting work only under the same or similar license to this one.Python en:Preface This book started out as my personal notes on Python and I still consider it in the same way. However.
if you find some material to be inconsistent or incorrect. php? oldid=987 Contributors: Gasolin. 2 anonymous edits . A. org/ licenses/ bsd-license. 14 Feedback I have put in a lot of effort to make this book as interesting and as accurate as possible. please consider purchasing a printed copy (http:/ / www. -. so that I can make suitable improvements.Python en:Preface 3. Something To Think About There are two ways of constructing a software design: one way is to make it so simple that there are obviously no deficiencies.C. php) unless otherwise noted. opensource.C. then please do inform me. Swaroop. However. or simply needs improvement. Volunteer contributions to this original book must be under this same license and the copyright must be assigned to the main author of this book. All the code/scripts provided in this book is licensed under the 3-clause BSD License (http:/ / www. Buy the Book If you wish to support the continued development of this book. -. R. Wendte Previous Next Source: http:/ / www. Hoare Success in life is a matter not so much of talent and opportunity as of concentration and perseverance. W. com/ mediawiki/ index. swaroopch. swaroopch. You can reach me via my user page. the other is to make it so complicated that there are no obvious deficiencies. 4. com/ buybook) or making a donation.
although very strict English! This pseudo-code nature of Python is one of its greatest strengths. All your Python programs can work on any of these platforms without requiring any changes at all if you are careful enough to avoid any . Features of Python Simple Python is a simple and minimalistic language. named the language after the BBC show "Monty Python's Flying Circus". In simple terms. High-level Language When you write programs in Python. Python is extremely easy to get started with. Free and Open Source Python is an example of a FLOSS (Free/Libré and Open Source Software). you can freely distribute copies of this software. Easy to Learn As you will see.it has been created and is constantly improved by a community who just want to see a better Python. make it an ideal language for scripting and rapid application development in many areas on most platforms. powerful programming language. make changes to it. Python has an extraordinarily simple syntax. you never need to bother about the low-level details such as managing the memory used by your program. etc. This is one of the reasons why Python is so good . as already mentioned.Python en:Introduction 15 Python en:Introduction Introduction Python is one of those rare languages which can claim to be both simple and powerful. I will discuss most of these features in more detail in the next section. He doesn't particularly like snakes that kill animals for food by winding their long bodies around them and crushing them. Note Guido van Rossum. read its source code. changed to make it work on) many platforms. Python's elegant syntax and dynamic typing. You will find that you will be pleasantly surprised on how easy it is to concentrate on the solution to the problem rather than the syntax and structure of the language you are programming in. and use pieces of it in new free programs. together with its interpreted nature. Reading a good Python program feels almost like reading English. Portable Due to its open-source nature. Python has been ported to (i. FLOSS is based on the concept of a community which shares knowledge. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. the creator of the Python language.e. It allows you to concentrate on the solution to the problem rather than the language itself. The official introduction to Python is: Python is an easy to learn.
Tk. AS/400. email. When you run the program. there are various other high-quality libraries such as wxPython (http:/ / www. It can help you do various things involving regular expressions. Palm OS. CGI. databases.e. twistedmatrix. does not need compilation to binary. Sharp Zaurus. you can code that part of your program in C or C++ and then use it from your Python program. GUI (graphical user interfaces). All this. Extensible If you need a critical piece of code to run very fast or want to have some piece of algorithm not to be open. and other system-dependent stuff. C or C++ into a language that is spoken by your computer (binary code i. especially when compared to big languages like C++ or Java. OS/2. Python Imaging Library (http:/ / www. etc. XML-RPC. Embeddable You can embed Python within your C/C++ programs to give 'scripting' capabilities for your program's users. Windows. documentation generation. com/ products/ pil/ index. org) . QNX. WAV files. Windows CE and even PocketPC ! Interpreted This requires a bit of explanation. This also makes your Python programs much more portable. com/ products/ twisted). z/OS. all this is always available wherever Python is installed. XML. on the other hand. 16 . making sure that the proper libraries are linked and loaded. Macintosh. VMS. Extensive Libraries The Python Standard Library is huge indeed. cryptography. HTML. OS/390. web browsers. 0s and 1s) using a compiler with various flags and options. unit testing. In procedure-oriented languages. htm) and many more. FreeBSD. Besides. since you can just copy your Python program onto another computer and it just works! Object Oriented Python supports procedure-oriented programming as well as object-oriented programming.e. Acorn RISC OS. etc. Internally. the linker/loader software copies the program from hard disk to memory and starts running it. the standard library. threading. Python has a very powerful but simplistic way of doing OOP. Twisted (http:/ / en:Introduction system-dependent features. In object-oriented languages. the program is built around objects which combine data and functionality. Psion. FTP. Python converts the source code into an intermediate form called bytecodes and then translates this into the native language of your computer and then runs it. AROS. Amiga. actually. You can use Python on Linux. Python. A program written in a compiled language like C or C++ is converted from the source language i. VxWorks. makes using Python much easier since you don't have to worry about compiling the program. BeOS. the program is built around procedures or functions which are nothing but reusable pieces of programs. Remember. Solaris. pythonware. This is called the 'Batteries Included' philosophy of Python. wxpython. You just run the program directly from the source code. PlayStation.
It has the right combination of performance and features that make writing programs in Python both fun and easy. is its huge CPAN (http:/ / cpan. clearer.the Comprehensive Perl Archive Network. This article was the real inspiration for my first brush with Python. purely from an ease-of-learning perspective. com/ article. then I would definitely recommend you to continue using it. As the name suggests. org/ pypi). 17 Why not Perl? If you didn't know already. linuxjournal. you would have answered this question yourself! In other words. that it feels like it is one big (but one hell of a) hack. However. The only and very significant advantage that I feel Perl has. Raymond is the author of "The Cathedral and the Bazaar" and is also the person who coined the term Open Source. Perl programs are easy when they are small and it excels at small hacks and scripts to 'get work done'. If you have ever tried writing a large program in Perl. this is a humongous collection of Perl modules and it is simply mind-boggling because of its sheer size and depth . they quickly become unwieldy once you start writing bigger programs and I am speaking this out of my experience writing large Perl programs at Yahoo! When compared to Perl. Python programs are definitely simpler. He says that Python is perhaps the only language that focuses on making things easier for the . Sadly. Unfortunately. easier to write and hence more understandable and maintainable. they all praise the beauty of the language. but for people who understand Ruby. I always start thinking in terms of Python because it has become so natural for me. Ruby is another popular open source interpreted programming language.Python en:Introduction Python is indeed an exciting and powerful language. php?sid=3882). the upcoming Perl 6 does not seem to be making any improvements regarding this. For other people who have not used it and are trying to judge whether to learn Python or to learn Ruby. Perl is another extremely popular open source interpreted programming language. He says that Python has become his favorite programming language (http:/ / www. He says that no language has made him more productive than Python. org) library . Perl has undergone so many hacks and changes. I personally found it hard to grok the Ruby language. I am not as lucky.you can do virtually anything you can do with a computer using these modules. However this seems to be changing with the growing Python Package Index (http:/ / pypi. Why not Ruby? If you didn't know already. If you already like and use Ruby. One of the reasons that Perl has more libraries than Python is that it has been around for a much longer time than Python. perl. • Bruce Eckel is the author of the famous Thinking in Java and Thinking in C++ books. then I would recommend Python. python. I do admire Perl and I do use it on a daily basis for various things but whenever I write a program. What Programmers Say You may find it interesting to read what great hackers like ESR have to say about Python: • Eric S.
com/ jobs/ index. • Peter Norvig is a well-known Lisp author and Director of Search Quality at Google (thanks to Guido van Rossum for pointing that out). It is sometimes referred to as Python 3000 or Py3K. org/ dev/ whatsnew/ 2. com/ intv/ aboutme. html) (features significantly different from previous Python 2. python.x source (http:/ / docs. python. python. 0/ library/ 2to3. 18 About Python 3.6 (http:/ / docs. swaroopch. python. You can actually verify this statement by looking at the Google Jobs (http:/ / www. txt) Previous Next Source: http:/ / code.0) • What's New in Python 3.x versions and most likely will be included in Python 3. 6. 2 anonymous edits . 0. The main reason for a major new version of Python is to remove all the small problems and nitpicks that have accumulated over the years and to make the language even more clean. com/ mediawiki/ index. html).0 Python 3.0 (http:/ / docs. artima. Read the complete interview (http:/ / and 3. php? oldid=1789 Contributors: JeremyBicha.0 Plans (http:/ / www. 0/ NEWS. If you already have a lot of Python 2. org/ download/ releases/ 3. org/ dev/ peps/ pep-0361/ ) • Python 3000 (the official authoritative list of proposed changes) (http:/ / www. He says that Python has always been an integral part of Google. python. com/ weblogs/ viewpost. html) • Python 2.x to 3. python. org/ dev/ peps/ pep-3000/ ) • Miscellaneous Python 3.0 Release Schedule (http:/ / www. org/ dev/ peps/ pep-3100/ ) • Python News (detailed list of changes) (http:/ / www. More details are at: • Guido van Rossum's introduction (http:/ / www. then there is a utility to assist you to convert 2. html) page which lists Python knowledge as a requirement for software engineers. python. jsp?thread=208549) • What's New in Python 2. google. Swaroop.Python en:Introduction programmer. org/ dev/ 3. artima. 0/ whatsnew/ 3. html) for more details.0 is the new version of the language. org/ dev/ 3.
0/ ) and install it. For Linux and BSD users If you are using a Linux distribution such as Ubuntu. you have two ways of installing Python on your system. such as apt-get in Ubuntu/Debian and other Debian-based Linux. you can download the binaries from somewhere else and then copy to your PC and install it. • [This option will be available after the final release of Python 3. . However.0. To test if you have Python already installed on your Linux box. pkg_add in FreeBSD. then try python3 -V. hence I will indicate the prompt by just the $ symbol.x already installed.Python en:Installation 19 Python en:Installation If you have Python 2. if you get a message like this one: $ python -V bash: Python: command not found Then you don't have Python installed. Alternatively. This is highly unlikely but possible. Note If you have Python 2. etc. you do not have to remove it to install Python 3. python. Fedora. If you see some version information like the one shown above. or a BSD system such as FreeBSD. open a shell program (like konsole or gnome-terminal) and enter the command python -V as shown below. org/ download/ releases/ 3. OpenSUSE or {put your choice here}. It will be different for you depending on the settings of your OS. Note that you will need an internet connection to use this method. $ python -V Python 3. then you have Python installed already.0b1 Note $ is the prompt of the shell. You can have both installed at the same time. then it is most likely you already have Python installed on your system. In this case. • You can compile Python from the source code (http:/ / www. yum in Fedora Linux. The compilation instructions are provided at the website.0] Install the binary packages using the package management software that comes with your OS.x installed already.
NT file. Click on the variable named PATH in the 'System Variables' section. 0b1.BAT : 'PATH=%PATH%. Otherwise. Caution When you are given the option of unchecking any "optional" components. msi) as of this writing. For Windows NT. An interesting fact is that majority of Python downloads are by Windows users. For Windows 2000. Open the Terminal. use the AUTOEXEC. For a Windows system. which was 3.Python en:Installation 20 For Windows Users Visit http:/ / www. DOS Prompt If you want to be able to use Python from the Windows command line i. use the appropriate directory name. don't uncheck any! Some of these components can be useful for you. especially IDLE. installing Python is as easy as downloading the installer and double-clicking on it. For older versions of Windows. 2003 .app and run python -V and follow the advice in the above Linux section. Of course.e. click on Control Panel -> System -> Advanced -> Environment Variables.C:\Python30 to the end of what is already there. XP. . Next. add the following line to the file C:\AUTOEXEC. this doesn't give the complete picture since almost all Linux users will have Python installed already on their systems by default.C:\Python30' (without the quotes) and restart the system. org/ ftp/ python/ 3. From now on. you most probably already have Python installed on your system. Of course.0 beta 1 (http:/ / www. the DOS prompt. then you need to set the PATH variable appropriately. This is just 12.8 MB which is very compact compared to most other languages or software. we will write our first Python program. For Mac OS X Users Mac OS X Users will find Python already installed on their system. then select Edit and add . Summary For a Linux system. you can install it using the package management software that comes with your distribution. we will assume that you have Python installed on your system. python. org/ download/ releases/ 3. The installation is just like any other Windows-based software. 0/ python-3. 0/ and download the latest version from this website. python.
Choosing An Editor Before we move on to writing Python programs in source files.0b2 (r30b2:65106. we need an editor to write the source files. >>> print('Hello World') Hello World >>> Notice that Python gives you the output of the line immediately! What you just entered is a single Python statement. we are supplying the text Hello World and this is promptly printed to the screen. How to Quit the Interpreter Prompt To exit the prompt. you can run the interpreter in the command line if you have set the PATH variable appropriately. click on Start → Programs → Python 3. This will teach you how to write. You have to choose an editor as you would choose a car you would buy. Jul 18 2008. "credits" or "license" for more information. Here.Python en:Installation 21 Previous Next Source: http:/ / www. swaroopch. 1 anonymous edits Python en:First Steps Introduction We will now see how to run a traditional 'Hello World' program in Python. If you are using IDLE. The choice of an editor is crucial indeed.1500 32 bit (Intel)] on win32 Type "help".using the interactive interpreter prompt or using a source file. 18:44:17) [MSC v. press ctrl-z followed by enter key. In case of the Windows command prompt. There are two ways of using Python to run your program . We use print to (unsurprisingly) print any value that you supply to it. $ python Python 3. A good editor will help you write Python programs easily. . "copyright". For Windows users. You should see the words Hello World as output. save and run Python programs. com/ mediawiki/ index. making your journey more comfortable and helps you reach your destination (achieve your goal) in a much faster and safer way. press ctrl-d if you are using IDLE or are using a Linux/BSD shell. We will now see how to use both of these methods Using The Interpreter Prompt Start the interpreter on the command line by entering python at the shell prompt.0 → IDLE (Python GUI). php? oldid=1746 Contributors: Swaroop. Now enter print('Hello World') followed by the Enter key.
We will explore how to use IDLE in the next section. python. html) and BSDs in their respective repositories.Python en:First Steps One of the very basic requirements is syntax highlighting where all the different parts of your Python program are colorized so that you can see your program and visualize its running. I personally use Vim for most of my programs. please choose a proper editor . 22 . For Vim users There is a good introduction on how to make Vim a powerful Python IDE by John M Anderson (http:/ / blog. In this book.it is a bad choice because it does not do syntax highlighting and also importantly it does not support indentation of the text which is very important in our case as we will see later. I repeat once again. IDLE does syntax highlighting and a lot more such as allowing you to run your programs within IDLE among other things. If you are using Linux/FreeBSD. these are two of the most powerful editors and you will be benefitted by using them to write your Python programs. net/ 2008/ 05/ 11/ python-with-a-modular-ide-vim/ ). then you have a lot of choices for an editor. If you are an experienced programmer. see the comprehensive list of Python editors (http:/ / www. Once you start writing large Python programs. blogspot. enigmacurry. If you still want to explore other choices of an editor. You can also choose an IDE (Integrated Development Environment) for Python. sontek. For Emacs users There is a good introduction on how to make Emacs a powerful Python IDE by Ryan McGuire (http:/ / www. html). org/ cgi-bin/ moinmoin/ PythonEditors) and make your choice. then you must be already using Vim or Emacs. our IDE and editor of choice. Needless to say. It has a graphical user interface and has buttons to compile and run your python program without a fuss. If you are just beginning to program. please refer the IDLE documentation (http:/ / www. then I highly recommend that you do learn to use either of them as it will be very useful for you in the long run. IDLE is installed by default with the Windows and Mac OS X Python installers. com/ 2008/ 03/ install-idle-in-linux. See the comprehensive list of IDEs that support Python (http:/ / www. we will use IDLE. org/ idle/ doc/ idlemain. then you can use Kate which is one of my favorites. For further details. python. IDEs can be very useful indeed. In case you are willing to take the time to learn Vim or Emacs. then I suggest that you use IDLE. com/ 2008/ 05/ 09/ emacs-as-a-powerful-python-ide/ ). org/ cgi-bin/ moinmoin/ IntegratedDevelopmentEnvironments) for more details.it can make writing Python programs more fun and easy. If you are using Windows. A special note: Do not use Notepad . python. It is also available for installation for Linux (http:/ / love-python. you might want to use geany. Good editors such as IDLE (and also VIM) will automatically help you do this. If you are a beginner programmer.
congratulations! . If you are using IDLE.anything to the right of the # symbol is a comment and is mainly useful as notes for the reader of the program. that person can be yourself after six months! The comments are followed by a Python statement.you have successfully run your first Python program. Important Use comments sensibly in your program to explain some important details of your program . use the menu Run → Run Module or the keyboard shortcut F5. We will learn about functions in a → later chapter.py If you are using IDLE.py print('Hello World') Run this program by opening a shell (Linux terminal or DOS prompt) and entering the command python helloworld.py.note the lowercase p in the former and the uppercase P in the latter. How It Works Let us consider the first two lines of the program. what .this is useful for readers of your program so that they can easily understand what the program is doing. Here we call the print function this just prints the text 'Hello World'. There is a tradition that whenever you learn a new programming language.py .we will see why this is important later.all it does is just say 'Hello World' when you run it.Python en:First Steps 23 Using A Source File Now let's get back to programming.e. Note that you can always run the program on any platform by specifying the interpreter directly on the command line such as the command python helloworld. ensure there are no spaces or tabs before the first character in each line . It is called the shebang line . Note that Python is case-sensitive i. In case you got an error. click on File → New Window and enter the following program. Then click on File → Save. print is not the same as Print . Python does not use comments except for the special case of the first line here. Start your choice of editor. Also. it is the 'traditional incantation to the programming gods to help you learn the language better' :) .whenever the first two characters of the source file are #! followed by the location of a program. Remember. #!/usr/bin/python #Filename: helloworld. The output is as shown below. enter the following program and save it as helloworld. As Simon Cozens [1] puts it. This is explained in detail in the next section. please type the above program exactly as shown and above and run the program again. this tells your Linux/Unix system that this program should be run with this interpreter when you execute the program. the first program that you write and run is the 'Hello World' program . These are called comments .py Hello World If you got the output as shown above. $ python helloworld.
we have been able to run our program as long as we know the exact path. What if we wanted to be able to run the program from anywhere? You can do this by storing the program in one of the directories listed in the PATH environment variable. It is like creating your own commands just like cd or any . We see that /home/swaroop/bin is one of the directories in the PATH variable where swaroop is the username I am using in my system. This method is very useful if you want to write useful scripts that you want to run the program anytime. we will explore these terminologies in detail later.py Hello World The chmod command is used here to change the mode of the file by giving execute permission to all users of the system./helloworld and it will still work since the system knows that it has to run the program using the interpreter whose location is specified in the first line in the source file. $ chmod a+x helloworld.py /home/swaroop/bin/helloworld $ helloworld Hello World We can display the PATH variable using the echo command and prefixing the variable name by $ to indicate to the shell that we need the value of this variable. you can rename the file to just helloworld and run it as . To make things more fun. We can make this program available everywhere by simply copying this source file to one of the directories listed in PATH. we execute the program directly by specifying the location of the source file.Python en:First Steps you should understand now is that whatever you supply in the parentheses will be printed back to the screen. we supply 'Hello World' which is referred to as a string don't worry./ to indicate that the program is located in the current directory. the system looks for that program in each of the directories listed in the PATH environment variable and then runs that program. $ echo $PATH /usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/swaroop/bin $ cp helloworld. anywhere. What if you don't know where Python is located? Then.this can be done by running PATH=$PATH:/home/swaroop/mydir where '/home/swaroop/mydir' is the directory I want to add to the PATH variable. There will usually be a similar directory for your username on your system. you can use the special env program on Linux/Unix systems. we have to give the program executable permission using the chmod command then run the source program. In this case. 24 Executable Python Programs This applies only to Linux/Unix users but Windows users might be curious as well about the first line of the program./helloworld. you can add a directory of your choice to the PATH variable . Then. First.py $ . Alternatively. Whenever you run any program. Just change the first line of the program to the following: #!/usr/bin/env python The env program will in turn look for the Python interpreter which will run the program. We use the . So far.
Caution W. 9 anonymous edits . Similarly. 25 Getting Help If you need quick information about any function or statement in Python. save and run Python programs at ease.this displays the help for the print function which is used to print things to the screen. php? oldid=2332 Contributors: Swaroop. com/ mediawiki/ index.t.Python en:First Steps other commands that you use in the Linux terminal or DOS prompt. swaroopch.r. References: [1] The author of the amazing 'Beginning Perl' book → Previous → Next Source: http:/ / www. Note Press q to exit the help. you can obtain information about almost anything in Python. Summary You should now be able to write. let's learn some more Python concepts. then you can use the built-in help functionality. For example. a program or a script or software all mean the same thing. Now that you are a Python user. Python. run help(print) . then you need to put those inside quotes such as help('return') so that Python doesn't get confused on what we're trying to do. This is very useful especially when using the interpreter prompt. Use help() to learn more about using help itself! In case you need to get help for operators like return.
It is called a literal because it is literal .6j) Note for Experienced Programmers There is no separate 'long int' type. Strings are basically just a bunch of words. The words can be in English or any other language that is supported in the Unicode standard. org/ faq/ basic_q. Note for Experienced Programmers There are no "ASCII-only" strings because Unicode is a superset of ASCII. I can almost guarantee that you will be using strings in almost every Python program that you write.3 * 10-4. 1. unicode. all strings are in Unicode.25e-3 or a string like 'This is a string' or "It's a string!". In this case. all these are referred to as literal constants. • Examples of floating point numbers (or floats for short) are 3. 52.3 . .4. please see the related discussion at StackOverflow (http:/ / stackoverflow.23 and 52. For more details. Literal Constants An example of a literal constant is a number like 5.Python en:Basics 26 Python en:Basics Just printing 'Hello World' is not enough. then use str. manipulate it and get something out of it. html#16). The default integer type can be any large value. If a strictly ASCII-encoded byte-stream is needed.encode("ascii"). • An examples of an integer is 2 which is just a whole number. is it? You want to do more than that . 9. Numbers Numbers in Python are of three types .integers.it is a constant because its value cannot be changed. The number 2 always represents itself and nothing else .you use its value literally. floating point and complex numbers. Hence. We can achieve this in Python using constants and variables. Strings A string is a sequence of characters. • Examples of complex numbers are (-5+4j) and (2.3E-4.you want to take some input.23.3E-4 means 52. so pay attention to the following part on how to use strings in Python. which means almost any language in the world (http:/ / www. The E notation indicates powers of 10. com/ questions/ 175240/ how-do-i-convert-a-files-format-from-unicode-to-ascii-using-python#175270). By default.
An example is "What's your name?" Triple Quotes You can specify multi-line strings using triple quotes . Also. Now. . "Bond." I asked.\t. Another way of specifying this specific string would be "What's your name?" i.". You specify the single quote as \' . An example is This is the first line\nThis is the second line.e. Similarly. you can specify the string as 'What\'s your name?'. the string is What's your name?. the second line. Double Quotes Strings in double quotes work exactly the same way as strings in single quotes. For example: "This is the first sentence.(""" or ''')." Escape Sequences Suppose. An example is: '''This This is "What's He said ''' is a multi-line string. You can use single quotes and double quotes freely within the triple quotes.\n to indicate the start of a new line. spaces and tabs are preserved as-is. This can be done with the help of what is called an escape sequence.\ This is the second sentence. you have to use an escape sequence for using a double quote itself in a double quoted string. This is the first line. So. There are many more escape sequences but I have mentioned only the most useful ones here. One thing to note is that in a string.notice the backslash. you will have to specify that this single quote does not indicate the end of the string.e. You cannot specify 'What's your name?' because Python will be confused as to where the string starts and ends. James Bond. What if you wanted to specify a two-line string? One way is to use a triple-quoted string as shown previously or you can use an escape sequence for the newline character . Another useful escape sequence to know is the tab . you have to indicate the backslash itself using the escape sequence \\. This is the second sentence. you want to have a string which contains a single quote ('). how will you specify this string? For example. a single backslash at the end of the line indicates that the string is continued in the next line. using double quotes." is equivalent to "This is the first sentence. All white space i. your name?. but no newline is added.Python en:Basics 27 Single Quotes You can specify strings using single quotes such as 'Quote me on this'.
you cannot change it. The format Method Sometimes we may want to construct strings from other information. the format method can be called to substitute those specifications with corresponding arguments to the format method. 'What\'s ' 'your name?' is automatically converted in to "What's your name?".they do not differ in any way. This is where the format() method is useful. age)) print('Why is {0} playing with that python?'. Although this might seem like a bad thing. Otherwise.Python en:Basics 28 Raw Strings If you need to specify some strings where no special processing such as escape sequences are handled. For example. An example is r"Newlines are indicated by \n". Note for C/C++ Programmers There is no separate char data type in Python. they are automatically concatenated by Python.py age = 25 name = 'Swaroop' print('{0} is {1} years old'. Note for Perl/PHP Programmers Remember that single-quoted strings and double-quoted strings are the same . We will see why this is not a limitation in the various programs that we see later on. Strings Are Immutable This means that once you have created a string. For example.format(name. backreferences can be referred to as '\\1' or r'\1'.py Swaroop is 25 years old Why is Swaroop playing with that python? How It Works: A string can use certain specifications and subsequently. a lot of backwhacking may be required.format(name)) Output: $ python str_format. . There is no real need for it and I am sure you won't miss it. Note for Regular Expression Users Always use raw strings when dealing with regular expressions. it really isn't. then what you need is to specify a raw string by prefixing r or R to the string. String Literal Concatenation If you place two string literals side by side. #!/usr/bin/python # Filename: str_format.
29 Variables Using just literal constants can soon become boring . Identifier Naming Variables are examples of identifiers. underscores ('_') or digits (0-9). and "this_is_in_quotes".format('hello') # fill with underscores (_) with the text centered (^) to 11 width '___hello___' >>> '{name} wrote {book}'. . • Examples of valid identifier names are i.. name_23. this is spaced out.e.>> '{0:_^11}'. myname and myName are not the same. the conversion to string would be done automatically by the format method instead of the explicit conversion here.format(name='Swaroop'. What Python does in the format method is that it substitutes each argument value into the place of the specification. Note the lowercase n in the former and the uppercase N in the latter. This is where variables come into the picture. Variables are exactly what the name implies . python. the second specification is {1} corresponding to age which is the second argument to the format method. There can be more detailed specifications such as: >>> '{0:. • Identifier names are case-sensitive. Second. i.. 3101 (http:/ / www. org/ dev/ peps/ pep-3101/ ).
Python en:Basics 30 Data Types Variables can hold values of different types called data types.py 5 6 This is a multi-line string. This is the second line. strings and functions.py or use IDLE to run the programs. How It Works: Here's how this program works. Objects Remember. Open your favorite editor. 1.''' print(s) Output: $ python var. Run the interpreter with the command python program. Example: Using Variables And Literal Constants # Filename : var. We will now see how to use variables along with literal constants. This is the second line. the standard procedure to save and run a Python program is as follows: 1. The basic types are numbers and strings. we assign the literal constant value 5 to the variable i using the assignment operator (=). This line is called a statement because it states that . 1. First. This is meant in the generic sense.py. 1. I follow the convention of having all Python programs saved with the extension . In later chapters. Save it as a file with the filename mentioned in the comment. which we have already discussed. Instead of saying 'the something'.py i = 5 print(i) i = i + 1 print(i) s = '''This is a multi-line string. Save the following example and run the program. How to write Python programs Henceforth. we say 'the object'. Note for Object Oriented Programming users Python is strongly object-oriented in the sense that everything is an object including numbers. Python refers to anything used in a program as an object. we will see how to create our own types using classes. You can also use the executable method as explained earlier. Enter the program code given in the example.
print(i). An example of a logical line is a statement like print('Hello World') . a if it a An example of writing a logical line spanning many physical lines follows. just prints the value of the variable to the screen. Next. Python implicitly assumes that each physical line corresponds to a logical line. Implicitly. \ This continues the string. then you have to explicitly specify this using a semicolon (. This is referred to as explicit line joining. and the same can be written as i = 5. In fact. print(i). A logical line is what Python sees as a single statement. No declaration or data type definition is needed/used.) which indicates the end of a logical line/statement. For example. If you want to specify more than one logical line on a single physical line. unsurprisingly. We then print it and expectedly.' print(s) .if this was on a line by itself (as you see it in an editor). Python encourages the use of a single statement per line which makes code more readable. then this also corresponds to a physical line. i = 5 print(i) is effectively same as i = 5. 31 Logical And Physical Lines A physical line is what you see when you write the program. I strongly recommend that you stick to writing a single logical line in single physical line only. we print the value of i using the print statement which. The idea is to avoid the semicolon as much as possible since leads to more readable code.Python en:Basics something should be done and in this case. we get the value 6. Note for static language programmers Variables are used by just assigning them a value. print(i) However. Then we add 1 to the value stored in i and store it back. or even i = 5. I have never used or even seen a semicolon in Python program. we assign the literal string to the variable s and then print it. Use more than one physical line for a single logical line only the logical line is really long. Similarly. we connect the variable name i to the value 5. s = 'This is a string.
I strongly recommend that you use a single tab or four . square brackets or curly braces. the program was not properly written. This is is called implicit line joining. Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line. the value is '. of course). line 4 print('Value is '. Actually. whitespace at the beginning of the line is important. print\ (i) is the same as print(i) Sometimes. Cases where you can use new blocks will be detailed in later chapters such as the control flow chapter. i) When you run this.e. What this means to you is that you cannot arbitrarily start new blocks of statements (except for the default main block which you have been using all along. which in turn is used to determine the grouping of statements. Each such set of statements is called a block. One thing you should remember is that wrong indentation can give rise to errors. 32 Indentation Whitespace is important in Python. you get the following error: File "whitespace. You can see this in action when we write programs using lists in later chapters. there is an implicit assumption where you don't need to use a backslash. This is called indentation. This means that statements which go together must have the same indentation. This is the case where the logical line uses parentheses. For example: i = 5 print('Value is '. This continues the string. How to indent Do not use a mixture of tabs and spaces for the indentation as it does not work across different platforms properly. i) # Error! Notice a single space at the start of the line ^ IndentationError: unexpected indent Notice that there is a single space at the beginning of the second line. Similarly. We will see examples of how blocks are important in later chapters. i) # Error! Notice a single space at the start of the line print('I repeat.py". The error indicated by Python tells us that the syntax of the program is invalid i.Python en:Basics This gives the output: This is a string.
. 2 and 3 are the operands. Note to static language programmers Python will always use indentation for blocks and will never use braces. 33 Summary Now that we have gone through many nitty-gritty details. In this case. Operators are functionality that do something and can be represented by symbols such as + or by special keywords. choose one and use it consistently i. com/ mediawiki/ index. Operators require some data to operate on and such data is called operands. Choose either of these two indentation styles. -5. we can move on to more interesting stuff such as control flow statements.2 gives a negative number. 10 anonymous edits Python en:Operators and Expressions Introduction Most statements (logical lines) that you write will contain expressions. An expression can be broken down into operators and operands. Run from __future__ import braces to learn more. 'a' + 'b' gives 'ab'.Python en:Basics spaces for each indentation level. use the interactive Python interpreter prompt: >>> 2 + 3 5 >>> 3 * 5 15 >>> Operator + Name Plus Minus Explanation Adds the two objects Either gives a negative number or gives the subtraction of one number from the other Examples 3 + 5 gives 8. php? oldid=2376 Contributors: Swaroop. More importantly. 50 . Operators We will briefly take a look at the operators and their usage: Note that you can evaluate the expressions given in the examples using the interpreter interactively.e. swaroopch. Previous Next Source: http:/ / www. A simple example of an expression is 2 + 3. Vages. use that indentation style only.24 gives 26. For example. Be sure to become comfortable with what you have read in this chapter. to test the expression 2 + 3.
x and y returns False since x is False. x != y returns True. Comparisons can be chained arbitrarily: 3 < 5 < 7 gives True. In this case. Returns whether x is greater than y 11 >> 1 gives 5. x and y returns False if x is False. Python will not evaluate y since it knows that the left hand side of the 'and' expression is False which implies that the whole expression will be False irrespective of the other values. y = 'str'. != Not Equal To Compares if the objects are not equal x = 2. Bitwise AND of the numbers Bitwise OR of the numbers Bitwise XOR of the numbers The bit-wise inversion of x is -(x+1) Returns whether x is less than y. it always returns False. 5 & 3 gives 1. All comparison operators return True or False. not Boolean NOT If x is True. they are first converted to a common type. y = 2. x = 'str'. x == y returns True. 4 // 3 gives 1. Floor Division Returns the floor of the quotient Modulo Returns the remainder of the division % 8 % 3 gives 2. This is called short-circuit evaluation. x == y returns False. else it returns evaluation of y x = False. not x returns False. 5 | 3 gives 7 5 ^ 3 gives 6 ~5 gives -6. x >= 3 returns True. 'la' * 3 gives 'lalala'. it returns False. x = 3. x is False. y = 3. y = 'stR'.5. Note the capitalization of these names. Otherwise. If x = True. x = 'str'. y = True. 11 is represented in bits by 1011 which when right shifted by 1 bit gives 101 which is the decimal 5. represented in memory by bits or binary digits i.3333333333333333. << Left Shift Shifts the bits of the number 2 << 2 gives 8. it returns True. == x = 2.e.25 gives 1. 0 and 1) Shifts the bits of the number to the right by the number of bits specified. (Each number is decimal 8. y = 6. -25. If both operands are numbers. x <= y returns True. Left to the left by the number of shifting by 2 bits gives 1000 which represents the bits specified. * Multiply Gives the multiplication of the two numbers or returns the string repeated that many times. Returns x to the power of y Divide x by y ** / // Power Divide 3 ** 4 gives 81 (i. >> Right Shift & | ^ ~ Bitwise AND Bit-wise OR Bit-wise XOR Bit-wise invert Less Than < 5 < 3 gives False and 3 < 5 gives True.e.5 % 2. 2 is represented by 10 in bits. y = 3. x == y returns True. > Greater Than 5 > 3 returns True. <= Less Than or Equal To Greater Than or Equal To Equal To Returns whether x is less than or equal to y Returns whether x is greater than or equal to y Compares if the objects are equal >= x = 4. 3 * 3 * 3 * 3) 4 / 3 gives 1. and Boolean AND .Python en:Operators and Expressions 34 2 * 3 gives 6.
is the addition done first or the multiplication? Our high school maths tells us that the multiplication should be done first. html#evaluation-order). hence there is a shortcut for such expressions: You can write: a = 2. is not <. //. % +x. it returns True. !=. >> +. This means that the multiplication operator has higher precedence than the addition operator. x or y returns True. This makes the program more readable. <=. *. Floor Division and Remainder Positive. -x Description Lambda Expression Boolean OR Boolean AND Boolean NOT Membership tests Identity tests Comparisons Bitwise OR Bitwise XOR Bitwise AND Shifts Addition and subtraction Multiplication. The following table gives the precedence table for Python. Python will first evaluate the operators and expressions lower in the table before the ones listed higher in the table. The following table. python. Evaluation Order If you had an expression such as 2 + 3 * 4. Operator lambda or and not x in. It is far better to use parentheses to group operators and operands appropriately in order to explicitly specify the precedence. taken from the Python reference manual (http:/ / docs. Division. >=. == | ^ & <<. 0/ reference/ expressions. /. Negative . a *= 3 Notice that var = var operation expression becomes var operation= expression. Short-circuit evaluation applies here as well. is provided for the sake of completeness. not in is. else it returns evaluation of y Shortcut for math operation and assignment It is common to run a math operation on a variable and then assign the result of the operation back to the variable. This means that in a given expression. See Changing the Order of Evaluation below for details. a = a * 3 as: a = 2. y = False. from the lowest precedence (least binding) to the highest precedence (most binding). org/ dev/ 3. >. or Boolean OR If x is True.Python en:Operators and Expressions 35 x = True.
we can use parentheses. if you want addition to be evaluated before multiplication in an expression. a = b = c is treated as a = (b = c).) [expressions. Expressions Example: #!/usr/bin/python # Filename: expression.attribute x[index] x[index1:index2] f(arguments ..Python en:Operators and Expressions 36 Bitwise NOT Exponentiation Attribute reference Subscription Slicing Function call Binding or tuple display List display Dictionary display ~x ** x.. There is an additional advantage to using parentheses . . For example. . operators with same precedence are evaluated in a left to right manner. .] {key:datum. Operators with the same precedence are listed in the same row in the above table.it helps us to change the order of evaluation.. then you can write something like (2 + 3) * 4. the parentheses should be used reasonably (do not overdo it) and should not be redundant (as in 2 + (3 + 4)).py length = 5 breadth = 2 area = length * breadth print('Area is'.. 2 * (length + breadth)) Output: . 2 + (3 * 4) is definitely easier to understand than 2 + 3 * 4 which requires knowledge of the operator precedences... 2 + 3 + 4 is evaluated as (2 + 3) + 4. + and . For example. Changing the Order Of Evaluation To make the expressions more readable.. As with everything else. For example.} The operators which we have not already come across will be explained in later chapters. area) print('Perimeter is'. Some operators like assignment operators have right to left associativity i.) (expressions. For example..have the same precedence.e.e. Associativity Operators are usually associated from left to right i.
com/ mediawiki/ index. We store the result of the expression length * breadth in the variable area and then print it using the print function.py Area is 10 Perimeter is 14 How It Works: The length and breadth of the rectangle are stored in variables by the same name. 4 anonymous edits . Next. Previous Next Source: http:/ / en:Operators and Expressions $ python expression. In the second case. Even though we have not specified a space between 'Area is' and the variable area.these are the basic building blocks of any program. we will see how to make use of these in our programs using statements. php? oldid=1579 Contributors: Swaroop. swaroopch. operands and expressions . This is an example of how Python makes life easy for the programmer. Also. We use these to calculate the area and perimeter of the rectangle with the help of expressions.). notice how Python 'pretty-prints' the output. 37 Summary We have seen how to use operators.
py Enter an integer : 50 No. for and while.. we run a block of statements (called the if-block).') # New block starts here print('(but you do not win any prizes!)') # New block ends here elif guess < number: print('No. The else clause is optional. this is achieved using control flow statements.Python en:Control Flow 38 Python en:Control Flow Introduction In the programs we have seen till now. else we process another block of statements (called the else-block).if. The if statement The if statement is used to check a condition and if the condition is true. it is a little lower than that Done $ python if. there has always been a series of statements and Python faithfully executes them in the same order. else: print('No. There are three control flow statements in Python . you want the program to take some decisions and do different things depending on different situations such as printing 'Good Morning' or 'Good Evening' depending on the time of the day? As you might have guessed. it is a little higher than that') # Another block # You can do whatever you want in a block . Example: #!/usr/bin/python # Filename: if.py number = 23 guess = int(input('Enter an integer : ')) if guess == number: print('Congratulations.py Enter an integer : 22 . after the if statement is executed Output: $ python if.. What if you wanted to change the flow of how it works? For example. it is a little lower than that') # you must have guess > number to reach here print('Done') # This last statement is always executed. you guessed it.
Next. it is the main block where execution of the program starts and the next statement is the print('Done') statement. say 23. it is a little higher than that Done $ python if. After this. you guessed it. Actually. as a string. We'll read more about them in the next chapter. Are you? Notice how the if statement contains a colon at the end . I hope you are sticking to the "consistent indentation" rule. This makes the program easier and reduces the amount of indentation required. Remember that the elif and else parts are optional. Python sees the ends of the program and simply finishes up. Then. All these are pretty straightforward (and surprisingly simple for those of you from C/C++ backgrounds) and requires you to become 39 . and if so. Although this is a very simple program. we compare the guess of the user with the number we have chosen. We set the variable number to any integer we want. Functions are just reusable pieces of programs.we are indicating to Python that a block of statements follows.Python en:Control Flow No. In this case. we print a success message. Once we enter something and press enter key. we take the user's guess using the input() function. it moves on to the next statement in the block containing the if statement. If they are equal. Notice that we use indentation levels to tell Python which statements belong to which block. we inform the user to guess a little higher than that. I have been pointing out a lot of things that you should notice even in this simple program. we check if the guess is less than the number. A minimal valid if statement is: if True: print('Yes. The elif and else statements must also have a colon at the end of the logical line followed by their corresponding block of statements (with proper indentation. (but you do not win any prizes!) Done How It Works: In this program.py Enter an integer : 23 Congratulations. This is why indentation is so important in Python. of course) You can have another if statement inside the if-block of an if statement and so on . it is true') After Python has finished executing the complete if statement along with the associated elif and else clauses. What we have used here is the elif clause which actually combines two related if else-if else statements into one combined if-elif-else statement. We then convert this string to an integer using int and then store it in the variable guess. the int is a class but all you need to know right now is that you can use it to convert a string to an integer (assuming the string contains a valid integer in the text). we take guesses from the user and check if it is the number that we have. We supply a string to the built-in input function which prints it to the screen and waits for input from the user.this is called a nested if statement. Then. the input() function returns what we entered.
elif.') running = False # this causes the while loop to stop elif guess < number: print('No. A while statement is an example of what is called a looping statement. You can use an if.py number = 23 running = True while running: guess = int(input('Enter an integer : ')) if guess == number: print('Congratulations. Note for C/C++ Programmers There is no switch statement in Python. A while statement can have an optional else clause. it is a little lower than that. it is a little lower than that. but after that.') # Do anything else you want to do here print('Done') Output: $ python while.') else: print('The while loop is over. you guessed it.Python en:Control Flow aware of all these initially. Enter an integer : 22 No. it is a little higher than that. use a dictionary to do it quickly) 40 The while Statement The while statement allows you to repeatedly execute a block of statements as long as a condition is true. The while loop is over. you will become comfortable with it and it'll feel 'natural' to you.') else: print('No.. Done How It Works: .py Enter an integer : 50 No. Enter an integer : 23 Congratulations. you guessed it..else statement to do the same thing (and in some cases. it is a little higher than that. Example: #!/usr/bin/python # Filename: while.
This aptly demonstrates the use of the while statement. What you need to know right now is that a sequence is just an ordered collection of items. First. it is always executed unless you break out of the loop with a break statement.in statement is another looping statement which iterates over a sequence of objects i. we are still playing the guessing game. we execute the while-block again. The else block is executed when the while loop condition becomes False .py for i in range(1. the condition is again checked which in this case is the running variable. Note for C/C++ Programmers Remember that you can have an else clause for the while loop. we check if the variable running is True and then proceed to execute the corresponding while-block. else we continue to execute the optional else-block and then continue to the next statement. We move the input and if statements to inside the while loop and set the variable running to True before the while loop.. If it is true. but the advantage is that the user is allowed to keep guessing until he guesses correctly . go through each item in a sequence. 5): print(i) else: print('The for loop is over') Output: $ python for. After this block is executed.5) . If there is an else clause for a while loop.this may even be the first time that the condition is checked. as we have done in the previous section. The True and False are called Boolean types and you can consider them to be equivalent to the value 1 and 0 respectively. We generate this sequence of numbers using the built-in range function.Python en:Control Flow In this program. we are printing a sequence of numbers. Example: #!/usr/bin/python # Filename: for. For example. 41 The for loop The for. What we do here is supply it two numbers and range returns a sequence of numbers starting from the first number and up to the second number. We will see more about sequences in detail in later chapters.e. range(1.there is no need to repeatedly run the program for each guess.py 1 2 3 4 The for loop is over How It Works: In this program.
the for loop is simpler.e. then that becomes the step count. By default. we have a list of numbers generated by the built-in range function. As you can see. In C/C++.5.py while True: s = (input('Enter something : ')) if s == 'quit': break print('Length of the string is'. then in Python you write just for i in range(0. Remember that the else part is optional. If we supply a third number to range. 4] which is like assigning each number (or object) in the sequence to i.2) gives [1.e. An important note is that if you break out of a for or while loop. and then executing the block of statements for each value of i. range(1. Note for C/C++/Java/C# Programmers The Python for loop is radically different from the C/C++ for loop. For example. When included. 2. Java programmers will note that the same is similar to for (int i : IntArray) in Java 1. stop the execution of a looping statement.5).5) is equivalent to for i in [1.py Enter something : Programming is fun Length of the string is 18 Enter something : When the work is done Length of the string is 21 . any corresponding loop else block is not executed. 42 The break Statement The break statement is used to break out of a loop statement i.. one at a time. The for loop then iterates over this range . i < 5. C# programmers will note that the for loop in Python is similar to the foreach loop in C#. even if the loop condition has not become False or the sequence of items has been completely iterated over. it does not include the second number. len(s)) print('Done') Output: $ python break.Python en:Control Flow gives the sequence [1.5 . i++). it is always executed once after the for loop is over unless a break statement is encountered.3]. range takes a step count of 1.for i in range(1. if you want to write for (int i = 0. we just print the value in the block of statements.in loop works for any sequence. but in general we can use any kind of sequence of any kind of objects! We will explore this idea in detail in later chapters. Remember that the range extends up to the second number i. 4]. Here. 3. more expressive and less error prone in Python. In this case. Remember that the for. 2. Example: #!/usr/bin/python # Filename: break. 3.
Example: #!/usr/bin/python # Filename: continue. Output: $ python test..Python en:Control Flow Enter something : if you wanna make your work also fun: Length of the string is 37 Enter something : use Python! Length of the string is 12 Enter something : quit Done How It Works: In this program..py while True: s = input('Enter something : ') if s == 'quit': break if len(s) < 3: print('Too small') continue print('Input is of sufficient length') # Do other kinds of processing here.py Enter something : a Too small Enter something : 12 Too small . we repeatedly take the user's input and print the length of each input each time.. We stop the program by breaking out of the loop and reach the end of the program. We are providing a special condition to stop the program by checking if the user input is 'quit'. Remember that the break statement can be used with the for loop as well. The length of the input string can be found out using the built-in len function.
They allow you to give a name to a block of statements and you can run that block using that name anywhere in your program and any number of times. php? oldid=1664 Contributors: Swaroop. Otherwise. This is followed by an identifier name for the function followed by a pair of parentheses which may enclose some names of variables and the line ends with a colon. but we process them only if they are at least 3 characters long. 44 Summary We have seen how to use the three control flow statements . while and for along with their associated break and continue statements. 8 anonymous edits Python en:Functions Introduction Functions are reusable pieces of programs.Python en:Control Flow Enter something : abc Input is of sufficient length Enter something : quit How It Works: In this program. This is known as calling the function. so we will explore various aspects of functions in this chapter.if. The function concept is probably the most important building block of any non-trivial software (in any programming language). swaroopch. com/ mediawiki/ index. These are some of the most often used parts of Python and hence. we will see how to create and use functions. we skip the rest of the statements in the block by using the continue statement. we accept input from the user.py def sayHello(): print('Hello World!') # block belonging to the function # End of function . So. becoming comfortable with them is essential. Note that the continue statement works with the for loop as well. Next. the rest of the statements in the loop are executed and we can do any kind of processing we want to do here. An example will show that this is actually very simple: Example: #!/usr/bin/python # Filename: function1. Previous Next Source: http:/ / www. Functions are defined using the def keyword. Next follows the block of statements that are part of this function. we use the built-in len function to get the length and if the length is less than 3. We have already used many built-in functions such as the len and range.
Notice that we can call the same function twice which means we do not have to write the same code again.Python en:Functions 45 sayHello() # call the function sayHello() # call the function again Output: $ python function1. Example: #!/usr/bin/python # Filename: func_param. we supply the values in the same way. Function Parameters A function can take parameters. 'is maximum') elif a == b: print(a. separated by commas. Parameters to functions are just input to the function so that we can pass in different values to it and get back corresponding results. b): if a > b: print(a. When we call the function. This function takes no parameters and hence there are no variables declared in the parentheses. y) # give variables as arguments Output: . 'is maximum') printMax(3. These parameters are just like variables except that the values of these variables are defined when we call the function and are already assigned values when the function runs. 4) # directly give literal values x = 5 y = 7 printMax(x. Parameters are specified within the pair of parentheses in the function definition.py def printMax(a.the names given in the function definition are called parameters whereas the values you supply in the function call are called arguments. b) else: print(b. which are values you supply to the function so that the function can do something utilising those values.py Hello World! Hello World! How It Works: We define a function called sayHello using the syntax as explained above. Note the terminology used . 'is equal to'.
py x is 50 Changed local x to 2 x is still 50 How It Works: In the function. the x defined in the main block remains unaffected. arguments. we directly supply the numbers i. In the first usage of printMax. So. x) func(x) print('x is still'. Example: #!/usr/bin/python # Filename: func_local. 46 Local Variables When you declare variables inside a function definition.Python en:Functions $ python func_param..e. we call the function using variables. In the last print function call.py x = 50 def func(x): print('x is'. x) x = 2 print('Changed local x to'. This is called the scope of the variable.py 4 is maximum 7 is maximum How It Works: Here. The printMax function works the same in both the cases. we display the value of x in the main block and confirm that it is actually unaffected.else statement and then print the bigger number. Python uses the value of the parameter declared in the function. when we change the value of x in the function. x) Output: $ python func_local. Next. The name x is local to our function. printMax(x.e. We find out the greater number using a simple if. the first time that we use the value of the name x. variable names are local to the function. All variables have the scope of the block they are declared in starting from the point of definition of the name. y) causes value of argument x to be assigned to parameter a and the value of argument y assigned to parameter b. we assign the value 2 to x. we define a function called printMax where we take two parameters called a and b. In the second usage. . they are not related in any way to other variables with the same names used outside the function i.
py x = 50 def func(): global x print('x is'. x) func() print('Value of x is'. You can specify more than one global variable using the same global statement. You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). global x. For example. x) x = 2 print('Changed global x to'. However. Example: #!/usr/bin/python # Filename: func_global. that change is reflected when we use the value of x in the main block.Python en:Functions 47 Using The global Statement If you want to assign a value to a name defined at the top level of the program (i. Using the global statement makes it amply clear that the variable is defined in an outermost block. but it is global.e. x) Output: $ python func_global. It is impossible to assign a value to a variable defined outside a function without the global statement. then you have to tell Python that the name is not local. . z. y. We do this using the global statement. not inside any kind of scope such as functions or classes).hence. when we assign a value to x inside the function.
We declare that we are using this x by nonlocal x and hence we get access to that variable. Default Argument Values For some functions. Example: .Python en:Functions 48 Using nonlocal statement We have seen how to access variables in the local and global scope above. the default argument value should be immutable .py x is 2 Changed local x to 5 How It Works: When we are inside func_inner. For now. just remember this. you can define functions anywhere. This is done with the help of default argument values. Since everything in Python is just executable code. There is another kind of scope called "nonlocal" scope which is in-between these two types of scopes.. Nonlocal scopes are observed when you define functions inside functions. Note that the default argument value should be a constant. x) func_outer() Output: $ python func_nonlocal. x) def func_inner(): nonlocal x x = 5 func_inner() print('Changed local x to'.py def func_outer(): x = 2 print('x is'. More precisely. Let's take an example: #!/usr/bin/python # Filename: func_nonlocal.this is explained in detail in later chapters. Try changing the nonlocal x to global x and also by removing the statement itself and observe the difference in behavior in these two cases. the 'x' defined in the first line of func_outer is relatively neither in local scope nor in global scope.
Two.we use the name (keyword) instead of the position (which we have been using all along) to specify the arguments to the function. then by default. b) is not valid. but def func(a=5. Example: #!/usr/bin/python # Filename: func_key. def func(a. then you can give values for such parameters by naming them . We achieve this by specifying a default argument value of 1 to the parameter times.py def say(message. times = 1): print(message * times) say('Hello') say('World'. 5) Output: $ python func_default.one. For example. Important Only those parameters which are at the end of the parameter list can be given default argument values i.this is called keyword arguments . c) func(3. a. This is because the values are assigned to the parameters by position.Python en:Functions #!/usr/bin/python # Filename: func_default. b=5.py Hello WorldWorldWorldWorldWorld How It Works: The function named say is used to print a string as many times as specified. In the second usage of say. you cannot have a parameter with a default argument value before a parameter without a default argument value in the order of parameters declared in the function parameter list. In the first usage of say. b. 7) . we supply only the string and it prints the string once.e.py def func(a. we can give values to only those parameters which we want. provided that the other parameters have default argument values. There are two advantages . 'and c is'. using the function is easier since we do not need to worry about the order of the arguments. 'and b is'. 49 Keyword Arguments If you have some functions with many parameters and you want to specify only some of them. we supply both the string and an argument 5 stating that we want to say the string message 5 times. c=10): print('a is'. If we don't supply a value. b=5) is valid. the string is printed just once.
*numbers. keyword arguments. 1.py 166 How It Works: . the parameter c gets the value of 24 due to naming i. 7). a=100) Output: $ a a a python func_key. that we are specifying value for parameter c before that for a even though a is defined before c in the function definition. In the first usage. VarArgs parameters TODO Should I write about this in a later chapter since we haven't talked about lists and dictionaries yet? Sometimes you might want to define a function that can take any number of parameters. fruits=100)) Output: $ python total. Then.py def total(initial=5. Notice. the parameter b gets the value 7 and c gets the default value of 10. In the second usage func(25. the variable a gets the value of 25 due to the position of the argument.e. vegetables=50. 2.py is 3 and b is 7 and c is 10 is 25 and b is 5 and c is 24 is 100 and b is 5 and c is 50 50 How It Works: The function named func has one parameter without default argument values.Python en:Functions func(25. In the third usage func(c=50. the parameter a gets the value 3. c=24). func(3. The variable b gets the default value of 5. 3. c=24) func(c=50. followed by two parameters with default argument values. we use keyword arguments completely to specify the values. a=100). this can be achieved by using the stars: #!/usr/bin/python # Filename: total. **keywords): count = initial for number in numbers: count += number for key in keywords: count += keywords[key] return count print(total(10.
Therefore. php? oldid=2379 Contributors: Swaroop. Summary We have seen so many aspects of functions but note that we still haven't covered all aspects of it. com/ mediawiki/ index. Previous Next Source: http:/ / www. please see the Python Enhancement Proposal No. 3107 (http:/ / www. Automated tools can retrieve the documentation from your program in this manner. 7 anonymous edits . swaroopch. org/ dev/ peps/ pep-3107/ ). we will skip this feature in our discussion. If you are interested to read about annotations. we will see how to use as well as create Python modules. I strongly recommend that you use docstrings for any non-trivial function that you write. Next.Python en:Functions your program. we have already covered most of what you'll use regarding Python functions on an everyday basis. python. 54 Annotations Functions have another advanced feature called annotations which are a nifty way of attaching additional information for each of the parameters as well as the return value. However. Since the Python language itself does not interpret these annotations in any way (that functionality is left to third-party libraries to interpret in any way they want). Remember to press the q key to exit help. The pydoc command that comes with your Python distribution works similarly to help() using docstrings. Vages.
A module can be imported by another program to make use of its functionality.py we are arguments The command line arguments are: using_sys. the system.e.py extension that contains functions and variables. you can write modules in the C programming language (http:/ / docs. Example: #!/usr/bin/python # Filename: using_sys. There are various methods of writing modules. The sys module contains functionality related to the Python interpreter and its environment i. '\n') Output: $ python using_sys.py import sys print('The command line arguments are:') for i in sys.zip'. First. What if you wanted to reuse a number of functions in other programs that you write? As you might have guessed. sys. 'C:\\Python30\\lib\\plat-win'. 'C:\\Python30\\DLLs'. 'C:\\Python30\\lib'. Basically.py we are arguments The PYTHONPATH is [''. we import the sys module using the import statement. we will see how to use the standard library modules. . the answer is modules. 'C:\\Python30\\lib\\site-packages'] How It Works: First. 'C:\\Python30'. 'C:\\Windows\\system32\\python30. this translates to us telling Python that we want to use this module.argv: print(i) print('\n\nThe PYTHONPATH is'. Another method is to write the modules in the native language in which the Python interpreter itself was written. but the simplest way is to create a file with a . they can be used from your Python code when using the standard Python interpreter.path. org/ extending/ ) and when compiled.Python en:Modules 55 Python en:Modules Introduction You have seen how you can reuse code in your program by defining functions once. For example. python. This is how we can use the Python standard library as well.
these byte-compiled files are platform-independent.argv[2] and 'arguments' as sys. then the Python interpreter will search for it in the directories listed in its sys. If you are using an IDE to write and run these programs. The sys. The sys. Otherwise. Note These . sys. If it was not a compiled module i. Notice that Python starts counting from 0 and not 1. This means that you can directly import modules located in the current directory. in this case we will have 'using_sys. Note that the initialization is done only the first time that we import a module.argv list. So.argv variable is a list of strings (lists are explained in detail in a later chapter. Note that the current directory is the directory from which the program is launched. It clearly indicates that this name is part of the sys module.getcwd()) to find out the current directory of your program. One way is to create byte-compiled files with the extension . it looks for the sys module.py files.path which is same as the PYTHONPATH environment variable.e. 'are' as sys. the arguments passed to your program using the command line. and hence Python knows where to find it. Specifically. print(os. .py we are arguments. Another advantage of this approach is that the name does not clash with any argv variable used in your program. look for a way to specify command line arguments to the program in the menus.argv. it is one of the built-in modules.pyc which is an intermediate form that Python transforms the program into (remember the introduction section on how Python works?).pyc file is useful when you import the module the next time from a different program . then the . a module written in Python.py with the python command and the other things that follow are arguments passed to the program.path contains the list of directory names where modules are imported from.e.path is empty . Python stores the command line arguments in the sys.argv contains the list of command line arguments i. so Python does some tricks to make it faster.argv[1]. Run import os. Also. then the statements in the body of that module is run and then the module is made available for you to use. If Python does not have permission to write to files in that directory. we run the module using_sys.argv[3].argv variable for us to use.Python en:Modules When Python executes the import sys statement. Here.it will be much faster since a portion of the processing required in importing a module is already done. when we execute python using_sys.pyc files Importing a module is a relatively costly affair. The argv variable in the sys module is accessed using the dotted notation i.path. This .py' as sys.pyc files are usually created in the same directory as the corresponding . If the module is found. the sys.argv[0]. 'we' as sys.pyc files will not be created. Remember. you will have to place your module in one of the directories listed in sys.this empty string indicates that the current directory is also part of the sys. 56 Byte-compiled . Observe that the first string in sys. In this case.path variable. the name of the script running is always the first argument in the sys.e.
If you want to import all the names used in the sys module. A module's __name__ Every module has a name and statements in a module can find out the name of its module.statement If you want to directly import the argv variable into your program (to avoid typing the sys. it implies that the module is being run standalone by the user and we can take appropriate actions. We can use this concept to alter the behavior of the module if the program was used by itself and not when it was imported from another module. everytime for it). This is handy in the particular situation of figuring out if the module is being run standalone or being imported. This can be achieved using the __name__ attribute of the module. when a module is imported for the first time. then you can use the from sys import * statement.py This program is being run by itself $ python >>> import using_name I am being imported from another module >>> How It Works: Every Python module has it's __name__ defined and if this is '__main__'. the code in that module is executed. As mentioned previously.import . In general. you should avoid using this statement and use the import statement instead since your program will avoid name clashes and will be more readable. This works for any module.... then you can use the from sys import argv statement.py if __name__ == '__main__': print('This program is being run by itself') else: print('I am being imported from another module') Output: $ python using_name.. . Example: #!/usr/bin/python # Filename: using_name.Python en:Modules 57 The from .
As you can see.py from mymodule import sayhi.py def sayhi(): print('Hi.py Hi.__version__) Output: $ python mymodule_demo.. Version 0.py extension. mymodule.py The above was a sample module.Python en:Modules 58 Making Your Own Modules Creating your own modules is easy. We will next see how to use this module in our other Python programs.py import mymodule mymodule. Example: #!/usr/bin/python # Filename: mymodule.1 How It Works: Notice that we use the same dotted notation to access members of the module.') __version__ = '0. there is nothing particularly special about compared to our usual Python program. you've been doing it all along! This is because every Python program is also a module. #!/usr/bin/python # Filename: mymodule_demo.sayhi() print ('Version'.1' # End of mymodule. or the module should be in one of the directories listed in sys. Remember that the module should be placed in the same directory as the program that we import it in. this is mymodule speaking. You just have to make sure it has a . __version__ sayhi() print('Version'. __version__) .path. Here is a version utilising the from.import syntax: #!/usr/bin/python # Filename: mymodule_demo2. Python makes good reuse of the same notation to give the distinctive 'Pythonic' feel to it so that we don't have to keep learning new ways to do things. this is mymodule speaking. The following example should make it clear.
Example: $ python >>> import sys # get list of attributes. '__doc__'. Run import this to learn more and see this discussion (http:/ / stackoverflow. Hence. 'getcheckinterval'. 'flags'. 'callstats'. 'path_hooks'. '_getframe'. When no argument is applied to it. You could also use: from mymodule import * This will import all public names such as sayhi but would not import __version__ because it starts with double underscores. '__s tderr__'. 'call_tracing'. 'getfil esystemencoding'. 'path_importer_cache'.Python en:Modules The output of mymodule_demo2. 'hexversion'. for a module. it returns the list of names defined in the current module. 'excepthook'. 'getwindowsversion'. 'getrecursionlimit'. '__excepthook__'. it is always recommended to prefer the import statement even though it might make your program a little longer. 'maxunicode '. 'modules'. 'dont_write_bytecode'. 'gettrace'. 'builtin_module_names'. 'getdefaultencoding'. 'displayhook'. 'intern'. 59 The dir function You can use the built-in dir function to list the identifiers that an object defines. 'exec_prefix'. ' byteorder'. '__stdin__'. 'path'. For example. '__stdout__'. 'float_info'. the identifiers include the functions. there would be a clash. Zen of Python One of Python's guiding principles is that "Explicit is better than Implicit". '_clear_type_cache'. 'maxsize'. classes and variables defined in that module. 'meta_path'. 'getprofile'. 'exc_info'. '_compact_freelists'. This is also likely because it is common practice for each module to declare it's version number using this name.py. . 'argv'. '__package__'. When you supply a module name to the dir() function. 'executable'. Notice that if there was already a __version__ name declared in the module that imports mymodule.py is same as the output of mymodule_demo. 'copyright'. 'dllhandle' . '__name__'. 'getrefcount'. 'exit'. 'api_version'. '_current_frames'. it returns the list of the names defined in that module. com/ questions/ 228181/ zen-of-python) which lists examples for each of the principles. in this case. for the sys module >>> dir(sys) ['__displayhook__'. 'getsizeof'.
'setrecursionlimit '. Next. '__name__'. '__name__'. 60 . 'sys'] >>> del a # delete/remove a name >>> dir() ['__builtins__'. in this case del a.this statement is used to delete a variable/name and after the statement has run. '__doc__'. 'ps2'. For example. 'stdout'. 'sys'] >>> a = 5 # create a new variable 'a' >>> dir() ['__builtins__'. 'warnoptions'. 'setcheckinterval'. '__name__'. We remove the variable/attribute of the current module using the del statement and the change is reflected again in the output of the dir function. 'a'. 'ps1'. 'stderr'. Note that the dir() function works on any object. 'version'. it returns the list of attributes for the current module. '__package__'. 'sys'] >>> How It Works: First. 'prefix'. '__package__'. '__package__'. we see the usage of dir on the imported sys module. we define a new variable a and assign it a value and then check dir and we observe that there is an additional value in the list of the same name. you can no longer access the variable a . or dir(str) for the attributes of the str class. 'winver'] >>> dir() # get list of attributes for current module ['__builtins__'. By default. In order to observe the dir in action. '__doc__'. 'settrace'.it is as if it never existed before at all. 'stdin'. we use the dir function without passing parameters to it. run dir(print) to learn about the attributes of the print function. A note on del . 'subversion'. We can see the huge list of attributes that it contains.Python en:Modules 'platfor m'. Notice that the list of imported modules is also part of this list. 'version_in fo'. '__doc__'. 'setprofile'.
Python en:Modules 61 Packages By now. and these subpackages in turn contain modules like 'india'. You will see many instances of this in the standard library.py .madagascar/ . etc. Previous Next Source: http:/ / .py file that indicates to Python that this folder is special because it contains Python modules. Functions and global variables usually go inside modules.py . php? oldid=2371 Contributors: Swaroop.asia/ .<some folder present in the sys.africa/ . Summary Just like functions are reusable parts of programs. Variables usually go inside functions.py . we will learn about some interesting concepts called data structures. The standard library that comes with Python is an example of such a set of packages and modules. 7 anonymous edits . 'africa'. 'madagascar'. swaroopch. com/ mediawiki/ index.world/ . etc. Packages are another hierarchy to organize modules.py . What if you wanted to organize modules? That's where packages come into the picture.__init__.__init__.path>/ .foo. modules are reusable programs. Next. This is how you would structure the folders: .py . We have seen how to use these modules and create our own modules.__init__.py . Packages are just folders of modules with a special __init__. you must have started observing the hierarchy of organizing your programs.__init__.bar.py Packages are just a convenience to hierarchically organize modules.__init__. Let's say you want to create a package called 'world' with subpackages 'asia'.
for example.') print('These items are:'.py # This is my shopping list shoplist = ['apple'.append('an item') will add that string to the list mylist. you can read help(int) to understand this better. mylist.e.e.field. 'mango'. A class can also have fields which are nothing but variables defined for use with respect to that class only. Quick Introduction To Objects And Classes Although I've been generally delaying the discussion of objects and classes till now. In fact. functions defined for use with respect to that class only.they are structures which can hold some data together. this type can be altered. Example: #!/usr/bin/python # Filename: using_list. This is easy to imagine if you can think of a shopping list where you have a list of items to buy. you can add. A class can also have methods i. say integer 5 to it. len(shoplist). 'items to purchase. type) int. Note the use of dotted notation for accessing methods of the objects.list. Once you have created a list. We will see how to use each of them and how they make life easier for us.Python en:Data Structures 62 Python en:Data Structures Introduction Data structures are basically just that .e. The list of items should be enclosed in square brackets so that Python understands that you are specifying a list. we say that a list is a mutable data type i. A list is an example of usage of objects and classes. 'banana'] print('I have'. you can think of it as creating an object (i. For example. We will explore this topic in detail later in its own chapter.e. a little explanation is needed right now so that you can understand lists better. except that you probably have each item on a separate line in your shopping list whereas in Python you put commas in between them. Fields are also accessed by the dotted notation. you can store a sequence of items in a list. You can use these pieces of functionality only when you have an object of that class. end=' ') . tuple.e. they are used to store a collection of related data. There are four built-in data structures in Python . remove or search for items in the list. dictionary and set. Since we can add and remove items. mylist. Python provides an append method for the list class which allows you to add an item to the end of the list. In other words. List A list is a data structure that holds an ordered collection of items i. For example. 'carrot'. When we use a variable i and assign a value to it. instance) i of class (i. You can use these variables/names only when you have an object of that class.
shoplist) print('The first item I will buy is'. This is what we mean by saying that lists are mutable and that 63 . we only store strings of the names of the items to buy but you can add any kind of object to a list including numbers and even other lists. Then. shoplist) print('I will sort my list now') shoplist. The speciality of sequences will be discussed in a later section. Next.sort() print('Sorted shopping list is'.this is different from the way strings work. 'carrot'. We have also used the for. olditem) print('My shopping list is now'. 'rice'] I will sort my list now Sorted shopping list is ['apple'.append('rice') print('My shopping list is now'. we sort the list by using the sort method of the list. 'banana'. 'banana'. By now. In shoplist. we add an item to the list using the append method of the list object. we check that the item has been indeed added to the list by printing the contents of the list by simply passing the list to the print statement which prints it neatly. 'rice'] The first item I will buy is apple I bought the apple My shopping list is now ['banana'. These items are: apple mango carrot banana I also have to buy rice.. 'rice'] How It Works: The variable shoplist is a shopping list for someone who is going to the market. you must have realised that a list is also a sequence. Then. shoplist) Output: $ python using_list. 'carrot'. Notice the use of the end keyword argument to the print function to indicate that we want to end the output with a space instead of the usual line break. 'mango'. as already discussed before. end=' ') print('\nI also have to buy rice. shoplist[0]) olditem = shoplist[0] del shoplist[0] print('I bought the'.Python en:Data Structures for item in shoplist: print(item.in loop to iterate through the items of the list.') shoplist.py I have 4 items to purchase. 'mango'. It is important to understand that this method affects the list itself and does not return a modified list . 'mango'. My shopping list is now ['apple'. 'carrot'.
new_zoo[2][2]) print('Number of animals in the new zoo is'.e.Python en:Data Structures strings are immutable. len(new_zoo)) print('All animals in new zoo are'. 'penguin') Last animal brought from old zoo is penguin Number of animals in the new zoo is 5 How It Works: The variable zoo refers to a tuple of items. len(zoo)) new_zoo = ('monkey'. new_zoo[2]) print('Last animal brought from old zoo is'. 64 Tuple Tuples are used to hold together multiple objects. 'camel'. Here. 'elephant'. you cannot modify tuples. 'elephant'. One major feature of tuples is that they are immutable like strings i. we want to remove it from the list. 'elephant'. the tuple of values used will not change. but without the extensive functionality that the list class gives you.py zoo = ('python'. We specify that we want to remove the first item from the list and hence we use del shoplist[0] (remember that Python starts counting from 0). 'camel'. This also indicates that a tuple is a sequence as well. ('python'. zoo) print('Number of cages in the new zoo is'. Example: #!/usr/bin/python # Filename: using_tuple.py Number of animals in the zoo is 3 Number of cages in the new zoo is 3 All animals in new zoo are ('monkey'. 'penguin')) Animals brought from old zoo are ('python'. 'penguin') # remember the parentheses are optional print('Number of animals in the zoo is'. see help(list) for details. We see that the len function can be used to get the length of the tuple. If you want to know all the methods defined by the list object. Tuples are usually used in cases where a statement or a user-defined function can safely assume that the collection of values i. len(new_zoo)-1+len(new_zoo[2])) Output: $ python using_tuple.e. we mention which item of the list we want to remove and the del statement removes it from the list for us. new_zoo) print('Animals brought from old zoo are'. when we finish buying an item in the market. Think of them as similar to lists. . Tuples are defined by specifying items separated by commas within an optional pair of parentheses. Next. We achieve this by using the del statement.
a tuple with a single item is not so simple. As far as Python is concerned. Notice that the key-value pairs are separated by a colon and the pairs are separated themselves by commas and all this is enclosed in a pair of curly braces. then you will have to sort them yourself before using it. The dictionaries that you will be using are instances/objects of the dict class. Remember that key-value pairs in a dictionary are not ordered in any manner.e. However. Note for Perl programmers A list within a list does not lose its identity i. Pairs of keys and values are specified in a dictionary by using the notation d = {key1 : value1. I prefer always having them to make it obvious that it is a tuple.2. especially because it avoids ambiguity. You have to specify it using a comma following the first (and only) item so that Python can differentiate between a tuple and a pair of parentheses surrounding the object in an expression i. We can access the items in the tuple by specifying the item's position within a pair of square brackets just like we did for lists. they are just objects stored using another object. Parentheses Although the parentheses is optional. ) if you mean you want a tuple containing the item 2. or a list within a tuple. key2 : value2 }. the new_zoo tuple contains some animals which are already there along with the animals brought over from the old zoo.2. we associate keys (name) with values (details). Example: #!/usr/bin/python # Filename: using_dict. We access the third item in new_zoo by specifying new_zoo[2] and we access the third item within the third item in the new_zoo tuple by specifying new_zoo[2][2]. 65 Dictionary A dictionary is like an address-book where you can find the address or contact details of a person by knowing only his/her name i. The same applies to a tuple within a tuple. If you want a particular order. print(1.3) ) mean two different things . Note that the key must be unique just like you cannot find out the correct information if you have two persons with the exact same name.e.py . lists are not flattened as in Perl. or a tuple within a list. you have to specify singleton = (2 . This is called the indexing operator. Back to reality. etc.3) and print( (1. Note that you can use only immutable objects (like strings) for the keys of a dictionary but you can use either immutable or mutable objects for the values of the dictionary. Tuple with 0 or 1 items An empty tuple is constructed by an empty pair of parentheses such as myempty = (). This basically translates to say that you should use only simple objects for keys. that's all. This is pretty simple once you've understood the idiom.the former prints three numbers whereas the latter prints a tuple (which contains three numbers). Therefore.Python en:Data Structures We are now shifting these animals to a new zoo since the old zoo is being closed.e. note that a tuple within a tuple does not lose its identity. For example.
the del statement. '[email protected] en:Data Structures # 'ab' is short for 'a'ddress'b'ook ab = { 'Swaroop' 'Larry' 'Matsumoto' 'Spammer' : : : : 'swaroop@swaroopch. 'matz@ruby-lang. ab['Guido']) Output: $ python using_dict.org'. We simply specify the dictionary and the indexing operator for the key to be removed and pass it to the del statement.com'.. We can delete key-value pairs using our old friend .org How It Works: We create the dictionary ab using the notation already discussed. '[email protected] key followed by the value. address)) # Adding a key-value pair ab['Guido'] = 'guido@python. ab['Swaroop']) # Deleting a key-value pair del ab['Spammer'] print('\nThere are {0} contacts in the address-book\n'.org Guido's address is [email protected] There are 3 contacts in the address-book Contact Swaroop at swaroop@swaroopch. address in ab.py Swaroop's address is [email protected]_key('Guido') print("\nGuido's address is".format(len(ab))) for name. We retrieve this pair and assign it to the variables name and address correspondingly for each pair using the for. we access each key-value pair of the dictionary using the items method of the dictionary which returns a list of tuples where each tuple contains a pair of items .com Contact Matsumoto at matz@ruby-lang. We then access key-value pairs by specifying the key using the indexing operator as discussed in the context of lists and tuples. Observe the simple syntax.format(name.in loop and then print these values in the . There is no need to know the value corresponding to the key for this operation. Next.items(): print('Contact {0} at {1}'.org' if 'Guido' in ab: # OR ab.org Contact Larry at [email protected]'.com' 66 } print("Swaroop's address is".
Example: #!/usr/bin/python # Filename: seq. shoplist[:]) # Slicing on a string .e. shoplist[2]) print('Item 3 is'. shoplist[0]) print('Item 1 is'. The three types of sequences mentioned above . 67 Sequences Lists. We can add new key-value pairs by simply using the indexing operator to access a key and assign that value. 'banana'] name = 'swaroop' # Indexing or 'Subscription' operation print('Item 0 is'. shoplist[1:-1]) print('Item start to end is'.e. you have already used dictionaries! Just think about it . it is just a key access of a dictionary (which is called the symbol table in compiler design terminology). shoplist[1:3]) print('Item 2 to end is'. also have a slicing operation which allows us to retrieve a slice of the sequence i. if you have used keyword arguments in your functions. shoplist[2:]) print('Item 1 to -1 is'. tuples and strings. 'carrot'. The indexing operation which allows us to fetch a particular item in the sequence directly.lists.the key-value pair is specified by you in the parameter list of the function definition and when you access variables within your function. as we have done for Guido in the above case. You can see the documentation for the complete list of methods of the dict class using help(dict). shoplist[-1]) print('Item -2 is'. shoplist[3]) print('Item -1 is'. shoplist[1]) print('Item 2 is'. shoplist[-2]) print('Character 0 is'. the in and not in expressions) and indexing operations. a part of the sequence.py shoplist = ['apple'. 'mango'. Keyword Arguments and Dictionaries On a different note. name[0]) # Slicing on a list print('Item 1 to 3 is'.. tuples and strings are examples of sequences.
Remember the numbers are optional but the colon isn't. 'carrot'] Item 2 to end is ['carrot'.Python en:Data Structures print('characters print('characters print('characters print('characters Output: $ python seq. in which case. Note that the slice returned starts at the start position and will end just before the end position i. name[1:3]) 2 to end is'. Python will start at the beginning of the sequence. If the first number is not specified. name[2:]) 1 to -1 is'. shoplist[:] returns a copy of the whole sequence. Whenever you specify a number to a sequence within square brackets as shown above. 'carrot'] Item start to end is ['apple'. 'carrot'. 'banana'] characters 1 to 3 is wa characters 2 to end is aroop characters 1 to -1 is waroo characters start to end is swaroop How It Works: First. Similarly. the start position is included but the end position is excluded from the sequence slice. Python will stop at the end of the sequence. The index can also be a negative number. 1 to 3 is'. shoplist[0] fetches the first item and shoplist[3] fetches the fourth item in the shoplist sequence. 'banana'] Item 1 to -1 is ['mango'. we see how to use indexes to get individual items of a sequence. Hence. If the second number is left out. This is also referred to as the subscription operation. Thus. The first number (before the colon) in the slicing operation refers to the position from where the slice starts and the second number (after the colon) indicates where the slice will stop at. Therefore. Remember that Python starts counting numbers from 0.py Item 0 is apple Item 1 is mango Item 2 is carrot Item 3 is banana Item -1 is banana Item -2 is carrot Character 0 is s Item 1 to 3 is ['mango'.e. Python will fetch you the item corresponding to that position in the sequence. shoplist[1:3] returns a slice of the sequence starting at position 1. 'mango'. name[:]) 68 . includes position 2 but stops at position 3 and therefore a slice of two items is returned. shoplist[-1] refers to the last item in the sequence and shoplist[-2] fetches the second last item in the sequence.. name[1:-1]) start to end is'.
The great thing about sequences is that you can access tuples. 3. 2. . 'carrot'. 'carrot'] >>> shoplist[::3] ['apple'.. the prompt so that you can see the results immediately. 'carrot'. 'apple'] Notice that when the step is 2. Negative numbers are used for positions from the end of the sequence. 'banana'] >>> shoplist[::1] ['apple'. Using sets. You can also provide a third argument for the slice. . 'russia'. shoplist[:-1] will return a slice of the sequence which excludes the last item of the sequence but contains everything else. and so on. 'mango'.intersection(bric) {'brazil'. 'mango'.issuperset(bri) True >>> bri.remove('russia') >>> bri & bric # OR bri. find the intersection between two sets. we get the items with position 0.e. which is the step for the slicing (by default. These are used when the existence of an object in a collection is more important than the order or how many times it occurs. 'mango'. 'india'} How It Works: The example is pretty much self-explanatory because it involves basic set theory mathematics taught in school. the step size is 1): >>> shoplist = ['apple'. 'india']) >>> 'india' in bri True >>> 'usa' in bri False >>> bric = bri. Try various combinations of such slice specifications using the Python interpreter interactively i. 'carrot'. When the step size is 3.Python en:Data Structures You can also do slicing with negative positions. lists and strings all in the same way! 69 Set Sets are unordered collections of simple objects. For example.. we get the items with position 0.copy() >>> bric. 'banana'] >>> shoplist[::2] ['apple'. >>> bri = set(['brazil'.add('china') >>> bric. etc. whether it is a subset of another set. you can test for membership. 'banana'] >>> shoplist[::-1] ['banana'.
py print('Simple Assignment') shoplist = ['apple'. both of them will refer . '. Remember that if you want to make a copy of a list or such kinds of sequences or complex objects (not simple objects such as integers). 'carrot'. the variable name points to that part of your computer's memory where the object is stored. but there is a subtle effect due to references which you need to be aware of: Example: #!/usr/bin/python # Filename: reference. If you just assign the variable name to another name. the variable only refers to the object and does not represent the object itself! That is.Python en:Data Structures 70 References When you create an object and assign it to a variable. 'banana'] Copy by making a full slice shoplist is ['mango'. This is called as binding of the name to the object. 'banana'] mylist is ['mango'. 'banana'] How It Works: Most of the explanation is available in the comments. then you have to use the slicing operation to make a copy. 'banana'] mylist = shoplist # mylist is just another name pointing to the same object! del shoplist[0] # I purchased the first item. 'banana'] mylist is ['carrot'. mylist) # notice that now the two lists are different Output: $ python reference. shoplist) print('mylist is'. so I remove it from the list print('shoplist is'. 'carrot'.py Simple Assignment shoplist is ['mango'. 'carrot'. Generally. 'mango'. you don't need to be worried about this.
The str class also has a neat method to join the items of a sequence with the string acting as a delimiter between each item of the sequence and returns a bigger string generated from this. . the string starts with "Swa"') if 'a' in name: print('Yes.find('war') != -1: print('Yes. we see a lot of the string methods in action. Note for Perl programmers Remember that an assignment statement for lists does not create a copy. You have to use slicing operation to make a copy of the sequence.Python en:Data Structures to the same object and this could be trouble if you are not careful. For a complete list of such methods. Some useful methods of this class are demonstrated in the next example. What more can there be to know? Well.py name = 'Swaroop' # This is a string object if name.startswith('Swa'): print('Yes. 'Russia'.join(mylist)) Output: $ python str_methods. it contains the string "war" Brazil_*_Russia_*_India_*_China How It Works: Here. Example: #!/usr/bin/python # Filename: str_methods. did you know that strings are also objects and have methods which do everything from checking part of a string to stripping spaces! The strings that you use in program are all objects of the class str. it contains the string "a"') if name. the string starts with "Swa" Yes. The in operator is used to check if a given string is a part of the string. 71 More About Strings We have already discussed strings in detail earlier. it contains the string "a" Yes. 'India'. The find method is used to do find the position of the given string in the string or returns -1 if it is not successful to find the substring. see help(str).py Yes. 'China'] print(delimiter. The startswith method is used to find out whether the string starts with the given string. it contains the string "war"') delimiter = '_*_' mylist = ['Brazil'.
The idea is to learn how to write a Python script on your own. php) from the GnuWin32 project page (http:/ / gnuwin32. files are backed up into a zip file. Windows users can install (http:/ / gnuwin32. The Problem The problem is "I want a program which creates a backup of all my important files". Previous Next Source: http:/ / www. If you do the design. These data structures will be essential for writing programs of reasonable size. Note that you can use any archiving command you want as long as it has a command line interface so that we can pass arguments to it from our script. com/ mediawiki/ index. 5 anonymous edits Python en:Problem Solving We have explored various parts of the Python language and now we will take a look at how all these parts fit together. I have created the following list on how I want it to work. We use the standard zip command available by default in any standard Linux/Unix distribution. sourceforge. there is not enough information for us to get started with the solution. we design our program. we will next see how to design and write a real-world Python program. you may not come up with the same kind of analysis since every person has their own way of doing things. 3. backup must be stored in a main backup directory. php? oldid=1582 Contributors: Swaroop. Now that we have a lot of the basics of Python in place. this is a simple problem. We make a list of things about how our program should work. by designing and writing a program which does something useful. swaroopch. 4. . 2. 5. name of the zip archive is the current date and time. In this case.Python en:Data Structures 72 Summary We have explored the various built-in data structures of Python in detail. how do we specify which files are to be backed up? How are they stored? Where are they stored? After analyzing the problem properly. similar to what we did for recognizing the python command itself. 1. sourceforge. A little more analysis is required. net/ downlinks/ zip. For example. The The The The files and directories to be backed up are specified in a list. net/ packages/ zip. htm) and add C:\Program Files\GnuWin32\bin to your system PATH environment variable. Although. so that is perfectly okay.
target) else: print('Backup FAILED') Output: $ python backup_ver1.system(zip_command) == 0: print('Successful backup to'. ' '. then check the Python program if it exactly matches the program written above. We use the zip command to put the files in a zip archive zip_command = "zip -qr {0} {1}". The name of the zip archive is the current date and time target = target_dir + os. # 4.format(target. If the above program does not work for you. put a print(zip_command) just before the os. The backup must be stored in a main backup directory target_dir = 'E:\\Backup' # Remember to change this to what you will be using # 3. 'C:\\Code'] # Notice we had to use double quotes inside the string for names with spaces in it. Now copy/paste the printed zip_command to the shell prompt and see if it runs properly on its own. # 2. we can write the code which is an implementation of our solution. source = ['"C:\\My Documents"'.join(source)) # Run the backup if os.zip Now. remove the bugs (errors) from the program. If this command succeeds. The files are backed up into a zip file. then we have to debug our program i.py import os import time # 1.system call and run the program.Python en:Problem Solving 73 The Solution As the design of our program is now reasonably stable. If this command fails.strftime('%Y%m%d%H%M%S') + '.py Successful backup to E:\Backup\20080702185040. How It Works: You will notice how we have converted our design into code in a step-by-step manner. If it doesn't behave as expected.sep + time. . The files and directories to be backed up are specified in a list. check the zip command manual on what could be wrong.zip' # 5.e. #!/usr/bin/python # Filename: backup_ver1. we are in the testing phase where we test that our program works properly.
we create a string zip_command which contains the command that we are going to execute. Notice the use of os. we specify the files and directories to be backed up in the source list. 0/ library/ time.system function which runs the command as if it was run from the system i.e. there might be problems if you have not designed the program properly or if you have made a mistake in typing the code.sep variable . The above program works properly. The %m specification will be replaced by the month as a decimal number between 01 and 12 and so on.this gives the directory separator according to your operating system i.strftime() function.e. in the shell . The %Y specification will be replaced by the year without the century. it will be '\\' in Windows and ':' in Mac OS. Now that we have a working backup script.sep instead of these characters directly will make our program portable and work across these systems. We convert the source list into a string using the join method of strings which we have already seen how to use.it returns 0 if the command was successfully.strftime() function takes a specification such as the one we have used in the above program. Then. We create the name of the target zip file using the addition operator which concatenates the strings i. Linux/Unix users are advised to use the executable method as discussed earlier so that they can run the backup script anytime anywhere. The target directory is where store all the backup files and this is specified in the target_dir variable. For example. The complete list of such specifications can be found in the Python Reference Manual (http:/ / docs. However. strftime). you will have to go back to the design phase or you will have to debug your program. do not use 'C:\Documents' since you end up using an unknown escape sequence \D. it joins the two strings together and returns a new one. The two options are combined and specified in a shortcut as -qr.zip extension and will be stored in the target_dir directory. The zip command that we are using has some options and parameters passed.e. but (usually) first programs do not work exactly as you expect. For example. Depending on the outcome of the command. we print the appropriate message that the backup has failed or succeeded. 74 . The -r option specifies that the zip command should work recursively for directories i.Python en:Problem Solving We make use of the os and time modules by first importing them. we have created a script to take a backup of our important files! Note to Windows Users Instead of double backslash escape sequences. html#time. It will also have the . you can also use raw strings. Then. we finally run the command using the os. org/ dev/ 3. Using os. python. The time. This is called the operation phase or the deployment phase of the software. use 'C:\\Documents' or r'C:\Documents'. else it returns an error number. That's it. it will be '/' in Linux. it should include all the subdirectories and files. The -q option is used to indicate that the zip command should work quietly. Then. You can check if this command works by running it on the shell (Linux terminal or DOS prompt).e. The options are followed by the name of the zip archive to create followed by the list of files and directories to backup. Appropriately. Unix. The name of the zip archive that we are going to create is the current date and time which we find out using the time. etc. we can use it whenever we want to take a backup of the files.
source = ['"C:\\My Documents"'. ' '. today) # The name of the zip file target = today + os.using the time as the name of the file within a directory with the current date as a directory within the main backup directory. First advantage is that your backups are stored in a hierarchical manner and therefore it is much easier to manage. # 2. # 4.Python en:Problem Solving 75 Second Version The first version of our script works.strftime('%H%M%S') # Create the subdirectory if it isn't already there if not os.strftime('%Y%m%d') # The current time is the name of the zip archive now = time. Second advantage is that the length of the filenames are much shorter. #!/usr/bin/python # Filename: backup_ver2.sep + now + '.system(zip_command) == 0: print('Successful backup to'.exists(today): os.path. However. The files and directories to be backed up are specified in a list.sep + time.py import os import time # 1. 'C:\\Code'] # Notice we had to use double quotes inside the string for names with spaces in it. The backup must be stored in a main backup directory target_dir = 'E:\\Backup' # Remember to change this to what you will be using # 3.zip' # 5. The files are backed up into a zip file. Third advantage is that separate directories will help you to easily check if you have taken a backup for each day since the directory would be created only if you have taken a backup for that day. target) . The current day is the name of the subdirectory in the main directory today = target_dir + os.mkdir(today) # make directory print('Successfully created directory'. we can make some refinements to it so that it can work better on a daily basis. We use the zip command to put the files in a zip archive zip_command = "zip -qr {0} {1}". One of the refinements I felt was useful is a better file-naming mechanism .format(target.join(source)) # Run the backup if os. This is called the maintenance phase of the software.
please follow along because there's a lesson in here. I am finding it hard to differentiate what the backups were for! For example. 76 Third Version The second version works fine when I do many backups.py Successfully created directory E:\Backup\20080702 Successful backup to E:\Backup\20080702\202311.strftime('%H%M%S') .py Successful backup to E:\Backup\20080702\202325. The files and directories to be backed up are specified in a list. Note The following program does not work. The changes is that we check if there is a directory with the current day as name inside the main backup directory using the os.strftime('%Y%m%d') # The current time is the name of the zip archive now = time. # 4. but when there are lots of backups.path. I might have made some major changes to a program or presentation. then I want to associate what those changes are with the name of the zip archive.Python en:Problem Solving else: print('Backup FAILED') Output: $ python backup_ver2.exists function. #!/usr/bin/python # Filename: backup_ver3. This can be easily achieved by attaching a user-supplied comment to the name of the zip archive. we create it using the os. The current day is the name of the subdirectory in the main directory today = target_dir + os. # 2.sep + time. The backup must be stored in a main backup directory target_dir = 'E:\\Backup' # Remember to change this to what you will be using # 3. The files are backed up into a zip file. If it doesn't exist. 'C:\\Code'] # Notice we had to use double quotes inside the string for names with spaces in it.mkdir function. source = ['"C:\\My Documents"'.py import os import time # 1.zip How It Works: Most of the program remains the same.zip $ python backup_ver2. so do not be alarmed.
py File "backup_ver3. . So. On careful observation.join(source)) # Run the backup if os. ' '. This correction of the program when we find errors is called bug fixing.Python en:Problem Solving 77 # Take a comment from the user to create the name of the zip file comment = input('Enter a comment --> ') if len(comment) == 0: # check if a comment was entered target = today + os.zip' # Create the subdirectory if it isn't already there if not os.sep + now + '.py". We use the zip command to put the files in a zip archive zip_command = "zip -qr {0} {1}".path.mkdir(today) # make directory print('Successfully created directory'. it also tells us the place where it detected the error as well. we see that the single logical line has been split into two physical lines but we have not specified that these two physical lines belong together. target) else: print('Backup FAILED') Output: $ python backup_ver3.exists(today): os. '_') + '. line 25 target = today + os. So we start debugging our program from that line. Basically. Python has found the addition operator (+) without any operand in that logical line and hence it doesn't know how to continue.replace(' '. today) # 5.sep + now + '_' + comment. Remember that we can specify that the logical line continues in the next physical line by the use of a backslash at the end of the physical line.system(zip_command) == 0: print('Successful backup to'. we make this correction to our program.zip' else: target = today + os.sep + now + '_' + ^ SyntaxError: invalid syntax How This (does not) Work: This program does not work! Python says there is a syntax error which means that the script does not satisfy the structure that Python expects to see. When we observe the error given by Python.format(target.
zip' # Create the subdirectory if it isn't already there if not os. ' '. target) else: print('Backup FAILED') Output: . We use the zip command to put the files in a zip archive zip_command = "zip -qr {0} {1}".format(target. The files and directories to be backed up are specified in a list. '_') + '.strftime('%Y%m%d') # The current time is the name of the zip archive now = time.system(zip_command) == 0: print('Successful backup to'.path.sep + now + '_' + \ comment. # 2. 'C:\\Code'] # Notice we had to use double quotes inside the string for names with spaces in it. today) # 5.Python en:Problem Solving 78 Fourth Version #!/usr/bin/python # Filename: backup_ver4.mkdir(today) # make directory print('Successfully created directory'. The files are backed up into a zip file.join(source)) # Run the backup if os.py import os import time # 1. The current day is the name of the subdirectory in the main directory today = target_dir + os.replace(' '.zip' else: target = today + os. source = ['"C:\\My Documents"'. The backup must be stored in a main backup directory target_dir = 'E:\\Backup' # Remember to change this to what you will be using # 3.sep + now + '. # 4.strftime('%H%M%S') # Take a comment from the user to create the name of the zip file comment = input('Enter a comment --> ') if len(comment) == 0: # check if a comment was entered target = today + os.exists(today): os.sep + time.
then this is attached to the name of the zip archive just before the .zip $ python backup_ver4. so that the example is simple enough to be understood by everybody but real enough to be useful. html) module instead of the os.system call? .Python en:Problem Solving $ python backup_ver4. but there is always room for improvement. However. If the user has just pressed enter without entering anything (maybe it was just a routine backup or no special changes were made). Another possible enhancement would be to allow extra files and directories to be passed to the script at the command line. org/ dev/ 3. The most important refinement would be to not use the os. 0/ library/ zipfile.py Enter a comment --> added new examples Successful backup to E:\Backup\20080702\202836_added_new_examples.zip How It Works: This program now works! Let us go through the actual enhancements that we had made in version 3.system way of creating a backup in the above examples purely for pedagogical purposes.py Enter a comment --> Successful backup to E:\Backup\20080702\202839. python. I have been using the os. We take in the user's comments using the input function and then check if the user actually entered something by finding out the length of the input using the len function. then we proceed as we have done before. However. Can you try writing the fifth version that uses the zipfile (http:/ / docs. They are part of the standard library and available already for you to use without external dependencies on the zip program to be available on your computer.system way of creating archives and instead using the zipfile or tarfile built-in module to create these archives. if a comment was supplied. For example. Notice that we are replacing spaces in the comment with underscores . We can get these names from the sys.zip extension. 79 More Refinements The fourth version is a satisfactorily working script for most users.argv list and we can add them to our source list using the extend method provided by the list class.this is because managing filenames without spaces are much easier. you can include a verbosity level for the program where you can specify a -v option to make your program become more talkative.
2. swaroopch.Python en:Problem Solving 80 The Software Development Process We have now gone through the various phases in the process of writing a software. add any features that you want and continue to repeat the Do It-Test-Use cycle as many times as required. 5. Now. com/ mediawiki/ index. Software is grown. we will discuss object-oriented programming. not built. Start implementing with a simple version. You may find it useful to create your own program just like we did in this chapter so that you become comfortable with Python as well as problem-solving. Test and debug it. php? oldid=1395 Contributors: Swaroop. Remember. 3.. Previous Next Source: http:/ / www. These phases can be summarised as follows: 1. 4. 6. 3 anonymous edits . Next. Use it to ensure that it works as expected.
. but when writing large programs or have a problem that is better suited to this method. Note for Static Language Programmers Note that even integers are treated as objects (of the int class). This terminology is important because it helps us to differentiate between functions and variables which are independent and those which belong to a class or object. Classes and objects are the two main aspects of object oriented programming. but you do not give a value for this parameter when you call the method. Variables that belong to an object or class are referred to as fields.any reader of your program will immediately recognize it and even specialized IDEs (Integrated Development Environments) can help you if you use self. An analogy is that you can have variables of type int which translates to saying that variables that store integers are variables which are instances (objects) of the int class. C# and Java 1. we have designed our program around functions i. it is strongly recommended that you use the name self .any other name is definitely frowned upon. The self Class methods have only one specific difference from ordinary functions . There is another way of organizing your program which is to combine data and functionality and wrap it inside something called an object. A class is created using the class keyword.e.Python en:Object Oriented Programming 81 Python en:Object Oriented Programming Introduction In all the programs we wrote till now. Most of the time you can use procedural programming. See help(int) for more details on the class. Python will provide it.5) where integers are primitive native types. the fields and methods can be referred to as the attributes of that class.they can belong to each instance/object of the class or they can belong to the class itself. Such functions are called methods of the class. blocks of statements which manipulate data.they must have an extra first name that has to be added to the beginning of the parameter list. Collectively. you can use object oriented programming techniques. Objects can store data using ordinary variables that belong to the object. it is given the name self. Fields are of two types . A class creates a new type where objects are instances of the class. you can give any name for this parameter. Objects can also have functionality by using functions that belong to a class. This particular variable refers to the object itself. The fields and methods of the class are listed in an indented block. They are called instance variables and class variables respectively. This is called the procedure-oriented way of programming. There are many advantages to using a standard name .5 programmers will find this similar to the boxing and unboxing concept. This is called the object oriented programming paradigm. Although. and by convention. This is unlike C++ and Java (before version 1.
This is followed by an indented block of statements which form the body of the class. arg2). we create an object/instance of this class using the name of the class followed by a pair of parentheses.Person object at 0x019F85F0> How It Works: We create a new class using the class statement and the name of the class. this is automatically converted by Python into MyClass. Next. For our verification. we confirm the type of the variable by simply printing it. When you call a method of this object as myobject. 82 Classes The simplest class possible is shown in the following example.py class Person: pass # An empty block p = Person() print(p) Output: $ python simplestclass. It tells us that we have an instance of the Person class in the __main__ module. (We will learn more about instantiation in the next section).method(arg1. An example will make this clear.method(myobject. we have an empty block which is indicated using the pass statement. Say you have a class called MyClass and an instance of this class called myobject. The address will have a different value on your computer since Python can store the object wherever it finds space. You must be wondering how Python gives the value for self and why you don't need to give a value for it. arg1. arg2) . Notice that the address of the computer memory where your object is stored is also printed.the self. This also means that if you have a method which takes no arguments.Python en:Object Oriented Programming Note for C++/Java/C# Programmers The self in Python is equivalent to the this pointer in C++ and the this reference in Java and C#. . In this case.this is all the special self is about. #!/usr/bin/python # Filename: simplestclass. then you still have to have one argument .py <__main__.
sayHi() Output: $ python method. name): self. The __init__method There are many method names which have special significance in Python classes. how are you? How It Works: Here we see the self in action.Python en:Object Oriented Programming 83 Object Methods We have already discussed that classes/objects can have methods just like functions except that we have an extra self variable. We will see the significance of the __init__ method now.name) p = Person('Swaroop') p.name = name def sayHi(self): print('Hello. Notice the double underscores both at the beginning and at the end of the name. how are you?') p = Person() p. We will now see an example.sayHi() Output: .sayHi() # This short example can also be written as Person(). The __init__ method is run as soon as an object of a class is instantiated. #!/usr/bin/python # Filename: method.py class Person: def sayHi(self): print('Hello.sayHi() # This short example can also be written as Person('Swaroop'). Notice that the sayHi method takes no parameters but still has the self in the function definition. my name is'.py class Person: def __init__(self. Example: #!/usr/bin/python # Filename: class_init. The method is useful to do any initialization you want to do with your object. self.py Hello.
py class Robot: '''Represents a robot. we just create a new field also called name.''' # A class variable. The data part. we define the __init__ method as taking a parameter name (along with the usual self). we are able to use the self. There are two types of fields . Class variables are shared .name)) # When this person is created. name): '''Initializes the data. that change will be seen by all the other instances. fields.format(self. my name is Swaroop How It Works: Here. Now.population += 1 .e. 84 Class And Object Variables We have already discussed the functionality part of classes and objects (i. methods).name field in our methods which is demonstrated in the sayHi method. The dotted notation allows us to differentiate between them. i. they are not shared and are not related in any way to the field by the same name in a different instance.e.py Hello. This is the special significance of this method. are nothing but ordinary variables that are bound to the namespaces of the classes and objects.e. counting the number of robots population = 0 def __init__(self.''' self. Notice these are two different variables even though they are both called 'name'..Python en:Object Oriented Programming $ python class_init. That's why they are called name spaces. Most importantly. Object variables are owned by each individual object/instance of the class. In this case. the robot # adds to the population Robot. each object has its own copy of the field i.name = name print('(Initializing {0})'.they can be accessed by all instances of that class. An example will make this easy to understand: #!/usr/bin/python # Filename: objvar. Here. with a name. now let us learn about the data part. This means that these names are valid within the context of these classes and objects only.class variables and object variables which are classified depending on whether the class or the object owns the variables respectively.
\n") print("Robots have finished their work. my masters call me C-3PO.format(Robot.''' print('Greetings.population -= 1 if Robot.howMany() droid2 = Robot('C-3PO') droid2.sayHi() Robot. We have 1 robots.sayHi() Robot.'.format(self.format(self. my masters call me R2-D2.howMany() print("\nRobots can do some work here.population)) def sayHi(self): '''Greeting by the robot. they can do that. We have 2 robots.population == 0: print('{0} was the last one.Python en:Object Oriented Programming 85 def __del__(self): '''I am dying.name)) Robot.") del droid1 del droid2 Robot. my masters call me {0}.name)) def howMany(): '''Prints the current population.howMany() Output: (Initializing R2-D2) Greetings.'.name)) else: print('There are still {0:d} robots working. Yeah.''' print('We have {0:d} robots.''' print('{0} is being destroyed!'.format(self.format(Robot.population)) howMany = staticmethod(howMany) droid1 = Robot('R2-D2') droid1. (Initializing C-3PO) Greetings.'.'. . So let's destroy them.
population)) Decorators can be imagined to be a shortcut to calling an explicit statement. com/ developerworks/ linux/ library/ l-cpdecor.population count by 1. Thus. Remember. Observe that the __init__ method is used to initialize the Robot instance with a name. we increase the population count by 1 since we have one more robot being added. we refer to the population class variable as Robot. html): @staticmethod def howMany(): '''Prints the current population.__doc__ Just like the __init__ method.Python en:Object Oriented Programming 86 Robots can do some work here. C-3PO is being destroyed! C-3PO was the last one.name notation in the methods of that object. Here. In this program. This is called an attribute reference. Also observe that the values of self. We could have also achieved the same using decorators (http:/ / www. Remember this simple difference between class and object variables. that you must refer to the variables and methods of the same object using the self only. there is another special method __del__ which is called when an object is going to die i. it is no longer being used and is being returned to the computer system for reusing that piece of memory.''' print('We have {0:d} robots.'. we will go for staticmethod. We can access the class docstring at runtime using Robot.population. . ibm. R2-D2 is being destroyed! There are still 1 robots working.population and not as self.format(Robot. In this method.sayHi. We refer to the object variable name using self.__doc__ and the method docstring as Robot. as we have seen in this example. We have 0 robots. Also note that an object variable with the same name as a class variable will hide the class variable! The howMany is actually a method that belongs to the class and not to the object. How It Works: This is a long example but helps demonstrate the nature of class and object variables. we simply decrease the Robot. Since we don't need such information. we also see the use of docstrings for classes as well as methods. This means we can define it as either a classmethod or a staticmethod depending on whether we need to know which class we are part of.name is specific to each object which indicates the nature of object variables. The name variable belongs to the object (it is assigned using self) and hence is an object variable. In this method.e. Robots have finished their work. So let's destroy them. population belongs to the Robot class and hence is a class variable.
this is automatically reflected in the subtypes as well. Thus. The Teacher and Student classes are called the derived classes or subclasses. If you want to explicitly see it in action. Also observe that we reuse the code of the parent class and we do not need to repeat it in the different classes as we would have had to in case we had used independent classes. Inheritance can be best imagined as implementing a type and subtype relationship between classes. marks and fees for students. If we add/change any functionality in SchoolMember. A better way would be to create a common class called SchoolMember and then have the teacher and student classes inherit from this class i. Remember that this is only a convention and is not enforced by Python (except for the double underscore prefix). changes in the subtypes do not affect other subtypes. We will now see this example as a program. Python uses name-mangling to effectively make it a private variable. courses and leaves for teachers and.py . age and address. The SchoolMember class in this situation is known as the base class or the superclass. One exception: If you use data members with names using the double underscore prefix such as __privatevar.. They have some common characteristics such as name. they will become sub-types of this type (class) and then we can add specific characteristics to these sub-types. #!/usr/bin/python # Filename: inherit.e.e. you can add a new ID card field for both teachers and students by simply adding it to the SchoolMember class. Note for C++/Java/C# Programmers All class members (including the data members) are public and all the methods are virtual in Python.. You can create two independent classes for each type and process them but adding a new common characteristic would mean adding to both of these independent classes. the object can be treated as an instance of the parent class. However. For example.Python en:Object Oriented Programming The __del__ method is run when the object is no longer in use and there is no guarantee when that method will be run. Suppose you want to write a program which has to keep track of the teachers and students in a college. 87 Inheritance One of the major benefits of object oriented programming is reuse of code and one of the ways this is achieved is through the inheritance mechanism. This quickly becomes unwieldy. There are many advantages to this approach. They also have specific characteristics such as salary.
40. age) self.__init__(self.age). Shrividya'.format(self.age = age print('(Initialized SchoolMember: {0})'.''' def __init__(self. age) self.salary = salary print('(Initialized Teacher: {0})'. s] for member in members: member.name.tell(self) print('Salary: "{0:d}"'.name)) def tell(self): SchoolMember.salary)) class Student(SchoolMember): '''Represents a student.format(self.marks)) t = Teacher('Mrs. name. 30000) s = Student('Swaroop'.format(self.py (Initialized SchoolMember: Mrs. 25. salary): SchoolMember.''' print('Name:"{0}" Age:"{1}"'.''' def __init__(self.Python en:Object Oriented Programming 88 class SchoolMember: '''Represents any school member.format(self.tell() # works for both Teachers and Students Output: $ python inherit. name. name. age. 75) print() # prints a blank line members = [t.name)) def tell(self): SchoolMember.tell(self) print('Marks: "{0:d}"'.''' def __init__(self.format(self.name)) def tell(self): '''Tell my details. age.__init__(self.name = name self. name. end=" ") class Teacher(SchoolMember): '''Represents a teacher.marks = marks print('(Initialized Student: {0})'. marks): SchoolMember.format(self. Shrividya) . self. age): self. name.
if more than one class is listed in the inheritance tuple. We have also seen the benefits and pitfalls of object-oriented programming. Python is highly object-oriented and understanding these concepts carefully will help you a lot in the long run. it starts looking at the methods belonging to its base classes one by one in the order they are specified in the tuple in the class definition. Shrividya) (Initialized SchoolMember: Swaroop) (Initialized Student: Swaroop) Name:"Mrs. If it could not find the method.Python en:Object Oriented Programming (Initialized Teacher: Mrs. we observe that the __init__ method of the base class is explicitly called using the self variable so that we can initialize the base class part of the object. A note on terminology . One way to understand this is that Python always starts looking for methods in the actual type. Next. we will learn how to deal with input/output and how to access files in Python.Python does not automatically call the constructor of the base class. observe that the tell method of the subtype is called and not the tell method of the SchoolMember class. swaroopch. This is very important to remember . you have to explicitly call it yourself. php? oldid=2359 Contributors: Horstjens. Swaroop. we specify the base class names in a tuple following the class name in the class definition. Previous Next Source: http:/ / www.. then it is called multiple inheritance. Next. Also. com/ mediawiki/ index. which in this case it does. 89 Summary We have now explored the various aspects of classes and objects as well as the various terminologies associated with it. We also observe that we can call methods of the base class by prefixing the class name to the method call and then pass in the self variable along with any arguments. 6 anonymous edits .
The ability to create. We've already seen how we can make slices from sequences using the seq[a:b] code starting from position a to position b. it is a palindrome $ python user_input. you would want to take input from the user and then print some results back. it is not a palindrome") Output: $ python user_input. it is a palindrome How It Works: We use the slicing feature to reverse the text.py Enter text: sir No.Python en:Input Output 90 Python en:Input Output Introduction There will be situations where your program has to interact with the user. Input from user #!/usr/bin/python # user_input. we can also use the various methods of the str (string) class. it is not a palindrome $ python user_input. We can achieve this using the input() and print() functions respectively. it is a palindrome") else: print("No.py def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) something = input('Enter text: ') if (is_palindrome(something)): print("Yes.py Enter text: racecar Yes. you can use the rjust method to get a string which is right justified to a specified width. See help(str) for more details. For output. read and write files is essential to many programs and we will explore this aspect in this chapter. For example. We can also provide a third argument that determines the step by which the slicing is done. The . Another common type of input/output is dealing with files.py Enter text: madam Yes. For example.
readline() if len(line) == 0: # Zero length indicates EOF break print(line. For example. readline or write methods appropriately to read from or write to the file. when you are finished with the file. Then finally.txt'.e.txt') # if no mode is specified. -1 will return the text in reverse. 'w') # open for 'w'riting f. wiktionary. Example: #!/usr/bin/python # Filename: using_file. Giving a negative step. i. We take that text and reverse it.close() # close the file f = open('poem. spaces and case. the input() function will then return that text. If the original text and reversed text are equal. Homework exercise: Checking whether a text is a palindrome should also ignore punctuation. The ability to read or write to the file depends on the mode you have specified for the file opening. Then it waits for the user to type something and press the return key. org/ wiki/ palindrome). "Rise to vote. The input() function takes a string as argument and displays it to the user.write(poem) # write text to file f. you call the close method to tell Python that we are done using the file.py Programming is fun . Once the user has entered.. 'r'ead mode is assumed by default while True: line = f." is also a palindrome but our current program doesn't say it is.Python en:Input Output default step is 1 because of which it returns a continuous part of the text. end='') f. sir. then the text is a palindrome (http:/ / en.close() # close the file Output: $ python using_file.
Example: #!/usr/bin/python # Filename: pickling. Now. Next. When an empty string is returned. 'wb') pickle. We don't need to specify a mode because 'read text file' is the default mode. This is called storing the object persistently. we finally close the file.data' # the list of things to buy shoplist = ['apple'. write mode ('w') or append mode ('a'). We read in each line of the file using the readline method in a loop.close() del shoplist # destroy the shoplist variable # Read back from the storage . The mode can be a read mode ('r'). open() considers the file to be a 't'ext file and opens it in 'r'ead mode. Then. it means that we have reached the end of the file and we 'break' out of the loop. In our example. We are suppressing the newline by specifying end='' because the line that is read from the file already ends with a newline character. the print() function prints the text as well as an automatic newline to the screen.Python en:Input Output When the work is done if you wanna make your work also fun: use Python! How It Works: First. we first open the file in write text mode and use the write method of the file object to write to the file and then we finally close the file. f) # dump the object to a file f. This method returns a complete line including the newline character at the end of the line. 'mango'. There are actually many more modes available and help(open) will give you more details about them. We can also by dealing with a text file ('t') or a binary file ('b'). open a file by using the built-in open function and specifying the name of the file and the mode in which we want to open the file. we open the same file again for reading.dump(shoplist. By deafult. 92 Pickle Python provides a standard module called pickle using which you can store any Python object in a file and then get it back later. 'carrot'] # Write to the file f = open(shoplistfile.txt file to confirm that the program has indeed written and read from that file. check the contents of the poem. By default.py import pickle # the name of the file where we will store the object shoplistfile = 'shoplist.
Swaroop. in <module> Print('Hello World') NameError: name 'Print' is not defined >>> print('Hello World') Hello World . com/ mediawiki/ index. Python raises a syntax error. >>> Print('Hello World') Traceback (most recent call last): File "<pyshell#0>". 'mango'. This process is called unpickling. we have to first open the file in 'w'rite 'b'inary mode and then call the dump function of the pickle module. In this case.load(f) # load the object from the file print(storedlist) Output: $ python pickling. line 1.Python en:Input Output f = open(shoplistfile. Next. we will explore the concept of exceptions. Errors Consider a simple print function call. What if we misspelt print as Print? Note the capitalization. 93 Summary We have discussed various types of input/output and also file handling and using the pickle module. what if you are going to read a file and the file does not exist? Or what if you accidentally deleted it when the program was running? Such situations are handled using exceptions. 'carrot'] How It Works: To store an object in a file. 'rb') storedlist = pickle. swaroopch. 1 anonymous edits Python en:Exceptions Introduction Exceptions occur when certain exceptional situations occur in your program. what if your program had some invalid statements? This is handled by Python which raises its hands and tells you there is an error. php? oldid=1583 Contributors: Horstjens. Next. For example. This process is called pickling. we retrieve the object using the load function of the pickle module which returns the object. Previous Next Source: http:/ / ['apple'. Similarly.
The except . in <module> s = input('Enter something --> ') EOFError: EOF when reading a line Python raises an error called EOFError which basically means it found an end of file symbol (which is represented by ctrl-d) when it did not expect to see it.Python en:Exceptions Observe that a NameError is raised and also the location where the error was detected is printed. 94 Exceptions We will try to read input from the user.. $ python try_except.py try: text = input('Enter something --> ') except EOFError: print('Why did you do an EOF on me?') except KeyboardInterrupt: print('You cancelled the operation. >>> s = input('Enter something --> ') Enter something --> Traceback (most recent call last): File "<pyshell#2>".py Enter something --> # Press ctrl-d Why did you do an EOF on me? $ python try_except.') else: print('You entered {0}'.format(text)) Output: $ python try_except.py Enter something --> no exceptions You entered no exceptions How It Works: We put all the statements that might raise exceptions/errors inside the try block and then put handlers for the appropriate errors/exceptions in the except clause/block. #!/usr/bin/python # Filename: try_except.except statement. Handling Exceptions We can handle exceptions using the try. This is what an error handler for this error does.py Enter something --> # Press ctrl-c You cancelled the operation. We basically put our usual statements within the try-block and put all our error handlers in the except-block. Press ctrl-d and see what happens. line 1.
except block. atleast): Exception. We have already seen this in action above.length = length self. it will handle all errors and exceptions. length.py Enter something --> a .atleast = atleast try: text = input('Enter something --> ') if len(text) < 3: raise ShortInputException(len(text).. we will also see how to get the exception object so that we can retrieve additional information. then the default Python handler is called which just stops the execution of the program and prints an error message. #!/usr/bin/python # Filename: raising. You can also have an else clause associated with a try.__init__(self) self. If no names of errors or exceptions are supplied. what's the point of having a try block? If any error or exception is not handled. 3) # Other work can continue as usual here except EOFError: print('Why did you do an EOF on me?') except ShortInputException as ex: print('ShortInputException: The input was {0} long. The else clause is executed if no exception occurs.') Output: $ python raising. 95 Raising Exceptions You can raise exceptions using the raise statement by providing the name of the error/exception and the exception object that is to be thrown. ex. or a parenthesized list of errors/exceptions. The error or exception that you can arise should be class which directly or indirectly must be a derived class of the Exception class.Python en:Exceptions clause can handle a single specified error or exception. Otherwise.py class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self.atleast)) else: print('No exception was raised.format(ex. expected at least {1}'\ . In the next example. Note that there has to be at least one except clause associated with every try clause.length.
It has two fields . How It Works: Here. Within this particular except clause.py Enter something --> abc No exception was raised.length which is the length of the given input. This new exception type is called ShortInputException. expected at least 3 $ python raising.sleep(2) # To make sure it runs for a while except KeyboardInterrupt: print('!! You cancelled the reading from the file.txt') while True: # our usual file-reading idiom line = f.') finally: f.close() print('(Cleaning up: Closed the file)') Output: $ python finally. Note that you can use an except clause along with a finally block for the same corresponding try block. This is analogous to parameters and arguments in a function call. .py Programming is fun When the work is done if you wanna make your work also fun: !! You cancelled the reading from the file. we are creating our own exception type. end='') time. we mention the class of error which will be stored as the variable name to hold the corresponding error/exception object. and atleast which is the minimum length that the program was expecting. In the except clause.. How do you ensure that the file object is closed properly whether or not an exception was raised? This can be done using the finally block.Python en:Exceptions ShortInputException: The input was 1 long. 96 Try . we use the length and atleast fields of the exception object to print an appropriate message to the user. #!/usr/bin/python # Filename: finally. You will have to embed one within another if you want to use both.readline() if len(line) == 0: break print(line.Finally Suppose you are reading a file in your program.py import time try: f = open('poem.
org/ dev/ peps/ pep-0343/ ) for comprehensive explanation.finally statements repeatedly. Next..__exit__ after finishing the block of code.we leave the closing of the file to be done automatically by with open. before the program exits. It always calls the thefile.. It fetches the object returned by the open statement. let's call it "thefile" in this case.. php? oldid=1470 Contributors: Swaroop. there is also a with statement that enables this to be done in a clean manner: #!/usr/bin/python # Filename: using_with. Hence. we will explore the Python Standard Library. When the program is still running. 2 anonymous edits . Previous Next Source: http:/ / www. the finally clause is executed and the file object is always closed. This is what helps us to avoid having to use explicit try. but we have arbitrarily introduced sleeping for 2 seconds after printing each line using the time. We have seen how to create our own exception types and how to raise exceptions as well. So the code that we would have written in a finally block is should be taken care of automatically by the __exit__ method.__enter__ function before starting the block of code under it and always calls thefile. end='') How It Works: The output should be same as the previous example.Python en:Exceptions (Cleaning up: Closed the file) How It Works: We do the usual file-reading stuff. However. Observe that the KeyboardInterrupt exception is thrown and the program quits. The difference here is that we are using the open function with the with statement . 97 The with statement Acquiring a resource in the try block and subsequently releasing the resource in the finally block is a common pattern. Summary We have discussed the usage of the try.except and try. More discussion on this topic is beyond scope of this book. press ctrl-c to interrupt/cancel the program. com/ mediawiki/ index. swaroopch. What happens behind the scenes is that there is a protocol used by the with statement. python.txt") as f: for line in f: print(line. so please refer PEP 343 (http:/ / statements.sleep function so that the program runs slowly (Python is very fast by nature).py with open("poem.
py import sys. We have already seen that the sys. you may skip this chapter. 0. 0. ensure the program runs only under Python 3. warnings if sys. say.0 for this program to run". However.warn("Need Python 3. 'beta'. 2) >>> sys. You can find complete details for all of the modules in the Python Standard Library in the 'Library Reference' section (http:/ / docs. We will explore some of the commonly used modules in this library.version_info[0] >= 3 True How It Works: The sys module has a version_info tuple that gives us the version information. I highly recommend coming back to this chapter when you are more comfortable with programming using Python. We can check this to. sys module The sys module contains system-specific functionality. org/ dev/ 3. The sys module gives us such functionality.version_info (3.Python en:Standard Library 98 Python en:Standard Library Introduction The Python Standard Library contains a huge number of useful modules and is part of every standard Python installation.version_info[0] < 3: warnings. RuntimeWarning) else: print('Proceed as normal') Output: . Suppose we want to check the version of the Python command being used so that. It is important to become familiar with the Python Standard Library since many problems can be solved quickly if you are familiar with the range of things that these libraries can do. Let us explore a few useful modules. python.argv list contains the command-line arguments. The first entry is the major version. for example. Note If you find the topics in this chapter too advanced. >>> import sys >>> sys.0: #!/usr/bin/python # Filename: versioncheck. we want to ensure that we are using at least version 3. 0/ library/ ) of the documentation that comes with your Python installation.
233 : DEBUG : Start of the program 2008-09-03 13:18:16.info("Doing something") logging.getenv('HOMEPATH').basicConfig( level=logging.log.py versioncheck.233 : INFO : Doing something 2008-09-03 13:18:16.startswith('Windows'): logging_file = os.path.path.0 for this program to run RuntimeWarning) $ python3 versioncheck.join(os. #!/usr/bin/python # Filename: use_logging. filename = logging_file.py Logging to C:\Users\swaroop\test.py import os.platform().getenv('HOMEDRIVE').py Proceed as normal How It Works: We use another module from the standard library called warnings that is used to display warnings to the end-user.join(os. format='%(asctime)s : %(levelname)s : %(message)s'.. ) logging.DEBUG.5 versioncheck. platform.log') logging.getenv('HOME'). 'test.warning("Dying now") Output: $python use_logging. filemode = 'w'. 'test. we display a corresponding warning.log') else: logging_file = os.py:6: RuntimeWarning: Need Python 3. If the Python version number is not at least 3. os.233 : WARNING : Dying now .debug("Start of the program") logging. logging if platform. it will look something like this: 2008-09-03 13:18:16.Python en:Standard Library $ python2.log If we check the contents of test.
the os module for interacting with the operating system.py import sys if sys..path. First. This can be achieved using a few modules. information. First is the urllib module that we can use to fetch any webpage from the internet.0') import json import urllib. The reason to use a special function rather than just adding the strings together is because this function will ensure the full location matches the format expected by the operating system.e. we figure out the home drive. TODO This program doesn't work yet which seems to be a bug in Python 3.lBSfPhwr' SEARCH_BASE = '('This program needs Python 3. 100 urllib and json modules How much fun would it be if we could write our own program that will get search results from the web? Let us explore that now.0 beta 2 (http:/ / bugs. Once the program has run. #!/usr/bin/python # Filename: yahoo_search. org/ issue3763). we can put messages that are either meant for debugging. we check which operating system we are using by checking the string returned by platform.platform() (for more information. We configure the logging module to write all the messages in a particular format to the file we have specified. urllib. urllib. the operating system and the logging module to log information. even though no information was displayed to the user running the program. we can check this file and we will know what happened in the program. the home folder and the filename where we want to store the information. We use the os.com/wsregapp/ YAHOO_APP_ID = 'jl22psvV34HELWhdfUJbfDQzlJ2B57KFS_qs4I8D0Wz5U5_yCI1Awv8.response # Get your own APP ID at[0] != 3: sys. help(platform)).parse. Finally. python.Python en:Standard Library How It Works: We use three modules from the standard library . For other platforms. Putting these three parts together. If it is Windows.com/WebSearchService/V1/webSearch' .join() function to put these three parts of the location together. warning or even critical messages. we get the full location of the file. the platform module for information about the platform i. urllib.request.yahooapis.yahoo. see import platform.
parse. results=20. result['Url'])) Output: TODO How It Works: We can get the search results from a particular website by giving the text we are searching for in a particular format.urlencode(kwargs) result = json.Python en:Standard Library 101 class YahooSearchError(Exception): pass # Taken from. We then loop through these results and display it to the end-user. and we are asking for the output in JSON format.parse.urlopen(url)) if 'Error' in result: raise YahooSearchError(result['Error']) return result['ResultSet'] query = input('What do you want to search for? ') for result in search(query)['Result']: print("{0} : {1}". So for example.. 'output': 'json' }) url = SEARCH_BASE + '?' + urllib.load(urllib. 'results': results.yahoo. 'query': query.request.format(result['Title']. .load() which will read the content and simultaneously convert it to a Python object. start=1.update({ 'appid': YAHOO_APP_ID. We have to specify many options which we combine using key1=value1&key2=value2 format which is handled by the urllib. lBSfPhwr& results=20& start=1& output=json) and you will see 20 results. starting from the first result. for the words "byte of python". **kwargs): kwargs.html def search(query. We make a connection to this URL using the urllib. 'start': start. open this link in your web browser (http:/ / search.urlencode() function.request.urlopen() function and pass that file handle to json. yahooapis.
html). >>> errnum. Summary We have explored some of the functionality of many modules in the Python Standard Library. 2 anonymous edits Python en:More Introduction So far we have covered majority of the various aspects of Python that you will use. return (2.. com/ projects/ PyMOTW/ ) series. b = <some expression> interprets the result of the expression as a tuple with two values. org/ regular_expressions/ index. org/ dev/ library/ pdb. python. If you want to interpret the results as (a. then you just need to star it just like you would in function parameters: .. we will cover various aspects of Python that will make our tour of Python more complete. 0/ library/ getopt. Next. Previous Next Source: http:/ / www. 'second error details') . errstr = get_error_details() >>> errnum 2 >>> errstr 'second error details' Notice that the usage of a. >>> def get_error_details(): .. 0/ library/ ) to get an idea of all the modules that are available.. org/ dev/ 3. <everything else>). html) and so on. python. It is highly recommended to browse through the Python Standard Library documentation (http:/ / docs. doughellmann.Python en:Standard Library 102 Module of the Week Series There is much more to be explored in the standard library such as debugging (http:/ / docs. php? oldid=1156 Contributors: Swaroop. com/ mediawiki/ index. diveintopython. html). we will cover some more aspects that will make our knowledge of Python more well-rounded. In this chapter. Passing tuples around Ever wished you could return two different values from a function? You can. All you have to do is use a tuple. The best way to further explore the standard library is to read Doug Hellmann's excellent Python Module of the Week (http:/ / www. python. handling command line options (http:/ / docs. swaroopch. regular expressions (http:/ / www. org/ dev/ 3.
python. org/ dev/ 3. there are special methods for all the operators (+. Special methods are used to mimic certain behaviors of built-in types. Name __init__(self. If you think about it.. except for error checking. etc. 4] 103 This also means the fastest way to swap two variables in Python is: >>> >>> >>> (8. I strongly recommend avoiding this short-cut method. *b = [1. key) __len__(self) Single Statement Blocks We have seen that each block of statements is set apart from the rest by its own indentation level. mainly because it will be much easier to add an extra . 3. if you want to use the x[key] indexing operation for your class (just like you use it for lists and tuples). a. If you want to know about all the special methods. then you can specify it on the same line of. 0/ reference/ datamodel. Similarly. a = 5. b 5) Special Methods There are certain methods such as the __init__ and __del__ methods which have special significance in classes. Yes Notice that the single statement is used in-place and not as a separate block. b = 8 a.) Called when x[key] indexing operation is used. For example. there is one caveat. Called when the built-in len() function is used for the sequence object.... a conditional statement or looping statement. Well. >. then all you have to do is implement the __getitem__() method and your job is done. . Called when the less than operator (<) is used. If your block of statements contains only one single statement.Python en:More >>> >>> 1 >>> [2. see the manual (http:/ / docs. html#special-method-names). 2. other) Explanation This method is called just before the newly created object is returned for usage. 4] a b 3. this is what Python does for the list class itself! Some useful special methods are listed in the following table. b = b. a a. Although. The following example should make this clear: >>> flag = True >>> if flag: print 'Yes' . Called just before the object is destroyed Called when we use the print function or when str() is used. __getitem__(self.) __del__(self) __str__(self) __lt__(self. say. you can use this for making your program smaller.
Python en:More statement if you are using proper indentation. 3. TODO Can we do a list. Suppose you have a list of numbers and you want to get a corresponding list with all the numbers multiplied by 2 only when the number itself is greater than 2. #!/usr/bin/python # Filename: list_comprehension.py wordword 10 How It Works: Here. 104 Lambda Forms A lambda statement is used to create new function objects and then return them at runtime. #!/usr/bin/python # Filename: lambda. A lambda statement is used to create the function object. { 'x' : 4. b['x'])) List Comprehension List comprehensions are used to derive a new list from an existing list. b : cmp(a['x']. 'y' : 3 }. only expressions. we use a function make_repeater to create new function objects at runtime and return it.sort() by providing a compare function created using lambda? points = [ { 'x' : 2. List comprehensions are ideal for such situations. Essentially.py def make_repeater(n): return lambda s: s * n twice = make_repeater(2) print(twice('word')) print(twice(5)) Output: $ python lambda.py listone = [2. 'y' : 1 } ] # points. Note that even a print statement cannot be used inside a lambda form.sort(lambda a. 4] listtwo = [2*i for i in listone if i > 2] print(listtwo) Output: . the lambda takes a parameter followed by a single expression only which becomes the body of the function and the value of this expression is returned by the new function.
If a ** prefix had been used instead.. >>> def powersum(power... >>> eval('2*3') 6 . >>> powersum(2. the extra parameters would be considered to be key/value pairs of a dictionary. we can generate a string containing Python code at runtime and then execute these statements using the exec statement: >>> exec('print("Hello World")') Hello World Similarly. return total .. the eval function is used to evaluate valid Python expressions which are stored in a string. as opposed to written in the program itself.. This is useful when taking variable number of arguments in the function. power) . for i in args: . 10) 100 Because we have a * prefix on the args variable.. 4) 25 >>> powersum(2. exec and eval The exec function is used to execute Python statements which are stored in a string or file.. 8] How It Works: Here.''' . For example.. 105 Receiving Tuples and Lists in Functions There is a special way of receiving parameters to a function as a tuple or a dictionary using the * or ** prefix respectively. A simple example is shown below. we derive a new list by specifying the manipulation to be done (2*i) when some condition is satisfied (if i > 2).. 3. Note that the original list remains unmodified.py [6. *args): .. '''Return the sum of each argument raised to specified power.... total = 0 .Python en:More $ python list_comprehension.
an AssertionError is raised. Summary We have covered some more features of Python in this chapter and yet we haven't covered all the features of Python. we will discuss how to explore Python further. the repr function is used to obtain a printable representation of the object.Python en:More 106 The assert statement The assert statement is used to assert that something is true. we have covered most of what you are ever going to use in practice. . The interesting part is that you will have eval(repr(object)) == object most of the time. line AssertionError >= 1 >= 1 call last): 1. The repr function The repr function is used to obtain a canonical string representation of the object. then assert statement is ideal in this situation. This is sufficient for you to get started with whatever programs you are going to create. When the assert statement fails. For example.append('item') >>> repr(i) "['item']" >>> eval(repr(i)) ['item'] >>> eval(repr(i)) == i True Basically. if you are very sure that you will have at least one element in a list you are using and want to check this. either handle the problem or display an error message to the user and then quit. You can control what your classes return for the repr function by defining the __repr__ method in your class. However. in <module> The assert statement should be used judiciously. >>> i = [] >>> i. >>> mylist = ['item'] >>> assert len(mylist) >>> mylist. it is better to catch exceptions. Next. and raise an error if it is not true. Most of the time.pop() 'item' >>> mylist [] >>> assert len(mylist) Traceback (most recent File "<stdin>". at this stage.
Use the dictionary built-in methods to add. php? oldid=1463 Contributors: Swaroop. delete and modify the persons. ed. com/ contact/ ) thanking me for this great book . contributing improvements or volunteering translations to support the continued development of this book. Once you are able to do this. then you must have become comfortable and familiar with Python. The replace command can be as simple or as sophisticated as you wish. If you found that program easy. Use a dictionary to store person objects with their name as the key.-) . Details must be stored for later retrieval. then here's a hint. you should. from simple string substitution to looking for patterns (regular expressions). This step is optional but recommended. delete or search for your contacts such as friends. This is fairly easy if you think about it in terms of all the various stuff that we have come across till now. please consider making a donation. The question now is 'What Next?'. here's another one: Implement the replace command (http:/ / unixhelp. I would suggest that you tackle this problem: Create your own command-line address-book program using which you can browse. swaroopch. here are some ways to continue your journey with Python: . 1 anonymous edits Python en:What Next If you have read this book thoroughly till now and practiced writing a lot of programs. uk/ CGI/ man-cgi?replace). swaroopch.Python en:More 107 Previous Next Source: http:/ / www. ac. com/ mediawiki/ index. immediately send me a mail (http:/ / www. Now. Also. This command will replace one string with another in the list of files provided. After that. If you still want directions on how to proceed. If you have not done it already. modify. add. Use the pickle module to store the objects persistently on your hard disk. family and colleagues and their information such as email address and/or phone number. You have probably created some Python programs to try out stuff and to exercise your Python skills as well. Hint (Don't read) Create a class to represent the person's information. you can claim to be a Python programmer.
htm) • Python Cookbook (http:/ / code. html) • Python Interview Q & A (http:/ / dev. python. html) • Rosetta code repository (http:/ / www. Tutorials. web services. Other useful resources are: • ShowMeDo videos for Python (http:/ / showmedo. org) book which you can read fully online as well. fyicenter. net/ pleac_python/ index. net/ article/ 52) • Advanced Software Carpentry using Python (http:/ / ivory. org/ doc/ faq/ general/ ) • Norvig's list of Infrequently Asked Questions (http:/ / norvig. cx/ publish/ tech_index_cp. idyll. org/ zone/ ) • Links at the end of every Python-URL! email (http:/ / groups. com/ videos/ python) • GoogleTechTalks videos on Python (http:/ / youtube. Books. siafoo. etc. org/ wiki/ Category:Python) • Python examples at java2s (http:/ / www. XML processing. html) • Official Python FAQ (http:/ / www. html) is an excellent series of Python-related articles by David Mertz.Python en:What Next 108 Example Code The best way to learn a programming language is to write a lot of code and read a lot of code: • The PLEAC project (http:/ / pleac. unit testing. org/ dev/ howto/ doanddont. stackoverflow. lang. com/ tutorials. org/ articles/ advanced-swc/ ) • Charming Python (http:/ / gnosis. Questions and Answers • Official Python Dos and Don'ts (http:/ / docs. com/ Interview-Questions/ Python/ index. sourceforge. announce/ t/ 37de95ef0326293d) • Python Papers (http:/ / pythonpapers. com/ questions/ tagged/ python) Tips and Tricks • Python Tips & Tricks (http:/ / www. in detail. This is a must-read for every Python user. com/ group/ comp. html) • The Effbot's Python Zone (http:/ / effbot. Papers. com/ python-iaq. activestate. html) • StackOverflow questions tagged with python (http:/ / beta. python. java2s. rosettacode. google. Videos The logical next step after this book is to read Mark Pilgrim's awesome Dive Into Python (http:/ / www. The Dive Into Python book explores topics such as regular expressions. org) . com/ results?search_query=googletechtalks+ python) • Awaretek's comprehensive list of Python tutorials (http:/ / www. awaretek. com/ Code/ Python/ CatalogPython. com/ recipes/ langs/ python/ ) is an extremely valuable collection of recipes or tips on how to solve certain kinds of problems using Python. python. diveintopython.
com/ DevCenter/ EasyInstall#using-easy-install). html). Graphical Software Suppose you want to create your own graphical programs using Python. org/ tutorial. python.python discussion group (http:/ / groups. telecommunity. Bindings are what allow you to write programs in Python and use the libraries which are themselves written in C or C++ or other languages. Installing libraries There are a huge number of open source libraries at the Python Package Index (http:/ / pypi.lang. Qt is extremely easy to use and very powerful especially due to the Qt Designer and the amazing Qt documentation. Make sure you do your homework and have tried solving the problem yourself first. python. There are lots of choices for GUI using Python: PyQt This is the Python binding for the Qt toolkit which is the foundation upon which the KDE is built. qtrac. python/ topics) is the best place to ask your question. then follow the Official Python Planet (http:/ / planet. Eby's excellent EasyInstall tool (http:/ / peak. wxPython This is the Python bindings for the wxWidgets toolkit. pycs. com/ group/ comp. you can use Philip J. it is very portable and runs on Linux. lang. Starting with Qt 4. org). You can create both free as well as proprietary software using GTK+. read the PyQt tutorial (http:/ / zetcode. then the comp. org) and/or the Unofficial Python Planet (http:/ / www. com/ tutorials/ pyqt4/ ) or the PyQt book (http:/ / www. To get started. To install and use these libraries.Python en:What Next 109 Discussion If you are stuck with a Python problem. Windows. google. The Glade graphical interface designer is indispensable. There are many IDEs available for wxPython which include GUI designers as well such as SPE (Stani's Python Editor) (http:/ / spe. News If you want to learn what is the latest in the world of Python. read the PyGTK tutorial (http:/ / www. html). wxPython has a learning curve associated with it. eu/ pyqtbook. pygtk. To get started. GTK+ works well on Linux but its port to Windows is incomplete. GTK+ has many quirks in usage but once you become comfortable. org/ pypi) which you can use in your own programs. PyGTK This is the Python binding for the GTK+ toolkit which is the foundation upon which GNOME is built. Mac and even embedded platforms. However. planetpython. net/ ) and . you can create GUI apps fast. PyQt is free if you want to create open source (GPL'ed) software and you need to buy it if you want to create proprietary closed source software. This can be done using a GUI (Graphical User Interface) library with their Python bindings. The documentation is yet to improve.5 you can use it to create non-GPL software as well. and don't know whom to ask.
if Linux is a chosen platform. Java or C# in the above three implementations) Stackless Python (http:/ / www. org/ ThePythonPapersVolume3Issue1. is whether you are a KDE or GNOME user on Linux. The second factor is whether you want the program to run only on Windows or on Mac and Linux or all of them. Importantly. read the wxPython tutorial (http:/ / zetcode.NET libraries and classes from within Python language and vice-versa. TkInter This is one of the oldest GUI toolkits in existence. Volume 3. org) A Python implementation that runs on the Java platform. For a more detailed and comprehensive analysis.the language and the software. org/ cgi-bin/ moinmoin/ GuiProgramming). There are also other software that can run your Python programs: Jython (http:/ / www. IronPython (http:/ / www. To get started.Python en:What Next the wxGlade (http:/ / wxglade. com/ wxpython/ ). Issue 1 (http:/ / archive. com/ library/ tkinter/ introduction/ ). It doesn't have one of the best look & feel because it has an old-school look to it. The first factor is whether you are willing to pay to use any of the GUI tools. I suggest that you choose one of the above tools depending on your situation. A Python implementation that runs on the . We have been using the CPython software to run our programs. You can create free as well as proprietary software using wxPython. PyPy (http:/ / codespeak. you have seen a TkInter program at work. there is no one standard GUI tool for Python. It is referred to as CPython because it is written in the C language and is the Classical Python interpreter. The software is what actually runs our programs. pythonware. see the GuiProgramming wiki page at the official python website (http:/ / www. Various Implementations There are usually two parts a programming language . jython. com) A Python implementation that is specialized for thread-based performance. TkInter is portable and works on both Linux/Unix as well as Windows. For more choices. The third factor. This means you can use . sourceforge. net/ ) GUI builder. pythonpapers. . If you have used IDLE. pdf). html) A Python implementation written in Python! This is a research project to make it fast and easy to improve the interpreter since the interpreter itself is written in a dynamic language (as opposed to static languages such as C. 110 Summary of GUI Tools Unfortunately. net/ pypy/ dist/ pypy/ doc/ home. see Page 26 of the The Python Papers. python. This means you can use Java libraries and classes from within Python language and vice-versa. A language is how you write something. com/ Wiki/ View. read the Tkinter tutorial (http:/ / www. stackless.NET platform. To get started. TkInter is part of the standard Python distribution. aspx?ProjectName=IronPython) codeplex.
mozilla. [ Ubuntu Linux (http:/ / www. which itself is based on the concept of sharing. 2 anonymous edits Python en:Appendix FLOSS Free/Libre and Open Source Software (FLOSS) FLOSS (http:/ / en. presentation. This is an excellent office suite with a writer. and particularly the sharing of knowledge. ubuntu. com) ] • OpenOffice. So. It runs on almost all platforms. 111 Summary We have now come to the end of this book but. as they say.org. it is giving competition to Microsoft Windows. This is a community-driven distribution.Python en:What Next There are also others such as CLPython (http:/ / common-lisp. openoffice. net/ project/ clpython/ ) . Now. [ Linux Kernel (http:/ / Python implementation written in Common Lisp and IronMonkey (http:/ / wiki. [ OpenOffice (http:/ / www. you can just reboot your computer and run Linux off the CD! This allows you to completely try out the new OS before installing it on your computer. . spreadsheet and drawing components among other things. then you are already familiar with FLOSS since you have been using Python all along and Python is an open source software! Here are some examples of FLOSS to give an idea of the kind of things that community sharing and building can create: • Linux. sponsored by Canonical and it is the most popular Linux distribution today. This is a FLOSS operating system that the whole world is slowly embracing! It was started by Linus Torvalds as a student. The extensions concept allows any kind of plugins to be used. org) ] • Ubuntu. It can even open and edit MS Word and MS PowerPoint files with ease. It is blazingly fast and has gained critical acclaim for its sensible and impressive features. modification and redistribution. You are now an avid Python user and you are no doubt ready to solve many problems using Python. wikipedia. FLOSS are free for usage. This is the next generation web browser which is giving great competition to Internet Explorer.. Best of all. org/ wiki/ FLOSS) is based on the concept of a community. kernel. If you have already read this book. swaroopch. org) ] • Mozilla Firefox. get started! Previous Next Source: http:/ / www. It allows you to install a plethora of FLOSS available and all this in an easy-to-use and easy-to-install manner. com/ mediawiki/ index. You can start automating your computer to do all kinds of previously unimaginable things or write your own games and much much more. php? oldid=1845 Contributors: Swaroop. this is the the beginning of the end!.
apache. mysql. newsforge. ECMA (http:/ / www. This is a video player that can play anything from DivX to MP3 to Ogg to VCDs and DVDs to . This list could go on forever. PostgreSQL database server. org/ vlc/ ) ] • GeexBox is a Linux distribution that is designed to play movies as soon as you boot up from the CD! [ GeexBox (http:/ / geexbox. In fact. swaroopch. com/ net) ] • Apache web server. [ MySQL (http:/ / www. org) ] • MySQL. who says open source ain't fun? . freshmeat. com) 112 Visit the following websites for more information on FLOSS: • SourceForge (http:/ / www. mozilla. com) DistroWatch (http:/ / movie player.. free and open world of FLOSS! Previous Next Source: http:/ / www. PHP language. VIM editor. It allows . To get the latest buzz in the FLOSS world. Banshee audio player. linuxtoday. that's right . com/ mediawiki/ index. check out the following websites: • • • • linux..-) [ VLC media player (http:/ / (http:/ / www. [ Mono (http:/ / www. This is the popular open source web server. It is the M in the famous LAMP stack which runs most of the websites on the internet. 1 anonymous edits . go ahead and explore the vast.there are many more excellent FLOSS out there. ecma-international. org/ en/ start. org). sourceforge. com) LinuxToday (http:/ / www. mozilla. net) So.NET platform. org/ products/ thunderbird) ] • Mono. Windows.NET applications to be created and run on Linux.Apache handles more websites than all the competition (including Microsoft IIS) combined. GIMP image editing program. TORCS racing game. [ Mozilla Firefox (http:/ / (http:/ / www. php? oldid=1580 Contributors: Swaroop. [ Apache (http:/ / httpd. com) NewsForge (http:/ / www. such as the Perl language. Xine . FreeBSD. Yes. Quanta+ editor. microsoft. It is most famous for it's blazing speed.Python en:Appendix FLOSS • Its companion product Thunderbird is an excellent email client that makes reading email a snap. mono-project. KDevelop IDE. html) ] This list is just intended to give you a brief idea . Mac OS and many other platforms as well. com) ] • VLC Player. distrowatch. videolan. Drupal content management system for websites.. This is an extremely popular open source database server. Mozilla Thunderbird (http:/ / www. Microsoft . it is the most popular web server on the planet! It runs nearly more than half of the websites out there. linux. org/ products/ firefox). . com). net) • FreshMeat (http:/ / www. This is an open source implementation of the Microsoft .
but it produced very sloppy HTML from the document. The standard XSL stylesheets that came with Fedora Core 3 Linux were being used. I switched to OpenOffice which was just excellent with the level of control it provided for formatting as well as the PDF generation. I was using KWord to write the book (as explained in the History Lesson in the preface). I had used Red Hat 9. In the sixth draft. Now I edit everything online and the readers can directly read/edit/discuss within the wiki website.0 Linux as the foundation of my setup and in the sixth draft. I had written a CSS document to give color and style to the HTML pages. I discovered XEmacs and I rewrote the book from scratch in DocBook XML (again) after I decided that this format was the long term solution. I had also written a crude lexical analyzer. The standard default fonts are used as well. Now For this seventh draft. org) as the basis of my setup (http:/ / www. I'm using MediaWiki (http:/ / www. Finally. Initially. com/ notes/ ). I switched to DocBook XML using Kate but I found it too tedious. I used Fedora Core 3 Linux as the basis of my setup. which automatically provides syntax highlighting to all the program listings. mozilla. The standard fonts are used as well. Birth of the Book In the first draft of this book. So. org/ en-US/ firefox/ addon/ 394) that integrates with Vim.Python en:Appendix About 113 Python en:Appendix About Colophon Almost all of the software that I have used in the creation of this book are free and open source software. I still use Vim for editing thanks to the ViewSourceWith extension for Firefox (https:/ / addons. swaroopch. . I decided to use Quanta+ to do all the editing. However. Teenage Years Later. in Python of course. mediawiki.
swaroopch.20 • 13/01/2005 • Complete rewrite using Quanta+ on FC3 with lot of corrections and updates. swaroopch. Rewrote my DocBook setup from scratch. • 1. com/ mediawiki/ index.5 years! • Updating to Python 3. • 1.12 • 16/03/2004 • Additions and corrections. Book has improved a lot .98 • 16/02/2004 • Wrote a Python script and CSS stylesheet to improve XHTML output.99 • 22/02/2004 • Added a new chapter on modules. in DocBook XML (again).it is more coherent and readable. php? oldid=236 Contributors: Swaroop Python en:Appendix Revision History • 1. Added details about variable number of arguments in functions. • 0. . thanks to many enthusiastic and helpful readers. • 1.97 • 13/02/2004 • Another completely rewritten draft.Python en:Appendix About 114 About The Author http:/ / www. I have made significant revisions to the content along with typo corrections. • 0.00 • 08/03/2004 • After tremendous feedback and suggestions from readers. Many new examples.15 • 28/03/2004 • Minor revisions • 1.0 • Rewrite using MediaWiki (again) • 1. • 0.90 • 04/09/2008 and still in progress • Revival after a gap of 3. including a crude-yet-functional lexical analyzer for automatic VIM-like syntax highlighting of the program listings.10 • 09/03/2004 • More typo corrections. com/ about/ Previous Next Source: http:/ / www.
Improvised many topics. • 0. swaroopch. • 0. → Previous → Back to Table of Contents Source: http:/ / www. • 0. php? oldid=240 Contributors: Swaroop 115 . • 0.91 • 30/12/2003 • Corrected typos. OpenOffice format with revisions.90 • 18/12/2003 • Added 2 more chapters.10 • 14/11/2003 • Initial draft using KWord.92 • 05/01/2004 • Changes to few examples. • 0.60 • 21/11/2003 • Fully rewritten and expanded.Python en:Appendix Revision History • 0.93 • 25/01/2004 • Added IDLE talk and more Windows-specific stuff • 0. • 0.15 • 20/11/2003 • Converted to DocBook XML.20 • 20/11/2003 • Corrected some typos and errors. com/ mediawiki/ index.
html#about-unicode • Non-ASCII identifiers allowed • http:/ / www. htm on Windows • Classes • http:/ / docs. org/ dev/ peps/ pep-3101/ • http:/ / docs. python.format() instead of % operator • http:/ / www. 0/ tutorial/ introduction. org/ dev/ library/ string. html#formatstrings • Dict method changes • http:/ / www. html • Metaclasses • http:/ / www. org/ dev/ peps/ pep-3104/ • Functions can take * argument (varargs) for lists and keyword-only arguments • http:/ / www. etc. python. python.Python en:Appendix Changes for Python 3000 116 Python en:Appendix Changes for Python 3000 • Vim and Emacs editors • http:/ / henry. org/ dev/ peps/ pep-3127/ • nonlocal statement • http:/ / www. precheur. python. com/ 2008/ 05/ 09/ emacs-as-a-powerful-python-ide/ • String .) • http:/ / ivory. python. python. in data structures chapter • Problem Solving • Use http:/ / gnuwin32. python. org/ dev/ peps/ pep-3106/ • Built-in set class.unicode only • http:/ / docs. org/ dev/ 3. org/ dev/ 3. idyll. html • http:/ / www. org/ dev/ peps/ pep-3102/ • Functions can have annotations (make a passing note?) • http:/ / www. python. org/ articles/ advanced-swc/ #packages • String . python. org/ 2008/ 4/ 18/ Indenting%20Python%20with%20VIM. packages and their organization (including __init__. 0/ reference/ datamodel. net/ packages/ zip. python. org/ dev/ peps/ pep-3116/ • Exception handling . enigmacurry. python. org/ dev/ peps/ pep-3111/ • Integer Literal Support and Syntax • http:/ / www. org/ dev/ peps/ pep-3107/ • Better explanation of modules. python. org/ dev/ peps/ pep-3131/ • print() function • http:/ / www. python. org/ dev/ peps/ pep-3105/ • raw_input() becomes input() • http:/ / www. python.py. sourceforge. org/ dev/ peps/ pep-3115/ • Abstract Base Classes • http:/ / www. org/ dev/ peps/ pep-3119/ • Not sure if any changes required for New I/O • http:/ / www. python.
python. uk/ hppd/ hpux/ Users/ replace-2. com/ Interview-Questions/ Python/ index. python. org. coderholic. org/ dev/ peps/ pep-0352/ • http:/ / additions • • • • • • Reorganization : http:/ / to write a standard command-line program using python? • something like replace? • http:/ / hpux. html • http:/ / www. 0/ library/ trace. org/ dev/ howto/ doanddont. python. lang. html • http:/ / www. org/ dev/ library/ pdb. rosettacode. php? oldid=242 . html (important) http:/ / docs. org http:/ / www. com/ python-iaq. html • More • Unpacking can take * argument • http:/ / www. python. connect. python. html http:/ / docs. com/ mediawiki/ index. com/ Code/ Python/ CatalogPython. python. java2s. python. org/ dev/ peps/ pep-3110/ • Standard Library . ac. python. org/ dev/ 3. html http:/ / docs. net/ article/ 52 Source: http:/ / www. python. org/ dev/ peps/ pep-0343/ • What Next? • Implement 'replace' • http:/ / unixhelp. announce/ t/ 37de95ef0326293d • Examples • http:/ / www. python. org/ dev/ library/ urllib. org/ zone/ Links at the end of every Python-URL! email • http:/ / groups. python. repr/ascii functions • getopt/optparse . fyicenter. google. org http:/ / effbot. swaroopch. org/ dev/ library/ logging. ed. uk/ CGI/ man-cgi?replace • Mention use of PyPI • Q&A • http:/ / docs. python. com/ free-python-programming-books/ http:/ / pythonpapers. com/ group/ comp. org/ dev/ library/ warnings. org/ dev/ peps/ pep-3108/ http:/ / docs. org • http:/ / dev. python. python.Python en:Appendix Changes for Python 3000 • http:/ / www. html • Books & Resources • • • • • http:/ / www. html • http:/ / docs. html • eval. org/ dev/ library/ json. siafoo. org/ dev/ peps/ pep-3109/ • http:/ / www. mobilepythonbook. htm • Tips & Tricks • http:/ / www. org/ dev/ peps/ pep-3132/ • with statement • http:/ / www. html Debugging 117 • http:/ / docs. 24/ man. python. org/ doc/ faq/ general/ • http:/ / norvig.
0 Unported http:/ / creativecommons.Python en:Appendix Changes for Python 3000 Contributors: Swaroop 118 License Creative Commons Attribution-Share Alike 3. org/ licenses/ by-sa/ 3. 0/ . | https://www.scribd.com/doc/50649310/A-Byte-of-Python-3-0 | CC-MAIN-2017-39 | refinedweb | 35,557 | 69.38 |
It seems that some of the goals are not so hard. here I publised my progress. I show how to define a Ring, such a mathematical structure in Haskell, how to instantiate the class Num as a Ring , how to (possibly in other moment of space-time) instantiate a new class as Num and how to test the axioms for the new class. All of then is something like a sophisticated "assert" mechanism, but , I think, much more flexible and elegant. 2008/10/22 Alberto G. Corona <agocorona at gmail.com> > I guess that the namespace thing is not necesary. Maybe it can be done in > template haskell. I never used TH however. it is a matter of inserting code > here and there and rewrite rules somewhere at compile time. It´s a nice > project. I´ll try. > > > 2008/10/22 Mitchell, Neil <neil.mitchell.2 at credit-suisse.com> > >> Hi Alberta, >> >> It's a lot of work, but I wish you luck :-) Many of the underlying tools >> exist, but there definately needs more integration. >> >> Thanks >> >> Neil >> >> >> This material is sales and trading commentary and does not constitute >> investment research. Please follow the attached hyperlink to an important >> disclaimer >> *<>* >> >> >> ------------------------------ >> *From:* Alberto G. Corona [mailto:agocorona at gmail.com] >> *Sent:* 22 October 2008 4:23 pm >> *To:* Mitchell, Neil >> *Subject:* Re: [Haskell-cafe] Fwd: enhancing type classes with properties >> >> Hi Neil, >> >> I see the contract type mechanism and safety check techniques reflected >> in the above paper are a good step, But I think that something more >> general would be better. What I propose is to integrate directly in the >> language some concepts and developments that are already well know to >> solve some common needs that I thing can not be solved without this >> integration: >> >> To make use of: >> >> -Quickcheck style validation. By the way, Don Steward recommend to add >> quckcheck rules close to the class definitions just for better >> documentation >> >> - Implicit class properties defined everywhere in the documentation but >> impossible to reflect in the code (for example the famous monad rules: >> return x >>= f == f x etc ) >> >> - The superb ghc rewrite rule mechanism (perhaps with enhancements) >> >> - object style namespaces, depending on class names. >> >> To solve problems like >> >> - code optimization >> >> - code verification. regression tests for free!! >> >> - The need for safe overloading of methods and operators (making the >> namespaces dependent not only on module name but also in class names) . Why >> I can not overload the operator + in the context of a DSL for >> JavaScript generation if my operator does what + does? >> >> - strict and meaningful rules for class instances. >> - to make the rewrite rule mechanism visible to everyone >> >> >> >> 2008/10/22 Mitchell, Neil <neil.mitchell.2 at credit-suisse.com> >> >>> Hi Alberto, >>> >>> Take a look at ESC/Haskell and Sound Haskell, which provide mechanisms >>> for doing some of the things you want. I don't think they integrate with >>> type classes in the way you mention, but I think that is just a question of >>> syntax. >>> >>> <> >>> >>> Thanks >>> >>> Neil >>> >>> >>> This material is sales and trading commentary and does not constitute >>> investment research. Please follow the attached hyperlink to an important >>> disclaimer >>> *<>* >>> >>> >>> ------------------------------ >>> *From:* haskell-cafe-bounces at haskell.org [mailto: >>> haskell-cafe-bounces at haskell.org] *On Behalf Of *Alberto G. Corona >>> *Sent:* 22 October 2008 1:43 pm >>> *To:* haskell-cafe at haskell.org >>> *Subject:* [Haskell-cafe] Fwd: enhancing type classes with properties >>> >>> I´m just thinking aloud, but, because incorporating deeper mathematics >>> concepts has proven to be the best solution for better and more flexible >>> programming languages with fewer errors, I wonder if raising the type >>> classes incorporating axioms can solve additional problems. >>> >>> At first sight it does: >>> >>> >>> class Abelian a where >>> (+) :: a -> a -> a >>> property ((+))= a+b == b+a >>> >>> >>> >>> this permits: >>> 1- safer polimorphism: I can safely reuse the operator + if the type >>> and the property is obeyed. The lack of ability to redefine operators is a >>> problem for DSLs that must use wreid symbols combinations with unknow >>> meanings. To use common operators with fixed properties is very good. the >>> same aplies for method names. >>> >>> 2- the compiler can use the axions as rewrite rules. >>> >>> 3- in debugging mode, it is possible to verify the axiom for each >>> value a generated during execution. Thus, a generator is not needed like >>> in quickcheck. The logic to quickcheck can be incorporated in the debugging >>> executable. >>> >>> 3 guaranties that 1 and 2 are safe. >>> >>> >>> >>> >>> >>> a type class can express a relation between types, but it is not >>> possible to define relation between relations. >>> >>> ============================================================================== >>> Please access the attached hyperlink for an important electronic communications disclaimer: >>> >>> ============================================================================== >>> >>> >> ============================================================================== >> Please access the attached hyperlink for an important electronic communications disclaimer: >> >> ============================================================================== >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: | http://www.haskell.org/pipermail/haskell-cafe/2008-October/049749.html | CC-MAIN-2014-23 | refinedweb | 778 | 55.13 |
django-preserialize 1.0.7
Pre-serialize model instances and querysets
[]() []() []( "Bitdeli Badge")
django-preserialize is a one-stop shop for ensuring an object is free of `Model` and `QuerySet` instances. By default, all non-relational fields will be included as well as the primary keys of local related fields. The resulting containers will simply be `dict`s and `list`s.
## Install
```bash
pip install django-preserialize
```
## Docs
A serialized user object might look like this:
```python
>>> from preserialize.serialize import serialize
>>> serialize(user)
{
'date_joined': datetime.datetime(2009, 5, 16, 15, 52, 40),
'email': u'[email protected]',
'first_name': u'Jon',
'groups': [5],
'id': 1,
'is_active': True,
'is_staff': True,
'is_superuser': True,
'last_login': datetime.datetime(2012, 3, 3, 17, 40, 41, 927637),
'last_name': u'Doe',
'password': u'!',
'user_permissions': [1, 2, 3],
'username': u'jdoe'
}
```
This can then be passed off to a serializer/encoder, e.g. JSON, to turn
it into a string for the response body (or whatever else you want to do).
## Serialize Options
Some fields may not be appropriate or relevent to include as output.
To customize which fields get included or excluded, the
following arguments can be passed to ``serialize``:
**`fields`**
A list of fields names to include. Method names can also be specified that will be called when being serialized. Default is all local fields and local related fields. See also: `exclude`, `aliases`
**`exclude`**
A list of fields names to exclude (this takes precedence over fields). Default is `None`. See also: `fields`, `aliases`
**`related`**
A dict of related object accessors and configs (see below) for handling related objects.
**`values_list`**
This option only applies to `QuerySet`s. Returns a list of lists with the field values (like Django's `ValuesListQuerySet`). Default is `False`.
**`flat`**
Applies only if one field is specified in `fields`. If applied to a `QuerySet` and if `values_list` is `True` the values will be flattened out. If applied to a model instance, the single field value will used (in place of the dict). Note, if `merge` is true, this option has not effect. Default is `True`.
**`prefix`**
A string to be use to prefix the dict keys. To enable dynamic prefixes, the prefix may contain `'%(accessor)s'` which will be the class name for top-level objects or the accessor name for related objects. Default is `None`.
**`aliases`**
A dictionary that maps the keys of the output dictionary to the actual field/method names referencing the data. Default is `None`. See also: `fields`
**`camelcase`**
Converts all keys to a camel-case equivalent. This is merely a convenience for conforming to language convention for consumers of this content, namely JavaScript. Default is `False`.
**`allow_missing`**
Allow for missing fields (rather than throwing an error) and fill in the value with `None`.
### Hooks
Hooks enable altering the objects that are serialized at each level.
**`prehook`**
A function that takes and returns an object. For `QuerySet`s it can be used for filtering or annotating additional data to each model instance. For `Model` instances it can be prefetching additional data, swapping out an instance or whatever is necessary prior to serialization.
Since filtering `QuerySet`s is a common use case, a simple dict can be supplied instead of a function that will be passed to the `filter` method.
Here are two examples for filtering `posts` by the requesting user.
The shorthand method of using a `dict`:
```python
def view(request):
template = {
'related': {
'posts': {
'prehook': {'user': request.user},
}
}
}
...
```
For applying conditional logic, a function can be used:
```python
from functools import partial
def filter_by_user(queryset, request):
if not request.user.is_superuser:
queryset = queryset.filter(user=request.user)
return queryset
def view(request):
template = {
'related': {
'posts': {
'prehook': partial(filter_by_user, request=request)
}
}
}
...
```
**`posthook`**
A function that takes the original model instance and the serialized attrs for post-processing. This is specifically useful for augmenting or modifying the data prior to being added to the large serialized data structure.
Even if the related object (like `posts` above) is a `QuerySet`, this hook is applied per object in the `QuerySet`. This is because it would rarely ever be necessary to process a list of objects as a whole since filtering can already be performed above (using the `prehook`) prior to serialization.
Here is an example of adding resource links to the output data based on the serialized attributes:
```python
from functools import partial
from django.core.urlresolvers import reverse
def add_resource_links(instance, attrs, request):
uri = request.build_absolute_uri
attrs['_links'] = {
'self': {
'href': uri(reverse('api:foo:bar', kwargs={'pk': attrs.id})),
},
...
}
return attrs
template = {
'posthook': partial(add_resource_links, request=request),
...
}
```
### Examples
```python
# The field names listed are after the mapping occurs
>>> serialize(user, fields=['username', 'full_name'], aliases={'full_name': 'get_full_name'}, camelcase=True)
{
'fullName': u'Jon Doe',
'username': u'jdoe'
}
>>> serialize(user, exclude=['password', 'groups', 'permissions'])
{
'date_joined': datetime.datetime(2009, 5, 16, 15, 52, 40),
'email': u'[email protected]',
'first_name': u'Jon',
'id': 1,
'is_active': True,
'is_staff': True,
'is_superuser': True,
'last_login': datetime.datetime(2012, 3, 3, 17, 40, 41, 927637),
'last_name': u'Doe',
'username': u'jdoe'
}
>>> serialize(user, fields=['foo', 'bar', 'baz'], allow_missing=True)
{
'foo': None,
'bar': None,
'baz': None,
}
```
## Related Objects
Composite resources are common when dealing with data that have _tight_ relationships. A user and their user profile is an example of this. It is inefficient for a client to have to make two separate requests for data that is typically always consumed together.
`serialize` supports the `related` keyword argument for defining options for relational fields. The following additional argument (to the above) may be defined:
**`merge`**
This option only applies to local `ForeignKey` or `OneToOneField`. This allows for merging the related object's fields into the parent object.
```python
>>> serialize(user, related={'groups': {'fields': ['name']}, 'profile': {'merge': True}})
{
'username': u'jdoe',
'groups': [{
'name': u'Managers'
}]
# profile attributes merged into the user
'twitter': '@jdoe',
'mobile': '123-456-7890',
...
}
```
## Conventions
**Define a template dict for each model that will be serialized.**
Defining a _template_ enables reuse across different serialized objects as well as increases readability and maintainability. Deconstructing the above example, we have:
```python
# Render a list of group names.. note that 'values_list'
# options is implied here since there is only one field
# specified. It is here to be explicit.
group_template = {
'fields': ['name'],
'values_list': True,
}
# User profiles are typically always wanted to be merged into
# User, so we can add the 'merge' option. Remember this simply
# gets ignored if 'UserProfile' is the top-level object being
# serialized.
profile_template = {
`exclude`: ['user'],
'merge': True,
}
# Users typically always include some related data (groups and their
# profile), so we can reference the above templates in this one.
user_template = {
'exclude': ['password', 'user_permissions'],
'related': {
'groups': group_template,
'profile': profile_template,
}
}
# Everyone is the pool!
users = User.objects.all()
# Now we can use Python's wonderful argument _unpacking_ syntax.
# Clean.
serialize(users, **user_template)
```
### Does the serializer only understand model fields?
No. In fact it is smart about accessing the _field_. The following steps are taken when attempting to get the value:
1. Use `hasattr` to check if an attribute/property is present
2. If the object support `__getitem__`, check if the key is present
Assuming one of those two methods succeed, it will check if the value is callable and will call it (useful for methods). If the value is a `RelatedManager`, it will resolve the `QuerySet` and recursive downstream.
### Does the serializer only support model instances?
No. It is not always the case that a single model instance or queryset is the source of data for a resource. `serialize` also understands `dict`s and any iterable of `dict`s. They will be treated similarly to the model instances.
### My model has a ton of fields and I don't want to type them all out. What do I do?
The `fields` and `exclude` options understands four _pseudo-selectors_ which can be used in place of typing out all of a model's field names (although being explicit is typically better).
**`:pk`**
The primary key field of the model
**`:local`**
All local fields on a model (including local foreign keys and
many-to-many fields)
**`:related`**
All related fields (reverse foreign key and many-to-many)
**`:all`**
A composite of all selectors above and thus any an all fields on or related to a model
You can use them like this:
```python
# The two selectors here are actually the default, but defined
# for the example.
serialize(user, fields=[':pk', ':local', 'foo'], exclude=['password'])
```
## CHANGELOG
2013-05-01
- Update `posthook` to take the original instance as the first argument and the serialized data as the second argument
- Ensure the passed object is returned from `serialize` even if it does not qualify to be processed
2013-04-29
- Fix bug where the `flat` option was not respecting `merge`
- If `merge` is set, it takes precedence over flat
2013-04-28
- Add `prehook` and `posthook` options
- Add support for `flat` option for model instances with a single field
- Rename `key_map` to `aliases` for clarity
- Rename `key_prefix` to `prefix`
- It is implied the prefix applies to the keys since this a serialization
utility
- Internal clean up
- Correct documentation regarding the `flat` option
- It was incorrectly named `flatten`
- Author: Byron Ruth
- Keywords: serialize model queryset django
- License: BSD
- Categories
- Package Index Owner: bruth
- DOAP record: django-preserialize-1.0.7.xml | https://pypi.python.org/pypi/django-preserialize/1.0.7 | CC-MAIN-2017-09 | refinedweb | 1,532 | 54.93 |
absolute or fixed positioning
Places the element relative to either the element's parent or, if there isn't one, the body. Values for the element's Left and Top properties are relative to the upper-left corner of the element's parent.
Access workspace
A workspace that uses the Access database engine to access a data source. The data source can be an Access database file, an ODBC database, such as a Paradox or Microsoft SQL Server database, or an ISAM database.
action
The basic building block of a macro; a self-contained instruction that can be combined with other actions to automate tasks. This is sometimes called a command in other macro languages.
action argument
Additional information required by some macro actions. For example, the object affected by the action or special conditions under which the action is carried out.
action list
The list that appears when you click the arrow in the Action column of the Macro object tab.
action query
A query that copies or changes data. Action queries include append, delete, make-table, and update queries. They are identified by an exclamation point (!) next to their names in the Navigation Pane.
action row
A row in the upper part of the Macro object tab in which you enter macro names, actions, arguments, and comments associated with a particular macro or macro group.
ADE file
An Access project (.adp file) with all modules compiled and all editable source code removed.
Advanced Filter/Sort window
A window in which you can create a filter from scratch. You enter criteria expressions in the filter design grid to restrict the records in the open form or datasheet to a subset of records that meet the criteria.
aggregate function
A function, such as Sum, Count, Avg, or Var, that you use to calculate totals.
anonymous replica
In an Access database (.mdb file format only), a special type of replica in which you don't keep track of individual users. The anonymous replica is particularly useful in an Internet situation where you expect many users to download replicas.
ANSI SQL query mode
One of two types of SQL syntax: ANSI-89 SQL (also called Microsoft Jet SQL and ANSI SQL), which is the traditional Jet SQL syntax; and ANSI-92 SQL, which has new and different reserved words, syntax rules, and wildcard characters.
append query
An action query that adds the records in a query's result set to the end of an existing table.
application background
The background area of an application window.
ASCII
American Standard Code for Information Interchange (ASCII) 7-bit character set used to represent letters and symbols found on a standard U.S. keyboard.
autofiltering
Filtering data in PivotTable or PivotChart view by selecting one or more items in a field that allows filtering.
autoformat
A collection of formats that determines the appearance of the controls and sections in a form or report.
automatic link
A link from an OLE object in Access to an OLE server that automatically updates the object in Access when the information in the object file changes.
AutoNumber data type
In an Access database, a field data type that automatically stores a unique number for each record as it is added to a table. Three kinds of numbers can be generated: sequential, random, and Replication ID.
base table
A table in an Access database. You can manipulate the structure of a base table by using the DAO objects or data definition (DDL) SQL statements, and you can modify data in a base table by using Recordset objects or action queries.
bigint data type
In an Access project, a data type of 8 bytes (64 bits) that stores whole numbers in the range of -2^63 (-9,223,372,036,854,775,808) through 2^63-1 (9,223,372,036,854,775,807).
binary data type
In an Access project, a fixed-length data type with a maximum of 8,000 bytes of binary data.
bit data type
In an Access project, a data type that stores either a 1 or 0 value. Integer values other than 1 or 0 are accepted, but they are always interpreted as 1.
bit mask
A value that is used with bitwise operators (And, Eqv, Imp, Not, Or, and Xor) to test, set, or reset the state of individual bits in a bitwise field value.
bitwise comparison
A bit-by-bit comparison between identically positioned bits in two numeric expressions.
Bookmark
A property of a Recordset object or a form that contains a binary string identifying the current record.
bound column
The column in a list box, combo box, or drop-down list box that is bound to the field specified by the control's ControlSource property.
bound control
A control used on a form, report, or data access page to display or modify data from a table, query, or SQL statement. The control's ControlSource property stores the field name to which the control is bound.
bound hyperlink control
A control that is used on a data access page to bind a link, an intranet address, or an Internet address to an underlying Text field. You can click the hyperlink to go to the target location.
bound object frame
A control on a form or report that is used to display and manipulate OLE objects that are stored in tables.
bound picture
A control that is used on a form, report, or data access page to bind an image to an OLE Object field in an Access database or an image column in an Access project.
bound span control
A control that is used on a data access page to bind HTML code to a Text or Memo field in an Access database or to a text, ntext, or varchar column in an Access project. You cannot edit the contents of a bound span control.
builder
An Access tool that simplifies a task. For example, you can quickly create a complex expression by using the Expression Builder.
built-in toolbar
In Access 2003 and earlier, a toolbar that is part of the Access user interface when it is installed on your computer. In contrast, a custom toolbar is one that you create for your own database application. In current versions of Access, toolbars are replaced by the Ribbon, which arranges commands in related groups on tabs. In addition, you can add commands that you frequently use to the Quick Access Toolbar.
Byte data type
An Access database data type that is used to hold small positive integers ranging from 0 to 255.
calculated control
A control that is used on a form, report, or data access page to display the result of an expression. The result is recalculated each time there is a change in any of the values on which the expression is based.
calculated field
A field, defined in a query, that displays the result of an expression rather than displaying stored data. The value is recalculated each time a value in the expression changes.
call tree
All modules that might be called by any procedure in the module in which code is currently running.
caption section
The section on a grouped data access page that displays captions for columns of data. It appears immediately before the group header. You cannot add a bound control to a caption section.
Cartesian product
The result of executing an SQL SELECT statement that includes two or more tables in the FROM clause, but no WHERE or JOIN clause that indicates how the tables are to be joined.
cascade
The process of one action triggering another action. For example, when a cascading update relationship is defined for two or more tables, an update to the primary key in the primary table automatically triggers changes to the foreign table.
cascading delete
For relationships that enforce referential integrity between tables, the deletion of all related records in the related table or tables when a record in the primary table is deleted.
cascading event
A sequence of events caused by an event procedure directly or indirectly calling itself; also called an event cascade or a recursion. Be careful using cascading events, because they often result in stack-overflow or other run-time errors.
cascading update
For relationships that enforce referential integrity between tables, the updating of all related records in the related table or tables when a record in the primary table is changed.
category field
A field that is displayed in the category area of PivotChart view. Items in a category field appear as labels on the category axis.
channel number
An integer that corresponds to an open Dynamic Data Exchange (DDE) channel. Channel numbers are assigned by Microsoft Windows 95 or later, created by using the DDEInitiate function, and used by other DDE functions and statements.
char data type
In an Access project, a fixed-length data type with a maximum of 8,000 ANSI characters.
character code
A number that represents a particular character in a set, such as the ANSI character set.
chart
A graphical representation of data in a form, report, or data access page.
check box
A control that indicates whether an option is selected. A check mark appears in the box when the option is selected.
CHECK constraint
Allows for business rules that span multiple tables. For example, the Order table could have a CHECK constraint that would prevent orders for a customer from exceeding a credit limit defined for the customer in the Customer table.
class module
A module that can contain the definition for a new object. Each instance of a class creates a new object. Procedures defined in the module become properties and methods of the object. Class modules can exist alone or with forms and reports.
class name
The name used to refer to a class module. If the class module is a form or report module, the class name is prefaced with the type of module — for example, Form_OrderForm.
class name (OLE)
A predefined name used to refer to an OLE object in Visual Basic. It consists of the name of the application used to create the OLE object, the object's type, and, optionally, the version number of the application. Example: Excel.Sheet.
code stub
A segment of Visual Basic code that defines the beginning and end of a procedure.
collision
A conflict that occurs during a batch update. A client reads data from the server and then attempts to modify that data in a batch update, but before the update attempt is executed, another client changes the original server data.
column
A location within a database table that stores a particular type of data. It is also the visual representation of a field in a datasheet and, in an Access database, the query design grid or the filter design grid.
column area
The part of PivotTable view that contains column fields.
column field
A field in the column area of PivotTable view. Items in column fields are listed across the top of a PivotTable list. Inner column fields are closest to the detail area; outer column fields are displayed above the inner column fields.
column selector
The horizontal bar at the top of a column. You can click a column selector to select an entire column in the query design grid or the filter design grid.
combo box
A control used on a form that provides the combined functionality of a list box and a text box. You can type a value in a combo box, or you can click the control to display a list and then select an item from that list.
command button
A control that runs a macro, calls a Visual Basic function, or runs an event procedure. A command button is sometimes called a push button in other programs.
comparison operator
An operator that is used to compare two values or expressions. For example, < (less than), > (greater than), and = (equal to).
compound control
A control and an attached label, such as a text box with an attached label.
conditional filtering
Filtering a field to show the top or bottom n items based on a total. For example, you could filter for the three cities that generated the most sales or the five products that are least profitable.
conditional formatting
Formatting the contents of a control in a form or report based on one or more conditions. A condition can reference another control, the control with the focus, or a user-defined Visual Basic for Applications function.
conflict
A condition that occurs if data has changed in the same record of two replica set members. When a conflict occurs, a winning change is selected and applied in all replicas, and the losing change is recorded as a conflict in all replicas.
connection string
A string expression that is used to open an external database.
constraint
A restriction placed on the value that can be entered into a column or a row. For example, values in the Age column cannot be less than 0 or greater than 110.
continuous form
A form that displays more than one record on the screen in Form view.
control containing a hyperlink
A control that makes it possible for a user to jump to a document, Web page, or object. An example is a text box that is bound to a field that contains hyperlinks.
crosstab query
A query that calculates a sum, average, count, or other type of total on records, and then groups the result by two types of information: one down the left side of the datasheet and the other across the top.
Currency data type
In an Access database, a data type that is useful for calculations involving money or for fixed-point calculations in which accuracy is extremely important.
current record
The record in a recordset from which you can modify or retrieve data. There can be only one current record in a recordset at any given time, but a recordset may have no current record — for example, after a record has been deleted from a dynaset-type recordset.
cursor data type
In an Access project, a data type you can use only for creating a cursor variable. This data type cannot be used for columns in a table. A cursor is a mechanism used to work with one row at a time in the result set of a SELECT statement.
custom group
An item of a custom group field. A custom group contains two or more items from a row or column field.
custom group field
A field in the row or column area that contains custom groups as its items.
custom order
User-defined sort order. For example, you could define a custom sort order to display values in the EmployeeTitle column on the basis of the title's seniority.
custom properties dialog box
A custom property sheet that allows users to set properties for an ActiveX control.
custom toolbar
In Access 2003 and earlier versions, a toolbar that you create for your application. In contrast, a built-in toolbar is part of Access when it is installed on your computer.
DAO object
An object defined by the Data Access Objects (DAO) library. You can use DAO objects, such as Database, TableDef, and Recordset, to represent objects that are used to organize and manipulate data, such as tables and queries, in code.
data access objects
A programming interface that you can use to access and manipulate database objects.
Data Access Objects (DAO)
data access page
A Web page designed for viewing and working with data from the Internet or an intranet. Its data is typically stored in an Access database.
data access page properties
Attributes of a data access page that identify the database to which the page is connected and define the page's appearance and behavior.
data area
The part of PivotTable or PivotChart view that contains summary data. Values in the data area are displayed as records in PivotTable view and as data points in PivotChart view.
data collection
A method of gathering information from users by sending and receiving HTML forms or InfoPath 2007 forms from Access 2007. In Access, you create a data collection request and send it to users in a form contained in an e-mail message. Users then complete a form and return it to you.
data definition
The fields in underlying tables and queries, and the expressions, that make up the record source for a data access page.
data definition language (DDL)
The language used to describe attributes of a database, especially tables, fields, indexes, and storage strategy. ANSI defines this to have the tokens CREATE, DROP, and ALTER. DDL is a subset of structured query language (SQL).
data definition query
An SQL-specific query that can create, alter, or delete a table, or create or delete an index in a database. ANSI defines these as DDL queries and uses the tokens CREATE, DROP, and ALTER.
data field
A field that contains summarized data in PivotTable or PivotChart view. A data field usually contains numeric data.
data item
An application-specific piece of data that can be transferred over a (Dynamic Data Exchange) DDE channel.
data label
A label that provides additional information about a data marker, which represents a single data point or value.
data manipulation language (DML)
The language used to retrieve, insert, delete and update data in a database. DML is a subset of Structured Query Language (SQL).
data marker
A bar, area, dot, slice, or other symbol in a chart that represents a single data point or value. Related data markers in a chart constitute a data series.
data series
Related data points that are plotted in a chart. Each data series in a chart has a unique color or pattern. You can plot one or more data series in a chart.
data source control
The engine behind data access pages and Microsoft Office Web Components that manages the connection to the underlying data source. The data source control has no visual representation.
database application
A set of objects that can include tables, queries, forms, reports, macros, and code modules that are designed to work together to make a database easier to use. A database application is typically deployed to a group of users.
database diagram
A graphical representation of any portion of a database schema. It can be either a whole or partial picture of the structure of the database. It includes tables, the columns they contain, and the relationships between the tables.
Database Documenter
A tool that builds a report containing detailed information about the objects in a database.
database objects
An Access database contains objects such as tables, queries, forms, reports, pages, macros, and modules. An Access project contains objects such as forms, reports, pages, macros, and modules.
database replication
The process of creating two or more special copies (replicas) of an Access database. Replicas can be synchronized, changes made to data in one replica, or design changes made in the Design Master, are sent to other replicas.
Database window
In Access 2003 and earlier, the window that appears when you open an Access database or an Access project. It displays shortcuts for creating new database objects and opening existing objects. In Access 2007, the Database window is replaced by the Navigation Pane.
data-definition query
An SQL-specific query that contains data definition language (DDL) statements. These statements allow you to create or alter objects in the database.
datasheet
Data from a table, form, query, view, or stored procedure that is displayed in a row-and-column format.
Datasheet view
A view that displays data from a table, form, query, view, or stored procedure in a row-and-column format. In Datasheet view, you can edit fields, add and delete data, and search for data. In Access 2007, you can also modify and add fields to a table in Datasheet view.
date expression
Any expression that can be interpreted as a date, including date literals, numbers that look like dates, strings that look like dates, and dates returned from functions.
date literal
Any sequence of characters with a valid format that is surrounded by number signs (#). Valid formats include the date format specified by the locale settings for your code or the universal date format.
date separators
Characters used to separate the day, month, and year when date values are formatted. The characters are determined by system settings or by using the Format function.
Date/Time data type
An Access database data type that is used to hold date and time information.
datetime data type
In an Access project, a date and time data type that ranges from January 1, 1753, to December 31, 9999, to an accuracy of three-hundredths of a second, or 3.33 milliseconds.
DBCS
A character set that uses 1 or 2 bytes to represent a character, allowing more than 256 characters to be represented.
Decimal data type (Access database)
An exact numeric data type that holds values from -10^28 - 1 through 10^28 - 1. You can specify the scale (maximum number of digits) and precision (maximum total number of digits to the right of the decimal point).
Decimal data type (Access project)
An exact numeric data type that holds values from -10^38 - 1 through 10^38 - 1. You can specify the scale (maximum total number of digits) and precision (maximum number of digits to the right of the decimal point).
declaration
Nonexecutable code that names a constant, variable, or procedure, and specifies its characteristics, such as data type. For DLL procedures, declarations specify names, libraries, and arguments.
Declarations section
The section of a module containing declarations that apply to every procedure in the module. It can include declarations for variables, constants, user-defined data types, and external procedures in a dynamic-link library.
default control style
The default property setting of a control type. You customize a control type before you create two or more similar controls to avoid customizing each control individually.
default property
A property that you can set for a control so that each time a new control of that type is created, the property will have the same value.
default value
A value that is automatically entered in a field or control when you add a new record. You can either accept the default value or override it by typing a value.
delete query
A query (SQL statement) that removes rows matching the criteria that you specify from one or more tables.
design grid
The grid that you use to design a query or filter in query Design view or in the Advanced Filter/Sort window. For queries, this grid was formerly known as the QBE grid.
Design Master
The only member of the replica set in which you can make changes to the database structure that can be propagated to other replicas.
Design view
A view that shows the design of these database objects: tables, queries, forms, reports, and macros. In Design view, you can create new database objects and modify the design of existing objects.
detail area
The part of PivotTable view that contains detail and total fields.
detail field
A field that displays all rows, or records, from the underlying record source.
detail section
Used to contain the main body of a form or report. This section usually contains controls bound to the fields in the record source but can also contain unbound controls, such as labels that identify a field's contents.
direct synchronization
A method used to synchronize data between replicas that are connected directly to the local area network and are available through shared network folders.
disabled control
A control that appears dimmed on a form. A disabled control cannot get the focus and will not respond to mouse clicks.
document properties
Properties, such as title, subject, and author, that are stored with each data access page.
domain
A set of records that is defined by a table, a query, or an SQL expression. Domain aggregate functions return statistical information about a specific domain or set of records.
domain aggregate function
A function, such as DAvg or DMax, that is used to calculate statistics over a set of records (a domain).
double precision
Characteristic of a number stored in twice the amount (two words; typically 8 bytes) of computer memory that is required for storing a less precise (single-precision) number. Commonly handled by a computer in floating-point form.
drop area
An area in PivotTable view or PivotChart view in which you can drop fields from the field list to display the data in the field. The labels on each drop area indicate the types of fields that you can create in the view.
drop-down list box
A control on a data access page that, when clicked, displays a list from which you can select a value. You cannot type a value in a drop-down list box.
dynamic-link library
A set of routines that can be called from Visual Basic procedures and are loaded and linked into your application at run time.
echo
The process of Access updating or repainting the screen while a macro is running.
edit control
Also known as a text box, an edit control is a rectangular region in which a user can enter and edit text.
embed
To insert a copy of an OLE object from another application. The source of the object, called the OLE server, can be any application that supports object linking and embedding. Changes to an embedded object are not reflected in the original object.
enabled database
A previous-version database that has been opened in Access 2000 or later without converting its format. To change the design of the database, you must open it in the version of Access in which it was created.
error number
A whole number in the range 0 - 65,535 that corresponds to the Number property setting of the Err object. When combined with the Description property setting of the Err object, this number represents a particular error message.
exclusive
A mode of access to data in a database that is shared over a network. When you open a database in exclusive mode, you prevent others from opening the database.
expand control
A control on a data access page that, when clicked, expands or collapses a grouped record to display or hide its detail records.
expand indicator
A button that is used to expand or collapse groups of records; it displays the plus (+) or minus (-) sign.
export
To copy data and database objects to another database, spreadsheet file, or file format so that another database or program can use the data or database objects. You can export data to a variety of supported databases, programs, and file formats.
Expression Builder
An Access tool that you can use to create an expression. It includes a list of common expressions that you can select.
external database
The source of the table that is to be linked or imported to the current database, or the destination of a table that is to be exported.
external table
A table outside the currently open Access database or Access project.
field data types
A characteristic of a field that determines what kind of data it can store. For example, a field whose data type is Text can store data consisting of either text or numeric characters, but a Number field can store only numerical data.
Field List pane
A pane that lists all the fields in the underlying record source or database object.
field selector
A small box or bar that you click to select an entire column in a datasheet.
file number
A number used in the Open statement to open a file. Use file numbers in the range 1 - 255, inclusive, for files that are not accessible to other programs. Use file numbers in the range 256 - 511 for files accessible from other programs.
Fill
A report magnification that fills the Report Snapshot window by fitting either the width or the height of a page, depending on whether the report is in portrait or landscape orientation.
filter
A set of criteria applied to data in order to display a subset of the data or to sort the data. In Access, you can use filtering techniques, such as Filter By Selection and Filter By Form, to filter data.
filter area
The part of a PivotTable view or PivotChart view that contains filter fields.
Filter By Form
A technique for filtering data that uses a version of the current form or datasheet with empty fields in which you can type the values that you want the filtered records to contain.
Filter By Selection
A technique for filtering records in a form or datasheet in which you retrieve only records that contain the selected value.
Filter Excluding Selection
A technique in which you filter records in a form or datasheet to retrieve only those records that don't contain the selected value.
filter field
A field in the filter area that you can use to filter data displayed in PivotTable view or PivotChart view. Filter fields perform the same functions as page fields in Microsoft Excel PivotTable reports.
Filter For Input
A technique for filtering records that uses a value or expression that you enter to find only records that contain the value or satisfy the expression.
fixed-width text file
A file containing data in which each field has a fixed width.
float data type
In an Access project, an approximate numeric data type with 15-digit precision. The float data type can hold positive values from approximately 2.23E - 308 through 1.79E + 308, negative values from approximately -2.23E - 308 through -1.79E + 308, or zero.
floating
Able to move freely as its own window. A floating window is always on top. The Expression Builder, the Database Documenter, the toolbox, and palettes can float.
foreign key
One or more table fields (columns) that refer to the primary key field or fields in another table. A foreign key indicates how the tables are related.
foreign table
A table (such as Customer Orders) that contains a foreign key field (such as CustomerID) that is the primary key field in another table (such as Customers) in the database and that is usually on the "many" side of a one-to-many relationship
form
An Access database object on which you place controls for taking actions or for entering, displaying, and editing data in fields.
form footer
Used to display instructions for using a form, command buttons, or unbound controls to accept input. Appears at the bottom of the form in Form view and at the end of a printout.
form header
Used to display a title for a form, instructions for using the form, or command buttons that open related forms or carry out other tasks. The form header appears at the top of the form in Form view and at the beginning of a printout.
form module
A module that includes Visual Basic for Applications (VBA) code for all event procedures triggered by events occurring on a specific form or its controls.
Form object tab
An object tab in which you work with forms in Design view, Form view, Datasheet view, or Print Preview.
form properties
Attributes of a form that affect its appearance or behavior. For example, the DefaultView property is a form property that determines whether a form will automatically open in Form view or Datasheet view.
form selector
The box where the rulers meet, in the upper-left corner of a form in Design view. Use the box to perform form-level operations, such as selecting the form.
Form view
A view that displays a form that you use to show or accept data. Form view is the primary means of adding and modifying data in tables. You can also change the design of a form in this view.
format
Specifies how data is displayed and printed. An Access database provides standard formats for specific data types, as does an Access project for the equivalent SQL data types. You can also create custom formats.
front-end/back-end application
A database application consisting of a "back-end" database file that contains tables, and copies of a "front-end" database file that contain all other database objects with links to the "back-end" tables.
function
A query that takes input parameters and returns a result like a stored procedure. Types: scalar (multistatement; returns one value), inline (one statement; an updateable table value), and table (multistatement; table value).
Function procedure
In Visual Basic for Applications (VBA), a procedure that returns a value and that can be used in an expression. You declare a function by using the Function statement and end it by using the End Function statement.
General sort order
The default sort order determines how characters are sorted in the entire database, such as in tables, queries, and reports. You should define the General sort order if you plan to use a database with multiple language editions of Access.
global menu bar
In Access 2003 and earlier, a special custom menu bar that replaces the built-in menu bar in all windows in your database application, except where you've specified a custom menu bar for a form or report.
global replica
A replica in which changes are fully tracked and can be exchanged with any global replica in the set. A global replica can also exchange changes with any local or anonymous replicas for which it becomes the hub.
global shortcut menu
A custom shortcut menu that replaces the built-in shortcut menu for the following objects: fields in table and query datasheets; forms and form controls in Form view, Datasheet view, and Print Preview; and reports in Print Preview.
globally unique identifier (GUID)
A 16-byte field used in an Access database to establish a unique identifier for replication. GUIDs are used to identify replicas, replica sets, tables, records, and other objects. In an Access database, GUIDs are referred to as Replication IDs.
grid (Datasheet view)
Vertical and horizontal lines that visually divide rows and columns of data into cells in a table, query, form, view, or stored procedure. You can show and hide these grid lines.
grid (Design view)
An arrangement of vertical and horizontal dotted and solid lines that help you position controls precisely when you design a form or report.
group account
A collection of user accounts in a workgroup, identified by group name and personal ID (PID). Permissions assigned to a group apply to all users in the group.
group filter control
A drop-down list box control on a data access page that retrieves records from an underlying recordset based on the value that you select from the list. On a grouped page, the control retrieves a specific group of records.
group footer
Used to place information, such as group name or group total, at the end of a group of records.
group header
Used to place information, such as group name or group total, at the beginning of a group of records.
group level
The depth at which a group in a report or data access page is nested inside other groups. Groups are nested when a set of records is grouped by more than one field, expression, or group record source.
grouped controls
Two or more controls that can be treated as one unit while designing a form or report. You can select the group instead of selecting each individual control as you are arranging controls or setting properties.
grouped data access page
A data access page that has two or more group levels.
GUID data type
A unique identification string used with remote procedure calls. Every interface and object class uses a GUID (Globally Unique Identifier) for identification. A GUID is a 128-bit value.
host application
Any application that supports the use of Visual Basic for Applications.
hub
A global replica to which all replicas in the replica set synchronize their changes. The hub serves as the parent replica.
hyperlink address
The path to a destination such as an object, document, or Web page. A hyperlink address can be a URL (address to an Internet or intranet site) or a UNC network path (address to a file on a local area network).
Hyperlink data type
A data type for an Access database field that stores hyperlink addresses. An address can have up to four parts and is written using the following format: displaytext#address#subaddress#.
hyperlink field
A field that stores hyperlink addresses. In an Access database, it is a field with a Hyperlink data type. In an Access project, it is a field that has the IsHyperlink property set to True.
hyperlink image control
A control that is used on a data access page to display an unbound image that represents a hyperlink to a file or Web page. In Browse mode, you can click the image to go to the target location.
IDC/HTX files
Microsoft Internet Information Server uses an IDC file and an HTX file to retrieve data from an ODBC data source and format it as an HTML document.
identifier (expressions)
An element of an expression that refers to the value of a field, control, or property. For example, Forms![Orders]![OrderID] is an identifier that refers to the value in the OrderID control on the Orders form.
identifier (Visual Basic)
A data member in a Visual Basic code module. An identifier can be a Sub, Function, or Property procedure, a variable, a constant, a DECLARE statement, or a user-defined data type.
image control
A control that is used to display a picture on a form or report.
image data type
In an Access project, a variable-length data type that can hold a maximum of 2^31 - 1 (2,147,483,647) bytes of binary data. It is used to store Binary Large Objects (BLOBs), such as pictures, documents, sounds, and compiled code.
import
To copy data from a text file, spreadsheet file, or database table into an Access table. You can use the imported data to create a new table, or you can append (add) it to an existing table that has a matching data structure.
import/export specification
A specification that stores the information that Access needs to run an import or export operation on a fixed-width or delimited text file.
index
A feature that speeds up searching and sorting in a table based on key values and can enforce uniqueness on the rows in a table. The primary key of a table is automatically indexed. Some fields cannot be indexed because of their data type, such as OLE Object or Attachment.
Indexes window
In an Access database, a window in which you can view or edit a table's indexes or create multiple-field indexes.
indirect synchronization
A synchronization method that is used in a disconnected environment, such as when you travel with a portable computer. You must use the Replication Manager to configure indirect synchronization.
in-place activation
Activation of an OLE object's OLE server from within a field or control. For example, you can play a waveform audio (.wav) file contained in a control by double-clicking the control.
input mask
A format that consists of literal display characters (such as parentheses, periods, and hyphens) and mask characters that specify where data is to be entered as well as what kind of data and how many characters are allowed.
installable ISAM
A driver you can specify that allows access to external database formats such as dBASE, Excel, and Paradox. The Microsoft Access database engine installs (loads) these ISAM drivers when referenced by your application.
instance
An object that is created from the class that contains its definition. For example, multiple instances of a form class share the same code and are loaded with the same controls that were used to design the form class.
int data type
In an Access project, a data type of 4 bytes (32 bits) that stores whole numbers in the range of -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647).
Integer data type
A fundamental data type that holds integers. An Integer variable is stored as a 16-bit (2-byte) number ranging in value from -32,768 to 32,767.
Internet synchronization
Used to synchronize replicas in a disconnected environment in which an Internet server is configured. You must use the Replication Manager to configure Internet synchronization.
intrinsic constant
A constant that is supplied by Access, VBA, ADO, or DAO. These constants are available in the Object Browser by clicking globals in each of these libraries.
item
A unique element of data within a field. When a lower level of items is available for display in a PivotTable list or the field list, an expand indicator (+) appears beside the item.
Jet and Replication Objects
A set of automation interfaces that you can use to perform actions specific to Microsoft Jet databases. Using JRO, you can compact databases, refresh data from the cache, and create and maintain replicated databases.
keyboard handler
Code that determines and responds to keys or key combinations pressed by the user.
label
A control that displays descriptive text, such as a title, a caption, or instructions, on a form or report. Labels may or may not be attached to another control.
Layout view
A view in which you can make many types of design changes to forms and reports while viewing live data.
left outer join
An outer join in which all the records from the left side of the LEFT JOIN operation in the query's SQL statement are added to the query's results, even if there are no matching values in the joined field from the table on the right.
legend
A box that identifies the patterns or colors assigned to data series or categories in a chart.
library database
A collection of procedures and database objects that you can call from any application. In order to use the items in the library, you must first establish a reference from the current database to the library database.
link (tables)
An action that establishes a connection to data from another program so that you can view and edit the data in both the original program and in Access.
linked table
A table stored in a file outside the open database from which Access can access records. You can add, delete, and edit records in a linked table, but you cannot change its structure.
list index
The sequence of numbers for items in a list, starting with 0 for the first item, 1 for the second item, and so on.
local object
A table, query, form, report, macro, or module that remains in the replica or Design Master in which it was created. Neither the object nor changes to the object are copied to other members in the replica set.
local replica
A replica that exchanges data with its hub or a global replica but not with other replicas in the replica set.
locale
The set of information that corresponds to a given language and country.
locked
The condition of a record, recordset, or database that makes it read-only to all users except the user currently modifying it.
Lookup field
A field, used on a form or report in an Access database, that either displays a list of values retrieved from a table or query, or stores a static set of values.
ACCDE file
An Access 2007 database (.accdb) file with all modules compiled and all editable source code removed.
Access database engine
The part of the Access database system that retrieves and stores data in user and system databases. The engine can be thought of as a data manager upon which database systems, such as Access, are built.
macro
An action or set of actions that you can use to automate tasks.
Macro Builder
The object tab in which you create and modify macros. You can start the Macro Builder from a variety of places, such as a form or report, or directly from the Create tab on the Ribbon.
macro group
A collection of related macros that are stored together under a single macro name. The collection is often referred to simply as a macro.
main form
A form that contains one or more subforms.
make-table query
A query (SQL statement) that creates a new table and then creates records (rows) in that table by copying records from an existing table or query results.
manual link
A link that requires you to take action to update your data after the data in the source document changes.
many-to-many relationship
An association between two tables in which one record in either table can relate to many records in the other table. To establish a many-to-many relationship, create a third table and add the primary key fields from the other two tables to this table.
marquee
Moving text that is used on a data access page to draw the user's attention to a specific page element, such as a headline or an important announcement. To place a marquee on a page, create a scrolling text control.
maximum record limit
To improve performance, you can specify the maximum number of records that will be retrieved from a Microsoft SQL Server database for a form or datasheet in an Access project.
MDE file
An Access 2003 or earlier database (.mdb) file with all modules compiled and all editable source code removed.
Memo data type
In an Access database, this is a field data type. Memo fields can contain up to 65,535 characters.
Microsoft Access data file
An Access database or Access project file. An Access 2007 database stores database objects and data in an .accdb file, and earlier versions of Access use the .mdb format. A project file does not contain data, and is used to connect to a Microsoft SQL Server database.
Microsoft Access database
A collection of data and objects (such as tables, queries, or forms) that is related to a particular topic or purpose.
Microsoft Access object
An object, defined by Access, that relates to Access, its interface, or an application's forms and reports. In addition, you can use a Microsoft Access object to program the elements of the interface used for entering and displaying data.
Microsoft Access project
An Access file that connects to a Microsoft SQL Server database and is used to create client/server applications. A project file doesn't contain any data or data-definition-based objects, such as tables and views.
Microsoft Data Engine
A client/server data engine that provides local data storage on a smaller computer system, such as a single-user computer or small workgroup server, and that is compatible with Microsoft SQL Server 6.5, SQL Server 7.0, and SQL Server 2000.
Microsoft SQL Server database
A database in Microsoft SQL Server, it consists of tables, views, indexes, stored procedures, functions, and triggers. You can connect an Access database to SQL Server data by using ODBC or by creating an Access project (*.adp) file.
module level
Describes any variable or constant declared in the Declarations section of a Visual Basic for Applications (VBA) module or outside of a procedure. Variables or constants declared at the module level are available to all procedures in a module.
module-level variable
A variable that is declared in the Declarations section of a Visual Basic for Applications (VBA) module by using the Private keyword. These variables are available to all procedures in the module.
money data type
In an Access project, a data type that stores monetary values in the range -922,337,203,685,477.5707 through 922,337,203,685,477.5807, with accuracy to a ten-thousandth of a monetary unit.
move handle
The large square that is displayed in the upper left corner of the selected control or control layout in Design view or Layout view. You can drag the handle to move the control or control layout to another location.
Move mode
The mode in which you can move a column in Datasheet view by using the left and right arrow keys.
multivalued field
A lookup field that can store more than one value.
multiuser (shared) database
A database that permits more than one user to access and modify the same set of data at the same time.
Name AutoCorrect
A feature that automatically corrects common side effects that occur when you rename forms, reports, tables, queries, fields, or controls on forms and reports. However, Name AutoCorrect cannot repair all references to renamed objects.
navigation buttons
The buttons that you use to move through records. These buttons are located in the lower left corner of the Datasheet view and Form view. The buttons are also available in Print Preview so that you can move through the pages of your document.
Navigation Pane
The pane that appears when you open an Access database or an Access project. The Navigation Pane displays the objects in the database, and can be customized to sort and group objects in different ways.
nchar data type
In an Access project, a fixed-length data type with a maximum of 4,000 Unicode characters. Unicode characters use 2 bytes per character and support all international characters.
normalize
To minimize the duplication of information in a relational database through effective table design. You can use the Table Analyzer Wizard to normalize your database.
ntext data type
In an Access project, a variable-length data type that can hold a maximum of 2^30 - 1 (1,073,741,823) characters. Columns with the ntext data type store a 16-byte pointer in the data row, and the data is stored separately.
Null
A value you can enter in a field or use in expressions or queries to indicate missing or unknown data. In Visual Basic, the Null keyword indicates a Null value. Some fields, such as primary key fields, can't contain a Null value.
null field
A field containing a Null value. A null field is not the same as a field that contains a zero-length string (" ") or a field with a value of 0.
Number data type
In an Access database, a field data type designed for numerical data that will be used in mathematical calculations. Use the Currency data type, however, to display or calculate currency values.
numeric data type
In an Access project, an exact numeric data type that holds values from -10^38 - 1 through 10^38 - 1. You can specify the scale (maximum total number of digits) and precision (maximum number of digits to the right of the decimal point).
nvarchar(n) data type
In an Access project, a variable-length data type with a maximum of 4,000 Unicode characters. Unicode characters use 2 bytes per character and support all international characters.
Object data type
A fundamental data type representing any object that can be recognized by Visual Basic. Although you can declare any object variable as type Object, it is best to declare object variables according to their specific types.
Object Dependencies pane
Shows objects that have a dependency on the selected object and also objects on which the selected object has dependencies.
object library
A file that contains definitions of objects and their methods and properties. The file that contains an object library typically has the file name extension .olb.
object type
A type of object exposed by a program through Automation; for example, Application, File, Range, and Sheet. Use the Object Browser in the Visual Basic Editor or refer to the program's documentation for a complete listing of available objects.
object variable
A variable that contains a reference to an object.
ODBC Connection String Builder
An Access tool that you can use to connect to an SQL database when you create a pass-through query. If you save the query, the connection string is stored with the query.
ODBC data source
Data and the information needed to access that data from programs and databases that support the Open Database Connectivity (ODBC) protocol.
ODBC database
A database for which an Open Database Connectivity (ODBC) driver — a driver that you can use for importing, linking to, or exporting data — is supplied.
ODBCDirect
A technology that allows you to access ODBC data sources directly by using DAO features that bypass the Microsoft Jet database engine.
OLE container
A program that contains a linked or embedded OLE object from another program. For example, if an OLE object in an Access database contains an Excel worksheet, Access is the OLE container.
OLE DB
A component database architecture that provides efficient network and Internet access to many types of data sources, including relational data, mail files, flat files, and spreadsheets.
OLE DB provider
A program in the OLE DB architecture that enables native access to data, instead of accessing data by using ODBC or IISAM drivers, which are external ways to access the data.
OLE object
An object supporting the OLE protocol for object linking and embedding. An OLE object from an OLE server (for example, a Windows Paint picture or an Excel worksheet) can be linked or embedded in a field, form, or report.
OLE Object data type
A field data type that you use for objects created in other programs that can be linked or embedded (inserted) in an Access database.
OLE server
A program or DLL that supplies a linked or embedded OLE object to another program. For example, if an OLE object in an Access database contains an Excel worksheet, Excel is the OLE server.
OLE/DDE link
A connection between an OLE object and its OLE server, or between a Dynamic Data Exchange (DDE) source document and a destination document.
one-to-many relationship
An association between two tables in which the primary key value of each record in the primary table corresponds to the value in the matching field or fields of many records in the related table.
one-to-one relationship
An association between two tables in which the primary key value of each record in the primary table corresponds to the value in the matching field or fields of one, and only one, record in the related table.
option button
A control, also called a radio button, that is typically used as part of an option group to present alternatives on a form or report. A user cannot select more than one option.
option group
A frame that can contain check boxes, toggle buttons, and option buttons on a form or report. You use an option group to present alternatives from which the user can select a single option.
outer join
A join in which each matching record from two tables is combined into one record in the query's results, and at least one table contributes all of its records, even if the values in the joined field don't match those in the other table.
owner
When security is being used, the user account that has control over a database or database object. By default, the user account that created a database or database object is the owner.
page (data storage)
A portion of the database file in which record data is stored. Depending on the size of the records, a page (4 KB in size) may contain more than one record.
page footer
Used to display page summaries, dates, or page numbers at the bottom of every page in a form or report. In a form, the page footer appears only when you print the form.
page header
Used to display a title, column headings, dates, or page numbers at the top of every page in a form or report. In a form, the page header appears only when you print the form.
parameter query
A query in which a user interactively specifies one or more criteria values. A parameter query is not a separate kind of query; rather, it extends the flexibility of a query.
partial replica
A database that contains only a subset of the records in a full replica. With a partial replica, you can set filters and identify relationships that define which subset of the records in the full replica should be present in the database.
pass-through query
An SQL-specific query you use to send commands directly to an ODBC database server. By using pass-through queries, you work directly with the tables on the server instead of the data being processed by the Access database engine.
permissions
A set of attributes that specifies what kind of access a user has to data or objects in a database.
persistent object
An object stored in the database; for example, a database table or QueryDef object. Dynaset-type or snapshot-type Recordset objects are not considered persistent objects because they are created in memory as needed.
personal ID
A case-sensitive alphanumeric string that is 4 to 20 characters long and that Access uses in combination with the account name to identify a user or group in an Access workgroup.
pessimistic
A type of locking in which the page containing one or more records, including the record being edited, is unavailable to other users when you use the Edit method, and remains unavailable until you use the Update method.
pi
A mathematical constant equal to approximately 3.1415926535897932.
PivotChart view
A view that shows a graphical analysis of data in a datasheet or form. You can see different levels of detail or specify the layout by dragging fields and items or by showing and hiding items in the drop-down lists for the fields.
PivotTable form
An interactive table that summarizes large amounts of data by using format and calculation methods that you choose. You can rotate its row and column headings to view the data in different ways, similar to an Excel PivotTable report.
PivotTable list
A Microsoft Office Web Component that is used to analyze data interactively on a Web page. Data displayed in a row and column format can be moved, filtered, sorted, and calculated in ways that are meaningful for your audience.
PivotTable view
A view that summarizes and analyzes data in a datasheet or form. You can use different levels of detail or organize data by dragging the fields and items or by showing and hiding items in the drop-down lists for the fields.
plus pointer
The pointer that appears when you move the pointer to the left edge of a field in a datasheet. When the plus pointer appears, you can click to select the entire field.
pop-up form
A form that stays on top of other windows. A pop-up form can be modal or modeless.
primary key
One or more fields (columns) whose values uniquely identify each record in a table. A primary key cannot allow Null values and must always have a unique index. A primary key is used to relate a table to foreign keys in other tables.
primary table
The "one" side of two related tables in a one-to-many relationship. A primary table should have a primary key and each record should be unique.
private procedure
A Sub or Function procedure is declared as private by using the Private keyword in a Declare statement. Private procedures are available for use only by other procedures within the same module.
procedure
A sequence of declarations and statements in a module that are executed as a unit. Procedures in a Visual Basic for Applications (VBA) module include both Sub and Function procedures.
procedure level
Describes any variables or constants declared within a procedure. Variables and constants declared within a procedure are available to that procedure only.
procedure-level variable
A variable that is declared within a procedure. Procedure-level variables are always private to the procedure in which they're declared.
project
The set of all code modules in a database, including standard modules and class modules. By default, the project has the same name as the database.
property sheet
A pane that is used to view or modify the properties of various objects such as tables, queries, fields, forms, reports, data access pages, and controls.
pseudo index
A dynamic cross-reference of one or more table data fields (columns) that permits an ODBC table (server table) without a unique index to be edited.
public variable
A variable that you declare with the Public keyword in the Declarations section of a Visual Basic for Applications (VBA) module. A public variable can be shared by all the procedures in every module in a database.
publication
In an Access project, a publication can contain one or more published tables or stored procedure articles from one user database. Each user database can have one or more publications. An article is a grouping of data replicated as a unit.
publish
To save a database to a document management server, such as a server running Windows SharePoint Services.
query
A question about the data stored in your tables, or a request to perform an action on the data. A query can bring together data from multiple tables to serve as the source of data for a form or report.
Query window
A window in which you work with queries in Design view, Datasheet view, SQL view, or Print Preview.
QueryDef
a stored definition of a query in an Access database, or a temporary definition of a query in an ODBCDirect workspace.
real data type
In an Access project, an approximate numeric data type with seven-digit precision. It can hold positive values from approximately 1.18E - 38 through 3.40E + 38, negative values from approximately -1.18E - 38 through -3.40E + 38, or zero.
record navigation control
A control used on a data access page to display a record navigation toolbar. In a grouped page, you can add a navigation toolbar to each group level. You can customize the record navigation control by changing its properties.
record number box
A small box that displays the current record number in the lower-left corner in Datasheet view and Form view. To move to a specific record, you can type the record number in the box, and press ENTER.
record selector
A small box or bar to the left of a record that you can click to select the entire record in Datasheet view and Form view.
record source
The underlying source of data for a form, report, or data access page. In an Access database, it can be a table, query, or SQL statement. In an Access project, it can be a table, view, SQL statement, or stored procedure.
recordset
The collective name given to table-, dynaset-, and snapshot-type Recordset objects, which are sets of records that behave as objects.
referenced database
The Access database to which the user has established a reference from the current database. The user can create a reference to a database and then call procedures within standard modules in that database.
referencing database
The current Access database from which the user has created a reference to another Access database. The user can create a reference to a database and then call procedures within standard modules in that database.
referential integrity
Rules that you follow to preserve the defined relationships between tables when you add, update, or delete records.
refresh
In an Access database, to redisplay the records in a form or datasheet to reflect changes that other users have made. In an Access project, to rerun a query underlying the active form or datasheet in order to reflect changes to records.
relationship
An association that is established between common fields (columns) in two tables. A relationship can be one-to-one, one-to-many, or many-to-many.
Relationships object tab
An object tab in which you view, create, and modify relationships between tables and queries.
relative or inline positioning
Places the element in the natural HTML flow of the document but offsets the position of the element based on the preceding content.
repaint
To redraw the screen. The Repaint method completes any pending screen updates for a specified form.
replica
A copy of a database that is a member of a replica set and can be synchronized with other replicas in the set. Changes to the data in a replicated table in one replica are sent and applied to the other replicas.
replica set
The Design Master and all replicas that share the same database design and unique replica set identifier.
replica set topology
The order in which changes are propagated from replica to replica. Topology determines how quickly changes in another replica appear in your replica.
replication
The process of copying a database so that two or more copies can exchange updates of data or replicated objects. This exchange is called synchronization.
An Access database object that that you can print containing information that is formatted and organized according to your specifications. Examples of reports are sales summaries, phone lists, and mailing labels.
report footer
A report section that is used to place information that normally appears at the bottom of the page, such as page numbers, dates, and sums.
report header
A report section that is used to place information (such as a title, date, or report introduction) at the beginning of a report.
report module
A module that includes Visual Basic for Applications (VBA) code for all event procedures triggered by events occurring on a specific report or its controls.
Report object tab
An object tab in which you work with reports in Design view, Layout Preview, or Print Preview.
report selector
The box where the rulers meet in the upper-left corner of a report in Design view. Use the box to perform report-level operations, such as selecting the report.
report snapshot
A file (.snp file name extension) that contains a high-fidelity copy of each page of an Access report. It preserves the two-dimensional layout, graphics, and other embedded objects of the report.
requery
To rerun a query underlying the active form or datasheet in order to reflect changes to the records, display newly added records, and eliminate deleted records.
reserved word
A word that is part of a language, such as Visual Basic. Reserved words include the names of statements, predefined functions and data types, methods, operators, and objects..
rollback
The process of ending or cancelling a pending transaction without saving the changes.
row area
The part of PivotTable view that contains row fields.
row field
A field in the row area of PivotTable view. Items in row fields are listed down the left side of the view. Inner row fields are closest to the detail area; outer row fields are to the left of the inner row fields.
row selector
A small box or bar that, when clicked, selects an entire row in table or macro Design view or when you sort and group records in report Design view.
section
A part of a form or report, such as a header, footer, or detail section.
section header
The horizontal bar above a form or report section in Design view. The section bar displays the type and name of the section. Use it to access the section's property sheet.
section selector
The box on the left side of a section bar when an object is open in Design view. Use the box to perform section-level operations, such as selecting the section.
secure workgroup
An Access workgroup in which users log on with a user name and password and in which access to database objects is restricted according to permissions granted to specific user accounts and groups.
seed
An initial value used to generate pseudorandom numbers. For example, the Randomize statement creates a seed number used by the Rnd function to create unique pseudorandom number sequences.
select query
A query that asks a question about the data stored in your tables and returns a result set in the form of a datasheet, without changing the data.
selection rectangle
The rectangle formed by the currently selected rows (records) and columns (fields) within Datasheet view.
self-join
A join in which a table is joined to itself. Records from the table are combined with other records from the same table when there are matching values in the joined fields.
separator
A character that separates units of text or numbers.
series field
A field that is displayed in the series area of a chart and that contains series items. A series is a group of related data points.
series point
An individual data value that is plotted in a chart and represented by a column, bar, line, pie or doughnut slice, or other type of data marker.
Server Filter By Form
A technique that uses a version of the current form or datasheet with empty fields in which you can type values you want the filtered records to contain. The data is filtered by the server before it is retrieved from the database.
server-generated HTML
An Active Server Pages (ASP) or IDC/HTX file that is output from a table, query, or form, connected to an ODBC data source, and processed by the Internet Information Server to dynamically create read-only HTML files.
server-generated HTML: An Active Server Pages
session
A sequence of operations performed by the Access database engine that begins when a user logs on and ends when the user logs off. All operations during a session form one transaction scope and are subject to the user's logon permissions.
smalldatetime data type
In an Access project, a date and time data type that is less precise than the datetime data type. Data values range from January 1, 1900, through June 6, 2079, to an accuracy of one minute.
smallint data type
In an Access project, a data type of 2 bytes (16 bits) that stores whole numbers in the range of -2^15 (-32,768) through 2^15 - 1 (32,767).
smallmoney data type
In an Access project, a data type that stores monetary values from -214,748.3648 to 214,748.3647, with accuracy to a ten-thousandth of a monetary unit. When smallmoney values are displayed, they are rounded up to two decimal places.
snapshot
A static image of a set of data, such as the records displayed as the result of a query. Snapshot-type Recordset objects can be created from a base table, a query, or another recordset.
Snapshot Viewer
A program that you can use to view, print, or mail a snapshot, such as a report snapshot. Snapshot Viewer consists of a stand-alone executable program, a Snapshot Viewer control (Snapview.ocx), and other related files.
Snapshot Viewer control
An ActiveX control (Snapview.ocx) that you use to view a snapshot report from Microsoft Internet Explorer 3.0 or later, or from any program that supports ActiveX controls, such as Access or Microsoft Visual Basic.
SQL database
A database that is based on Structured Query Language (SQL).
SQL string/statement
An expression that defines an SQL command, such as SELECT, UPDATE, or DELETE, and includes clauses such as WHERE and ORDER BY. SQL strings/statements are typically used in queries and in aggregate functions.
sql variant data type
In an Access project, a data type that stores values of several data types, except for text, ntext, image, timestamp, and sql_variant data types. The sql variant data type is used in a column, parameter, variable, or return value of a user-defined function.
SQL view
An object tab that displays the SQL statement for the current query or that is used to create an SQL-specific query (union, pass-through, or data definition). When you create a query in Design view, Access constructs the SQL equivalent in SQL view.
SQL-specific query
A query that consists of an SQL statement. Subqueries and pass-through, union, and data-definition queries are SQL-specific queries.
standard deviation
A parameter that indicates the way in which a probability function is centered around its mean and that is equal to the square root of the moment in which the deviation from the mean is squared.
standard module
A Visual Basic for Applications (VBA) module in which you can place Sub and Function procedures that you want to be available to other procedures throughout your database.
stored procedure
A precompiled collection of SQL statements and optional control-of-flow statements that is stored under a name and processed as a unit. The collection is stored in an SQL database and can be run with one call from a program.
string delimiter
Text characters that set apart a string embedded within a string. Single quotation marks (') and double quotation marks (") are string delimiters.
Sub procedure
A Visual Basic for Applications (VBA) procedure that carries out an operation. Unlike a Function procedure, a Sub procedure doesn't return a value. You begin a Sub procedure with a Sub statement and end it with an End Sub statement.
subdatasheet
A datasheet that is nested within another datasheet and that contains data related or joined to the first datasheet.
subform
A form contained within another form or a report.
subform/subreport control
A control that displays a subform in a form or a subform or a subreport in a report.
subquery
An SQL SELECT statement that is inside another select or action query.
subreport
A report that is contained within another report.
subscribe
To agree to receive a publication in an Access database or an Access project. A subscriber database subscribes to replicated data from a publisher database.
subscription
The database that receives tables and data replicated from a publisher database in an Access project.
synchronization
The process of updating two members of a replica set by exchanging all updated records and objects in each member. Two replica set members are synchronized when the changes in each have been applied to the other.
sysname data type
In an Access project, a special system-supplied, user-defined data type that is used for table columns, variables, and stored procedure parameters that store object names.
system object
Database objects that are defined by the system, such as the table MSysIndexes, or by the user. You can create a system object by naming the object with USys as the first four characters in the object name.
tab control
A control that you can use to construct a single form or dialog box that contains several pages, each with a tab, and each containing similar controls, such as text boxes or option buttons. When a user clicks a tab, that page becomes active.
table
A database object that stores data in records (rows) and fields (columns). The data is usually about a particular category of things, such as employees or orders.
table data type
In an Access project, a special data type that is used to store a result set in a local variable or return value of a user-defined function for later processing. It can be used in place of a temporary table stored in the tempdb database.
Table object tab
In an Access database, an object tab in which you work with tables in Design view or Datasheet view.
table properties
In an Access database, attributes of a table that affect the appearance or behavior of the table as a whole. Table properties are set in table Design view, as are field properties.
text box
A control, also called an edit field, that is used on a form or report to display text or accept data entry. A text box can have a label attached to it.
text data type
In an Access project, a variable-length data type that can hold a maximum of 2^31 - 1 (2,147,483,647) characters; default length is 16.
Text data type
In an Access database, this is a field data type. Text fields can contain up to 255 characters or the number of characters specified by the FieldSize property, whichever is less.
timestamp data type
In an Access project, a data type that is automatically updated every time a row is inserted or updated. Values in timestamp columns are not datetime data, but binary(8) or varbinary(8), indicating the sequence of data modifications.
tinyint data type
In an Access project, a data type of 1 byte (8 bits) that stores whole numbers in the range of 0 through 255.
toggle button
A control that is used to provide on/off options on a form or report. It can display either text or a picture, and can be stand-alone or part of an option group.
toolbox
A set of tools that is available in Design view for adding controls to a form or report.
ToolTips
Brief descriptions of the names of commands and buttons on the Ribbon. A ToolTip is displayed when the mouse pointer rests on these commands and buttons.
topology
The order in which changes are propagated from replica to replica. Topology is important because it determines how quickly changes in another replica appear in your replica.
total field
A field that summarizes data from the underlying record source. A total field can use a summary function, such as Sum or Count, or use an expression to calculate summary values.
Total row
A row on a datasheet that displays your choice of summary information for each field, based on the type of data in the field.
totals query
A query that displays a summary calculation, such as an average or sum, for values in various fields from a table or tables. A totals query is not a separate kind of query; rather, it extends the flexibility of select queries.
transaction
A series of changes made to a database's data or schema. If any elements of the transaction fail, the entire transaction fails, and data is "rolled back."
trigger
A special form of a stored procedure that is carried out automatically when data in a specified table is modified. Triggers are often created to enforce referential integrity or consistency among logically related data in different tables.
unbound control
A control that is not connected to a field in an underlying table, query, or SQL statement. An unbound control is often used to display informational text or decorative pictures.
unbound form or report
A form or report that is not connected to a record source such as a table, query, or SQL statement. (The form's or report's RecordSource property is blank.)
unbound object frame
A control that you place on a form or report to contain an unbound object. An unbound object is an object, such as a picture, whose value is not derived from data stored in a table.
union query
A query that uses the UNION operator to combine the results of two or more select queries.
unique index
An index defined by setting a field's Indexed property to Yes (No Duplicates). A unique index will not allow duplicate entries in the indexed field. Setting a field as the primary key automatically defines the field as unique.
uniqueidentifier data type
In an Access project, a 16-byte globally unique identifier (GUID).
update
To accept changes to data in a record. The changes are saved in the database when you move to another record on a form or datasheet, or when you explicitly save the record.
update query
An action query (SQL statement) that changes a set of records according to criteria (search conditions) that you specify.
updateable snapshot
A type of recordset that works efficiently in a client/server environment by caching data on the client and minimizing round trips to the server to access and update data.
user account
An account identified by a user name and personal ID (PID) that is created to manage the user's permissions to access database objects in an Access workgroup.
user defined data type
In a Microsoft SQL Server database, a definition of the type of data a column can contain. It is defined by the user, and based on existing SQL Server data types. Rules and defaults can only be bound to user-defined data types.
user defined type
In Visual Basic for Applications (VBA), any data type defined by using the Type statement. User-defined data types can contain one or more elements of any data type. Arrays of user-defined and other data types are created using the Dim statement.
user-defined collection
A collection that you create by adding objects to a Collection object. Items in a collection defined by the Collection object are indexed, beginning with 1.
user-defined function
A query that takes input parameters and returns a result, similar to a stored procedure. Types: scalar (multistatement; returns one value), inline (one statement; an updateable table value), and table (multistatement; table value).
user-defined object
A custom object that is defined in a form or report class module. In a class module, you can create properties and methods for a new object, create a new instance of the object, and manipulate the object by using those properties and methods.
user-level security
When using user-level security in an Access database, a database administrator or an object's owner can grant individual users or groups of users specific permissions to tables, queries, forms, reports, and macros.
Users group
The group account that contains all user accounts. Access automatically adds user accounts to the Users group when you create them.
validation
The process of checking whether entered data meets certain conditions or limitations.
validation rule
A property that defines valid input values for a field or record in a table, or for a control on a form. Access displays the message specified in the ValidationText property when the rule is violated.
varbinary data type
In an Access project, a variable-length data type with a maximum of 8,000 bytes of binary data.
varchar
In an Access project, a variable-length data type with a maximum of 8,000 ANSI characters.
variance
The square of the standard deviation. It is a measure of the amount by which all values in a group vary from the average value of the group.
variant expression
Any expression that can evaluate to numeric, string, or date data, in addition to the special values Empty and Null.
view
In an Access project, a type of query that is a virtual table based on an SQL SELECT statement. For example, a view may contain only 3 out of 10 available columns in a join of two tables, in order to limit access to certain data.
visibility
A property of a replica that indicates which members of the replica set it can synchronize with and which conflict resolution rules apply. Replicas fall into three visibility types: global, local, and anonymous.
WHERE clause
The part of an SQL statement that specifies which records to retrieve.
wildcard characters
Characters used in queries and expressions to include all records, file names, or other items that begin with specific characters or that match a certain pattern.
XML attribute
Information that is added to a tag to provide more information about the tag, such as <ingredient quantity="2"units="cups">flour</ingredient>. In this example, quantity and units are attributes.
XML element
Information that is delimited by a start and end tag in an Extended Markup Language (XML) document. An example of an XML element is <LastName>Davolio</LastName>.
XML entities
Combinations of characters and symbols that replace other characters when an XML document is parsed, usually those that have other meanings in XML. For example, < represents the < symbol, which is also the opening bracket for a tag.
Yes/No data type
A field data type that you use for fields that will contain only one of two values, such as Yes or No and True or False. Null values are not allowed.
zero-length string
A string that contains no characters. You can use a zero-length string to indicate that you know no value exists for a field. You enter a zero-length string by typing two double quotation marks with no space between them (" "). | https://support.microsoft.com/en-us/office/access-glossary-29ab26b7-1f36-4da4-9e75-479f8e6e3c35?correlationid=84825415-a018-48a5-8ca8-2f69849d44c7&ui=en-us&rs=en-us&ad=us | CC-MAIN-2020-50 | refinedweb | 14,027 | 61.77 |
How.
Everything runs on a different thread except our code.
At first glance, this sentence doesn’t seem to make a lot of sense. Isn’t everything we execute technically “our code”? Well, yes and no. Lets take a look at two examples of synchronous and asynchronous implementations of the same functionality.
Synchronous implementation (python) :
import requests r = requests.get('') print r.text print "I come after the request"
Async implementation (js) :
var request = require('request'); request('', function (error, response, body) { console.log(body); }) console.log('I come after the request');
Now, all the above code runs on the same thread, no doubt about it. But what were missing is that the
request and
requests libraries, make http requests that go to other servers. The time spent in sending the request, processing it server side, and returning the response, is not spent in our thread. Thats what the web server you sent the request to does.
In our python implementation, we wait for all these processes to complete and receive the response before moving on to executing the next line of code. The async philosophy adopted by javascript and Node.js is fundamentally different in this regard. Instead of waiting for the response before executing the next bit of code, we declare what we want to happen once we receive our response, and move on to the next bit of code as usual.
This is why
"I come after the request" will always get printed to the console after the response in the case of our python code, and always get printed before the response for our javascript code[1].
What good does any of this do me?
Both the snippets of code are exactly similar in their functionality :
import requests==
var request = require('request');
r = requests.get('')==
request('', ... )
print r.text==
console.log(body);
print "I come after the request"==
console.log('I come after the request');
Let us assume, for the sake of experimentation, that each of the 4 snippets of code above take ~10ms to execute. Since we are only here to see the power of async, we are not going to take the raw execution speed of either language into consideration, and assuming the synchronous parts of both examples to have the same execution time (of 10ms). We will also take two cases of waiting time into consideration, one of 20ms, and one of 5ms.
Case 1 (Waiting time = 20ms)
With synchronous execution :
With asynchronous execution :
Snippet 4 doesn’t have to wait for our response to arrive in order to execute, but snippet 3 does. Our javascript code handles this by defining tasks that need to wait inside the callback and other tasks outside of it. In the case of our python example, all code after we send the request is blocked until the response arrives.
This gives us a *net loss of 10ms* in this case for the synchronous implementation.
Case 2 (Waiting time = 5ms)
With synchronous execution :
With asynchronous execution :
Synchronous execution with a smaller waiting time doesn’t look much different from the last picture, but the asynchronous timing diagram is pretty interesting. We see that snippet 4 starts execution as usual during waiting time, but snippet 3 doesnt execute right after the waiting time is over. This is because snippet 3 and snippet 4 are running on the same thread and hence snippet 3 has to wait for 4 to finish before it can start. This is a much better illustration of what it means to be single threaded and asynchronous.
Final thoughts
If async is so obviously the correct thing to do, then why should we bother with synchronous programming?
The first thing that stands out in the javascript code snippet is that it’s much less simple than the corresponding python snippet, and so takes a bit more time to read, understand, and develop. In fact, there are many articles and blog posts dedicated to managing async code, because without proper management, it can all get out of hand pretty quickly.
For rapid prototypes, or in cases where speed and timing is not the main concern, going the synchronous way can be more productive. On the other hand, if you’re planning to build an application with a lot of I/O and networking tasks, or with a lot of users, then the power of async really starts to shine.
Although async is not embedded in pythons “philosophy”, like it is with NodeJs, there are many libraries which let you leverage event driven and async programming, like the Twisted library.
*[1] Edit - Javascript always finishes the currently executing function first. Thanks @Twitchard for the correction.* | https://www.sohamkamani.com/blog/2016/03/14/wrapping-your-head-around-async-programming/ | CC-MAIN-2019-47 | refinedweb | 776 | 60.35 |
Visual Studio 2013 Preview has been out for a while now so I thought I should announce the new goodies in the product for T4 this time around. As the T4 engine is fairly mature now we focused on a couple of scenarios that have been blocked or tricky for customers. I’m sure you’ll agree they are good ones.
1. Enable fine-grained template reuse with a new ‘once’ option on the <#@ include #> directive.
This feature makes it really easy to build up a library of reusable T4 snippets that you can include at will without worrying that some other snippet has already included them. For example, I’ve now got a library of very fine-grained snippets that deal with template processing and C# generation. In turn, these are used by some more task-specific utilities such as generating exceptions, which I can then use from any more application-specific template. You can see in this dependency graph that my indentation helpers are used all over the place. Now I don’t have to worry about clashes.
Customers ask me a lot about strategies for building reusable template libraries and the ‘once’ feature is the last major unblocker to a smooth experience for big libraries. This feature works regardless of the host in use. Here’s the syntax:
<#@ include file=“myinterestingsnippet.t4” once=”true” #>
2. Enable project-relative assembly references and includes across IDE and msbuild.
Until now, it’s been awkward to create templates that reference assemblies from standard project-relative directories and then transform them in both the IDE and from msbuild. Typically it required environment variables, which most people hate! We’ve fixed that with this feature. You can now use project properties with include and assembly directives. This feature works in the standard IDE host and in the msbuild host. Here’s an example – imagine we have some helper code in an assembly called myLib.dll stored in a standard ‘libs’ directory. Something magnificent, like this:
namespace MyLib
{
public static class MyClass
{
public static string MyMethod()
{
return "World";
}
}
}
Now let’s use that helper from a template – in the IDE we could use macros like $(SolutionDir), but those don’t work in msbuild, so we’ll use a project variable instead:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="$(libDir)\MyLib.dll" #>
<#@ output extension=".txt" #>
Hello <#= MyLib.MyClass.MyMethod() #>
Of course, we’ll need to define the variable in our project file by adding a snippet like this:
<PropertyGroup>
<libDir>$(MSBuildProjectDirectory)\..\libs</libDir>
</PropertyGroup>
At this point, the template should work in the IDE, but we need to take one more step before it works in msbuild. We need to let the T4 msbuild task know which variables we’re using. We add one final snippet to do that:
<ItemGroup>
<T4ParameterValues Include="libDir">
<Value>$(libDir)</Value>
</T4ParameterValues>
</ItemGroup>
3. Standard host used in ASP.Net scaffolding
This isn’t strictly a T4 feature, but it’s great news. The very cool new ASP.Net scaffolding feature uses the standard VS T4 host, so you can use the full power of T4, and any include libraries you have when building scaffolding templates.
4. Tidy up after very spendy templates with CleanupBehavior directive.
Sometimes templates get big. Or crufty. Or both. Or they load a bajillion assemblies to do their work. This can bloat up your IDE’s memory footprint or lock assemblies in memory. Now there’s a great big hammer to solve this problem. Add the following line to your template and the appdomain it runs in will get blown away after every run.
<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #>
This defeat’s T4’s normal caching behavior, so it slows things down a bit, but you get a spangly clean IDE every time. This one only runs in the VS IDE host.
5. A bunch of small bugs, but that goes without saying.
Enjoy the release.
T4 is a powerful tool but why work so hard. Powershell can build your templates instead. Plus it has a debugger so you can step thru your code to make sure all is well. Since it is Powershell you can put in rules to where your models are. | https://blogs.msdn.microsoft.com/garethj/2013/08/28/whats-new-in-t4-for-visual-studio-2013/ | CC-MAIN-2018-30 | refinedweb | 702 | 65.52 |
painter.drawline() , overlapping opacity problems with 100% opaque pen.
Hello guys
I'm drawing 2 lines on top of each other, 1 long and 1 a bit shorter. I draw them on a QGraphicsItem.
When I zoom out in my scene, I can see the ovelapping as if the longer line has some opacity, allowing me to see the shorter line below it. But if I zoom back, it looks all good.
The color of my line is (180, 180, 180, 255) so no opacity.
My line has a width of 1 pixel.
My first guess is since 1px at no zoom is 1px, when I zoom out, my 1px becomes less than 1px (problem) but when I zoom in, it becomes more than 1px (so all good).
Is there a solution to fix that ?
Thx ! :)
Is it due to antialiasing effects perhaps?
from the view ?
Not sure what optimisation flags you are setting on the graphics view but one possibility might be...
QGraphicsView::DontAdjustForAntialiasing
or render hints set on the graphics view like...
QPainter::HighQualityAntialiasing
and I guess you read the docs here and here.
Remember, all drawing uses the painter in the end unless you are using only OpenGL for your drawing.
I hope this helps you find your way to a solution :-)
So I ve tried to turn off all the anitialiasing setting that I have + added the "DontAdjustForAntialiasing", True), True) self.setViewportUpdateMode(QtWidgets.QGraphicsView.FullViewportUpdate)
I ve also tried
self.setRenderHint(QtGui.QPainter.NonCosmeticDefaultPen, False)
But I still have the same issue ... looks like it might not be aliasing related.
hmm... It might be helpful to see a screen shot of the results you are seeing.
As you can see we see it on the small one but not on the zoomed in one.
Yes, i can see what you mean about the smaller scale image. Just as a matter of interest, what does the smaller one look like when you zoom the pixels of your screen to the extent that you can see each pixel clearly?
As opposed to zooming it with the graphics view.
What do you mean ? When it's at scale 1:1 ?
The problem occurs as soon as on my screen it becomes less than 1 px
Sorry, I guessed you might not get what I meant.
What I meant was it would be nice to see an enlarged screen shot of your 1:1 display of it. i.e. can you apply a magnifying glass to the small image on your screen so one can see what the actual pixels look like?
this one is 400%
Thank you.
Well, I can see evidence of antialiasing on the line ends and the circles even though you have turned the antialiasing features off. I expect to see them on the text because you left the text antialiasing settings on. Horizontal lines look darker (more transparent?) and corners look lighter because they are drawn twice. Am I seeing this correctly?
So, either your antialias settings are getting changed at the last moment or your display device has a hardware antialiasing capability or it is actually getting that way due to windows scaling??
Other than that I am out of ideas. I use the graphics view in a similar fashion with the same settings as you and do not see that kind of thing. However, I do see exactly that kind of thing when I turn antialiasing on (the user can switch it on and off in my application).
My bad, this screenshot has the antialiasing on. Will do it again tomorrow with antialiasing off.
They can turn it too in mine but i feel like it shouldn't happen even with antialiasing on
OK.
If you have issues with how the antialiasing is implemented I suggest you send your questions to the interest mailing list here and try to catch the eye of a developer who knows about the details., False), False) self.setViewportUpdateMode(QtWidgets.QGraphicsView.FullViewportUpdate)
even with those settings, that's what I get
This is not antialiasing related. Somehow lines get some opacity.
Well that is strange isn't it.
Maybe you could put the code that draws that into a minimal example app so we can all try to reproduce it.
Okay, I wrote a quick example with the same view settings.
It looks fine at scale 1 and same problem when zooming out.
from PySide2 import QtGui, QtCore, QtWidgets class TestView(QtWidgets.QGraphicsView): def __init__(self, parent=None): super(TestView, self).__init__(parent) self.setOptimizationFlag(QtWidgets.QGraphicsView.DontAdjustForAntialiasing) self.setRenderHint(QtGui.QPainter.Antialiasing, False) self.setRenderHint(QtGui.QPainter.HighQualityAntialiasing, False) self.setRenderHint(QtGui.QPainter.NonCosmeticDefaultPen, False) self.setViewportUpdateMode(QtWidgets.QGraphicsView.FullViewportUpdate) self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) def wheelEvent(self, event): self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) inFactor = 1.15 outFactor = 1 / inFactor if event.delta() > 0: zoomFactor = inFactor else: zoomFactor = outFactor self.scale(zoomFactor, zoomFactor) class TestItem(QtWidgets.QGraphicsItem): def __init__(self): super(TestItem, self).__init__() def boundingRect(self): return QtCore.QRect(0, 0, 200, 400) def shape(self): path = QtGui.QPainterPath() path.addRect(self.boundingRect()) return path def paint(self, painter, option, widget): brush = QtGui.QBrush(QtGui.QColor(70, 70, 70, 255)) painter.setBrush(brush) painter.drawRoundedRect(0, 0, 200, 400, 20, 20) pen = QtGui.QPen(QtGui.QColor(200, 200, 200, 255)) pen.setWidth(1) painter.setPen(pen) painter.drawLine(50, 50, 50, 300) painter.drawLine(50, 80, 50, 200) painter.drawLine(50, 80, 150, 80) view = TestView() scene = QtWidgets.QGraphicsScene() view.setScene(scene) item = TestItem() scene.addItem(item) view.show()
Great, i will give it a try when I can make a bit of time :-)
BTW, I don't use python so I will be testing it with C++. Someone else might pitch in and try it with python for you.
So which Version of Qt are you using for this? I assume you are using Windows right?
I'm using Qt5 I think it's 5.6.1 and yes I'm on windows, will give it a try on MacOS
I've tried in Qt 4.8.2 and it's exactly the same
Hello @Goffer. I made a test app with a QGraphicsView using the same settings as you here are the results so far.
Note: i did not bother to sub class a graphics item yet as I don't think it makes a difference.
I don't see those artifacts at 1:1 zoom scale.
zoom scale 1.0
I do see those artifacts at less than a 1:1 zoom scale. I guess this is because the line thickness of on device pixel is now trying to show line a less than one physical device pixel width?? I think this is what the paint engine does when the device to logical pixels don't match, but I am no expert on that. You need to discuss those details with the developers.
zoom scale 0.5
I used Qt 5.8.0
This is on macOS High Sierra 10.13
I will try it on Windows later and let you know the results.
Hope that helps :-)
Sorry but my images links are not showing up?? you will have to click on the links to see them I guess :-)
I've tried to make the pen cosmetic by setting the width to 0. That way the line should always have the same width on screen no matter the zoom factor. And the problem still occurs.
hello again @Goffer
I tried my test project on Windows and got the same results. It looks like we are stuck with that behaviour.
You could always submit it as a bug.
I ve sent it to the interest mailing list as you suggested. Will see what happens, how could I submit it as a bug ?
You can find out how to do that and much more here
also the wiki is a good place to look around for information.
The developers mailing list is here.
Good luck :-)
I've submited the bug ticket.
what is the number of the bug report?
OK, got the link and voted for it.
lets see what happens ;)
OK. I added my comments and zip file to the bug report.
thx ! hoppefully this will help, what do you think of the current "solution" ? | https://forum.qt.io/topic/84154/painter-drawline-overlapping-opacity-problems-with-100-opaque-pen | CC-MAIN-2017-51 | refinedweb | 1,391 | 68.06 |
2009/11/23 spir <[email protected]>: > Matthew Wild <[email protected]> wrote: > >> 2009/11/23 spir <[email protected]>: >> > Hello, >> > >> > the bottom of the file put "return __export", it will be used as >> the return value from require, and saved in package.loaded[modulename] >> for future calls. > > Great! That's exactly what I was looking for. (Didn't think, though, it could be _such_ straightforward). > By the way, does this means that require (or behing loadfile, or even load) will regard the whole module like a func? maybe taking the module's global namespace as return value if none explicitely defined? > By default the module's global namespace is *the* global namespace, so if you just define global functions and do nothing else then they are accessible anyway, as globals. Typically people use module(), which creates a new environment (namespace as you call it), and module() also sets package.loaded[modulename] to this environment, so that require() will return it now and in future (still returning something can overwrite package.loaded[modulename] though). If you don't call module(), don't set package.loaded[modulename] and don't return anything then require() will just return true. Matthew | http://lua-users.org/lists/lua-l/2009-11/msg00877.html | CC-MAIN-2017-17 | refinedweb | 200 | 58.89 |
In Java I rarely used generic data types, and rarely thought about types much at all. To demonstrate why, I’ll go back to one of my favorite examples, writing code for a pizza store.
Please note that my Java code my not be 100% correct. I haven’t put this in an IDE or tried to compile it. I’m just trying to quickly demonstrate the OOP approach.
To start modeling a point-of-sales application for a pizza store, I’ll first need my usual enumerations:
enum Topping { Cheese, Pepperoni, BlackOlives } enum CrustSize { Small, Medium, Large } enum CrustType { Regular, Thin, Thick }
Given those, let’s create a
Pizza class. But before doing that, let’s list the attributes and behaviors of an OOP pizza. The attributes are basically what I just listed with those enums:
- Crust size
- Crust type
- Types of toppings
The behaviors correspond to those attributes:
- Add topping
- Remove topping
- Set crust size
- Set crust type
If I also kept price-related information, a pizza could also calculate its own price, but since the toppings and crust attributes don’t carry price information with them, that’s pretty much all of the behaviors of a
Pizza.
Having gone through this exercise several times before, I know that I want all of the food-related items in a pizza store — pizza, breadsticks, soda, etc. — to extend a base
Product class:
public interface Product {}
In the real world a
Product will have attributes like cost and potentially a sales price associated with it, but for the purposes of this exercise I’ll just leave it as a marker interface like that.
Given that, and the attributes and behaviors of a pizza, my initial code for a Java/OOP
Pizza class looks like this:
public class Pizza implements Product { private List<Topping> toppings = new ArrayList<>(); private CrustSize crustSize; private CrustType crustType; public Pizza(CrustSize crustSize, CrustType crustType) { this.crustSize = crustSize; this.crustType = crustType; } }
That code is followed by a series of getter and setter methods that have these type signatures:
public CrustSize getCrustSize() public CrustType getCrustType() public List<Topping> getToppings() public void setCrustSize(CrustSize crustSize) public void setCrustType(CrustType crustType) public void setToppings(List<Topping> toppings)
The thing to notice here is that this is all very simple code. The getters don’t take any input parameters and they return basic data types, and the setters all return
void. I wrote Java code like this for more than 12 years.
In fact, if I wrote more code, such as for an
Order class, you’d see that the pattern is the same, all very simple code:
public class Order { private List<Product> lineItems = new ArrayList<>(); public Order() {} public void addItem(Product p) public void removeItem(Product p) public List<Product> getItems() public String getPrintableReceipt() public BigDecimal getTotalPrice() }
The closest I get to using generic types in that code is this:
private List<Topping> toppings = new ArrayList<>(); private List<Product> lineItems = new ArrayList<>();
Summary, Part 1
To summarize what you saw in these examples:
- My Java/OOP “pizza” code was very simple, with no generic types
- A lot of methods return
void
- A lot of methods have no input parameters
- I always use mutable data structures
Summary, Part 2
There are a few other things to say about that code, and bear in mind, I’m only talking about my own code.
(1) I didn’t realize it when I was writing Java/OOP code, but all of those methods that return
void and take no input parameters tend to warp your brain. You can’t tell what the methods do by looking at their type signatures, so you either (a) trust that the methods are well-named, or (b) you have to look at their source code to see what they do.
As an example of what I mean, I trusted my own code because I knew that all of my getters and setters were just boilerplate code. But one time when I was debugging a problem with a junior developer, I found that he wrote a setter method like this:
public void setFoo(Foo newFoo) { openTheGarageDoor(); walkTheDog(); buyGroceries(); solveWorldPeace(); this.foo = newFoo + 1; }
It wasn’t quite that exhaustive, but there was a lot going on there. And bear in mind, all of that happened inside a method with this type signature:
public void setFoo(Foo newFoo)
So, lessons learned:
- This developer needed some more training
I couldn’t trust method type signatures, I had to look at their code
(2) A second point I’ll add is that many Java methods can throw exceptions, and when they can, you have to think about (a) handling the successful case, and (b) handling the failure case, such as wrapping the method call with try/catch. This gets to be very hard on the brain, so I got to the point that — using the Model/View/Controller paradigm — I only handled exceptions with my top-level controllers. I ignored exceptions at the low levels, and just let them bubble up to my controllers and handled them there.
I didn’t know anything about functional programming, and I couldn’t think of a better way to deal with exceptions, so that’s how I dealt with that problem.
Is Java/OOP code that simple? A statistical look
I haven’t worked with Java in quite a while now, so I wondered, “Was my code really that simple?” To check what I was thinking, I searched three old Java codebases — all projects that were in production in their day. I just did a simple search for the
<.*> pattern, and found these stats in those three projects:
- 0.2%: 118 lines contain the
<.*>pattern out of 74,200 lines
- 1.4%: 686 lines out of 49,189
- 1.2%: 313 out of 27,083
So out of about 150,000 lines of code there are 1,117 lines with a
<.*> pattern, for a total of 0.74%. (Note that those line-count numbers include blanks lines and comment lines, so the actual percentages are higher.)
I then looked through all of those
<.*> lines of output, and found that these were the two most difficult lines to read:
SortedMap<String, Integer> wordCountMap = new TreeMap(); public Class<?> getColumnClass(int columnIndex) {
So that’s a look at some Java/OOP code. Next, let’s look at some Scala code. | https://alvinalexander.com/scala/thinking-with-types/thinking-in-java-oop/ | CC-MAIN-2021-49 | refinedweb | 1,063 | 63.12 |
BTREE(3) Linux Programmer's Manual BTREE(3)
btree - btree database access method
#include <sys/types.h> #include <db.h>
Noteing any of the following val‐ ues: R_DUP Permit duplicate keys in the tree, that is, permit insertion if the key to be inserted already exists in the tree. The default behavior, as described in dbopen(3), is to overwrite a matching key when insert‐ ing routine substantially improves access time. In addition, physical writes are delayed as long as possible, so a moderate cache can reduce the number of I/O operations significantly. Obvi‐ ously, using a cache increases (but only increases) the like‐ lihood of corruption or lost data if the system crashes while a tree is being modified. If cachesize is 0 (no size is spec‐ ified), maxi‐ mum page size is 64 KiB. If psize is 0 (no page size is spec‐ ified), a page size is chosen based on the underlying filesys‐ tem I/O block size. compare Compare is the key comparison function. It must return an integer less than, equal to, or greater than zero if the first key argument is considered to be respectively less than, equal to, or greater than the second key argument. The same compar‐ ison function must be used on a given tree every time it is opened. If compare is NULL (no comparison function is speci‐ fied), the keys are compared lexically, with shorter keys con‐ sidered less than longer keys. prefix Prefix is the prefix comparison function. If specified, this routine must return the number of bytes of the second key argument which are necessary to determine that it is greater than the first key argument. If the keys are equal, the key length should be returned. Note, the usefulness of this rou‐ tine is very data-dependent, but, in some data sets can pro‐ duce significantly reduced tree sizes and search times. If prefix is NULL (no prefix function is specified), and no com‐ parison function is specified, a default lexical comparison routine is used. If prefix is NULL and a comparison routine is specified, no prefix comparison is done. solu‐ tions imple‐ mentation has been modified to make ordered insertion the best case, resulting in a much better than normal page fill factor.
The btree access method routines may fail and set errno for any of the errors specified for the library routine dbopen(3).
Only big and little endian byte order is supported.
dbopen(3), hash(3), mpool(3), recno(3).
This page is part of release 5.08 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. 2017-09-15 BTREE(3)
Pages that refer to this page: db(3), dbopen(3), hash(3), mpool(3), recno(3) | https://man7.org/linux/man-pages/man3/btree.3.html | CC-MAIN-2020-40 | refinedweb | 473 | 62.48 |
Bummer! This is just a preview. You need to be signed in with a Pro account to view the entire video.
New & Powers5:59 with Dale Sande
Through the power of Sass we are able to address multiple scenarios of the module using two common conventions.
You'll be working in Sassmeister for this course.
Like what you see and want to read more? Check out 'Sass in the Real World' for more on Advanced Sass!
- 0:00
The next thing that came in Sass 3.3, which is pretty awesome.
- 0:04
So I'm actually gonna switch this over to Sass 3.2.
- 0:09
As we can see this all still here work.
- 0:12
But, in the same vein that we're gonna say ampersand is-selected.
- 0:20
Right, so that all puts what we're looking for over there.
- 0:23
When a lot of people who are fans of the BEM methodology, Base, Element, Modifier.
- 0:29
What they wanted to do was something like this.
- 0:33
As we can see here over on the right, Sass 3.2 did not support this.
- 0:36
It seemed pretty natural that we would want to try something like that, but
- 0:39
Sass 3.2 did not have the code to support this.
- 0:41
So if I come over here and I update this to Sass 3.3, bam, now we get this.
- 0:47
So now, this the new ampersand feature of being able to use the ampersand and
- 0:52
then basically put anything after it.
- 0:55
So I could is dot,
- 0:59
is dash, is double dash, is underscore, double underscore, triple underscore.
- 1:04
It doesn't matter.
- 1:05
Everything's gonna work from that scenario.
- 1:07
So how do we use this for BEM?
- 1:10
So, say we have a selector like, header-search__input.
- 1:18
Color, brown.
- 1:23
'Kay?
- 1:25
So, that's a regular CSS selector and that output a regular CSS selector.
- 1:30
With 3.3 I can do this.
- 1:33
Header, ampersand-search.
- 1:38
Ampersand__input,
- 1:43
ampersand--selected, color, brown.
- 1:55
This is pretty cool.
- 1:55
And the reason this is cool is because this allows us, you know,
- 1:59
again, to be really modular and be really specific about the sass that
- 2:04
we're outputting and not have to repeat, you know, these really,
- 2:07
really long named selectors when you're using the BEM methodology.
- 2:12
So, you know, let's turn this into something a little bit more interesting.
- 2:19
So if I go back to SCSS just so I can paste this in here.
- 2:25
So here's more of kind of like a real life scenario of,
- 2:28
I have a header with a background color of black, search with a file size,
- 2:31
input as a border, and a background color using a transparentize function.
- 2:35
And then what's also interesting is that the and
- 2:37
hover, and then I'm also using the and selected.
- 2:41
So I'm trying to I'm, I'm trying to kill two birds with one stone.
- 2:45
Is that when something is hover, and then it also has this BEM selector
- 2:48
associated to it, you're gonna get the border color of green.
- 2:51
'Kay.
- 2:53
So, now looking at this, we can have a little bit more fun, and one of
- 2:58
the things that I wanna do is, I wanna pull this out to a placeholder selector.
- 3:03
So, what I wanna do is I actually kinda wanna put this,
- 3:05
you know, I can create a default namespace.
- 3:09
So something like this, right.
- 3:13
And then what I'm gonna put inside this default namespace,
- 3:16
is that I'm gonna do the ampersand default input, okay?
- 3:20
And then I'm gonna paste in my rules here.
- 3:26
So it's interesting that I can do here is that I'm using a placeholder selected with
- 3:29
the word default, but it doesn't matter, could be zoo, voo, bar, baz, whatever.
- 3:34
Because when I, when I extend it, it's actually gonna replace that name with the,
- 3:39
the area, you know, that I'm extending it in.
- 3:42
So let's get rid of this.
- 3:44
And then inside of the input I'm gonna do @extend, and
- 3:50
then I'm gonna say default-input.
- 3:55
And then that ex, that extended it to exactly what it is that I'm looking for.
- 4:01
So, it's basically, it's replaced in the,
- 4:03
in the cascade of course, because it's put up here where the the extension is.
- 4:08
But nonetheless I have header, search, input.
- 4:11
Header, search, input is what I was looking for.
- 4:13
And then I have the border of one pixel solid and
- 4:16
the background color with the RGBA.
- 4:18
So now, let's say that, we want to, you know, we're
- 4:24
not only using the BEM methodology but we're also using the SMACSS methodology.
- 4:29
So another way we can extend this again using more ampersands, and
- 4:33
again this all just kinda works.
- 4:35
So we have and we have this extended default input here.
- 4:39
And then, say I wanna use this again.
- 4:42
I wanna put you down here.
- 4:45
So then that creates my chain of selectors.
- 4:48
And then what I wanna do is that, I have the and hover, and the and
- 4:51
sel, and selected.
- 4:52
And then I'm also gonna do the &.is-selected.
- 5:01
So this writes out all the selectors that I'm specifically looking for, and
- 5:05
this is not selector [UNKNOWN] these are just really long names I was putting out.
- 5:09
So, you know, using the ampersand is extremely powerful and
- 5:12
it gives you a lot of flexibility in how you want to architect your code.
- 5:16
And this last update to Sass 3.3, of putting this together this way,
- 5:20
of allowing us to really basically change anything together within, you know,
- 5:25
some type of parent selector.
- 5:28
is is really huge and really helpful, and so,
- 5:31
you know, I would love to see what you do with it.
- 5:35
And there you have it.
- 5:36
When you were learning grammar,
- 5:38
did you ever think that the little ampersand would be so powerful?
- 5:42
I didn't.
- 5:43
Building modular CSS is the nirvana of CSS developers.
- 5:48
And vanilla CSS was never able to give this to us.
- 5:51
Our friends in the sass community,
- 5:53
on the other hand, came through with flying colors.
- 5:57
Thank you Sasscotts, thank you. | https://teamtreehouse.com/library/advanced-sass/advanced-variables-mixins-functions-and-placeholders/new-powers | CC-MAIN-2017-43 | refinedweb | 1,215 | 82.14 |
Tutorial:
Outline
Adding the ability to redefine the controls in a game is a common and expected feature in PC games. The task can be broken down into three main areas:
- Store a list of which keys/buttons do what in a file, and load this into an in-memory array/list when the game starts. This stage provides persistence, so that if the controls are changed, the changes are saved for next time the game is played.
- Replace hard-wired references to specific key/button checks in your game code with references to corresponding items in the loaded key list. This stage provides the functionality of allowing any customized controls to actually work.
- Provide a user interface which allows the user to edit the key list and save any changes made. This stage provides the ability to change the controls from their default settings.
1. Processing keyboard input (without DirectX)
Virtual Key codes, Windows key events and AsyncGetKeyState
When the Windows message pump in your application receives a key event such as
WM_KEYDOWN (key has been pressed), the
WPARAM supplied with this is the so-called Windows Virtual Key code of the pressed key. Virtual key codes provide a handy way to represent each particular key with a universal number that remains the same regardless of keyboard manufacturer, territory, input language etc. No matter what type of keyboard you are using or where, the left arrow key (for example) will always have the same numerical equivalent value as a virtual key code. The Windows API defines an
enum which gives the key codes friendly names so that you don’t actually have to remember all these numbers, so for example, the left arrow key always maps to
VK_LEFT.
Generally speaking, when you are offering the user control of the game via Windows key press events, you will have code that looks roughly like this:
// Handle Windows message pump LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { ... // Code for dealing with window creation, resizing, focus changes, mouse movement etc. ... // Virtual key has been pressed case WM_KEYDOWN: yourApplicationObject->OnKeyDown(static_cast<int>(wParam), LOWORD(lParam), static_cast<bool>((lParam >> 30) & 1))); break; // Virtual key has been released (not always needed, largely dependent on your application) case WM_KEYUP: yourApplicationObject->OnKeyUp(static_cast<int>(wParam), LOWORD(lParam)); break; ... } ... } ... // Handle key presses in my game object YourApplicationClass::OnKeyDown(int key, int repeatCount, bool previousState) { if (key == VK_LEFT) ... // move left (left arrow pressed) if (key == VK_RIGHT) ... // move right (right arrow pressed) if (key == VK_SHIFT) ... // fire gun (SHIFT key pressed) ... }
wParam contains the virtual key code of the pressed (or released key), the low word of
lParam contains the repeat count, ie. how many times the key press has repeated with the current user’s keyboard settings (in Control Panel), and bit 30 of
lParam in a
WM_KEYDOWN event indicates whether the key was previously down before this event or not. This is handy as a test to help prevent duplicate processing of keys in certain situations, although it doesn’t apply here.
Allowing key presses to come in to your application according to the user’s keyboard repeat timing settings is fine for games like Tetris, but in an action game we want to ignore the repeat timing settings and get instantaneous “is the key up or down now?”-type information. Hence the alternative way to allow the user to control the game is to use
GetAsyncKeyState, which returns
true if the key corresponding to the virtual key code specified as the argument is currently pressed, ie.:
if (GetAsyncKeyState(VK_LEFT)) ... // move player left
This kind of checking would normally be performed in the game world object update stage of your game, each frame, prior to rendering the scene.
Scan codes
A scan code is a number representing a specific key on a specific keyboard. Different manufacturers are free to use their own scan codes, and keyboards designed for countries with non-English character sets will generate scan codes not generated by pure English keyboards, for example. Windows deals with the conversion of these internal hardware scan codes into virtual key codes for you, but there are a few reasons to be aware of them:
1. Not all virtual key codes can distinguish between the left and right versions of keys such as SHIFT, ALT and CTRL, ie. not all virtual key codes are always unique to a single key, whereas a scan code is and can be used to determine precisely which key has been pressed if it is important to distinguish between them. There are virtual key codes which distinguish between left and right versions of keys, however the Windows message loop returns the non-deterministic version of the virtual key code.
2. If we want to store a file with a list of redefined controls in the user’s roaming profile data, we need to store the control list as virtual key codes, not scan codes. This is because scan codes are not portable between computers. Additionally, when the game is shipped, it will have a default set of controls, yet you have no way in advance of knowing what kind of hardware your game will be played on, so you need to use a portable solution, which means using virtual key codes.
3. In our Redefine Controls user interface, we will need to display the names of the keys being edited. The Windows API function
GetKeyNameText accepts
lParam from an event such as
WM_KEYDOWN (which contains the scan code in the high word plus some other assorted single bits of information) and converts it into a human-readable key name such as ‘SHIFT’. Unfortunately, these values are not available when we are just reading virtual key codes from a list to draw a table of key names, and so we have to convert our virtual key codes into scan codes with another Windows API function, mangle them into the format
GetKeyNameText expects and pass those instead.
At this point, the astute among you may have spotted a problem. If virtual key codes are not unique to a specific key, and scan codes are, and we have to save the list of redefined controls as virtual key codes – making the compromise that a key such as ‘SHIFT’ will just have to mean ‘either SHIFT key’ for simplicity – then when we do the conversion from virtual key code to scan code in order to get the key’s name, how do we get the ‘right’ scan code and therefore display the ‘correct’ key name? For example, converting the up arrow (
VK_UP) to a scan code and then retrieving its name will in fact yield ‘
NUM 8‘ rather than ‘
UP ARROW‘ by default as the key name text, which is probably not what we want. This problem is addressed below.
2. Creating a re-usable class to store user-defined controls
Data structures
The first task is to create a type to store an individual game control. This will basically be a struct which wraps the functional name that you want to give to the key, eg. “Change Weapon” or “Rotate Piece”, and the virtual key code that the action is mapped to.
struct GameControl { string displayName; unsigned int keyCode; GameControl() : displayName(""), keyCode(0) {} GameControl(string name, unsigned int code) : displayName(name), keyCode(code) {} private: // Serialization helpers friend class boost::serialization::access; template <typename Archive> void serialize(Archive &ar, const unsigned int version) { ar & displayName; ar & keyCode; } }; BOOST_CLASS_TRACKING(GameControl, boost::serialization::track_never)
The serialization code using
Boost.Serialization serves to describe how the contents of the
struct will be saved to disk and works identically to as described in the high score table article, so I won’t go over it again here. Note that
Boost.Serialization generates a compilation error if you attempt to use a non-const struct; to eliminate this we use the
BOOST_CLASS_TRACKING macro to turn off object tracking, since we don’t need it anyway (see the Boost.Serialization documentation for more information on object tracking).
We then create a class to store all of the controls:
class GameControls { private: // File to store the controls in std::string keysFile; protected: // Map of (game action ID -> GameControl) typedef boost::unordered_map<int, GameControl> KeyMapping; KeyMapping keyMap; // Change the virtual key assigned to an action void setKey(int keyIndex, int key); // Get the name of a virtual key code void getKeyName(int key, char *buf, int bufSize); // Save the controls to file void save(); // Load the controls from file void load(); public: // NOTE: You should create an enum in the child with the names of all the keys used // Set up the default controls for this game virtual void SetDefaults() = 0; // Allow access to the key map using array syntax unsigned int operator[](int i) { return keyMap[i].keyCode; } // Constructors GameControls() {} GameControls(std::string path) : keysFile(path + "controls.dat") {} };
Note that this is an abstract class which cant be instantiated directly – we are going to derive from it for the specific game we shall use it with (Tetris, in this case).
The full qualified pathname of the file we will store the list of controls in is stored in
keysFile – to set this correctly, see the “Storage location” section of the high score table article. Container selection is always important and the list of controls itself is stored in a Boost
unordered_map. This is basically the same as a regular C++ Standard Library
map except that it isn’t automatically sorted. Notice that the map has a key which is an
int; the possible values for this
int will be defined by an
enum in the class we derive from
GameControls, with each
enum value corresponding to one possible in-game action (for example, move left, move right).
Deriving GameControls for your game
So far we have a generic re-definable controls class which can be used by any game. All the generic editing functions like setting a key value, fetching its value or its name, saving and loading are defined above. When we specialize the class (derive from it) to a class to be used by one specific game, we will include things such as the user interface code and anything else that is unique to the individual game.
The simplest possible version of a game-specific class is shown below. It basically includes only the default controls and list of possible actions, and no interface or other code:
class TetrisControls : public GameControls { public: enum Keys { Left, Right, Down, FastDrop, Rotate, Shift, Pause }; public: virtual void SetDefaults(); TetrisControls() {} TetrisControls(string path) : GameControls(path) { load(); } }; ... void TetrisControls::SetDefaults() { keyMap.clear(); keyMap[Left] = GameControl("Move Piece Left", VK_LEFT); keyMap[Right] = GameControl("Move Piece Right", VK_RIGHT); keyMap[Down] = GameControl("Move Piece Down", VK_DOWN); keyMap[FastDrop] = GameControl("Fast Drop", VK_UP); keyMap[Rotate] = GameControl("Rotate", VK_CONTROL); keyMap[Shift] = GameControl("Shift / Hold Piece", VK_SHIFT); keyMap[Pause] = GameControl("Pause Game", 'P'); }
We have defined a list of every possible in-game action the user can take in the Keys enumeration, and given each action a friendly name (for the user interface) and a default virtual key code in SetDefaults(). Pretty simple.
3. Implementing the user-defined controls class
To change the key assigned to an action:
void GameControls::setKey(int currentlyEditing, int key) { int prevKey = keyMap[currentlyEditing].keyCode; keyMap[currentlyEditing].keyCode = key; for (auto i = keyMap.begin(); i != keyMap.end(); i++) if (i->second.keyCode == key && i->first != currentlyEditing) i->second.keyCode = prevKey; }
Usage:
gameKeys.setKey(TetrisControls::Rotate, VK_SHIFT); (if
gameKeys is an instance of a class derived from
GameControls)
The first part of the function merely replaces the current virtual key code for the specified action to the one supplied. The
for loop checks to see if any other action already had that key assigned to it and, if so, to prevent unwanted behaviour, re-assigns it to use the key that was previously used by the action whose key we just re-defined. This guarantees there will be no clashes such that one key is assigned to more than one action at a time.
To retrieve the human-readable name of a key:
void GameControls::getKeyName(int key, char *text, int maxTextSize) { // From: <a href="" target="_blank"></a> int scanCode = MapVirtualKey(key, MAPVK_VK_TO_VSC); switch (key) { case VK_LEFT: case VK_RIGHT: case VK_UP: case VK_DOWN: case VK_HOME: case VK_END: case VK_PRIOR: case VK_NEXT: case VK_INSERT: case VK_DELETE: case VK_DIVIDE: case VK_NUMLOCK: scanCode |= 0x100; break; } GetKeyNameText(scanCode << 16, text, maxTextSize); }
I’d like to thank richardwb for blogging about this as it saved me a fair amount of hair-tearing and my hair is already falling out, so that’s good 🙂 Please see the link above for more information about the scan code / key name problem and how this solution works. The long and short of it though is that you pass in the virtual key code you want the human-readable name of in
key, and the result is stored in
text (with a maximum length of
maxTextSize characters).
This function isn’t actually needed at all, it is provided purely so that people coding the user interfaces for editing the controls have a quick way of getting the name of the existing assigned key if they want to.
To save and load the key list to file:
// Save game controls void GameControls::save() { std::ofstream KeysFile(keysFile, std::ios::out); boost::archive::text_oarchive oa(KeysFile); for (auto i = keyMap.begin(); i != keyMap.end(); i++) { oa << i->first; oa << i->second; } KeysFile.close(); } // Load game controls void GameControls::load() { // Make a default controls file if none exists DWORD attr = GetFileAttributes(keysFile.c_str()); if (attr == INVALID_FILE_ATTRIBUTES) { SetDefaults(); save(); } std::ifstream KeysFile(keysFile); boost::archive::text_iarchive ia(KeysFile); keyMap.clear(); KeyMapping::key_type k; KeyMapping::mapped_type v; while (!KeysFile.eof()) { ia >> k; ia >> v; keyMap[k] = v; } KeysFile.close(); }
The technique here is exactly the same as that in the high score table article so I shan’t go into great depth here. Two things worth noting which differ from the high score code are that
load() checks to see if the file exists first, and generates a default set of controls and saves them if not; also, when reading in the values from the serialization archive to be stored in the unordered map, note that we use the
key_type and
mapped_type traits to ensure that we instantiate temporary storage variables (
k and
v) of the correct type for the container being used.
4. Enabling your game to use the user-defined controls class
First of all we just need to add a declaration for our derived version of
GameControls in our main game class, and instantiate it when the application starts up:
class SimpleTetris : public Simple2D { ... private: // Control mappings TetrisControls gameKeys; ... }; ... // Constructor for main application SimpleTetris::SimpleTetris() : ... { ... // Set game controls gameKeys = TetrisControls(DataPath); }
Recalling that
DataPath is generated by Simple2D to contain the user’s roaming profile data path for the application, this will effectively cause the game controls to be loaded from file into
gameKeys (
GameControls::load() is called in the constructor of
TetrisControls). If none exist,
TetrisControls::SetDefaults() will be called to set the controls to their defaults, and the list of controls saved to file (if you aren’t using Simple2D, just substitute
DataPath for your own directory path choice). Therefore, initialization is very simple.
Next we need to replace any hard-coded references to specific virtual key codes to use the mappings in
gameKeys instead. This is pretty easy, just Find & Replace on VK_ in your code. In SimpleTetris the changes are all made in
SimpleTetris::OnKeyDown as you would expect, and look like this:; } // Toggle pause if (gameState == Playing && key == gameKeys[TetrisControls::Pause] && !prev) // was "key == 'P'" { SetGameState(Pause); return true; } else if (gameState == Pause && key == gameKeys[TetrisControls::Pause] && !prev) { SetGameState(Playing); return true; } // Only process keypresses if the game is in progress if (gameState != Playing) return false; if (currentShape.Active) { if (key == gameKeys[TetrisControls::Left]) // was 'key == VK_LEFT' currentShape.MoveLeft(); if (key == gameKeys[TetrisControls::Right]) // was 'key == VK_RIGHT' etc.... currentShape.MoveRight(); if (key == gameKeys[TetrisControls::Down]) if (currentShape.MoveDown()) placePiece(); if (key == gameKeys[TetrisControls::FastDrop]) { currentShape.MoveToBottom(); placePiece(); } if (key == gameKeys[TetrisControls::Rotate]) currentShape.Rotate(); if (key == gameKeys[TetrisControls::Shift] && !held) shiftShapes(); return true; } return false; }
Notice how the use of overloading the index operator (
[]) and the
enum in combination make for nice readable code.
Note also that
key == ' ' is still hard-wired to expect the user to press the space bar when the game has ended. This is fine, we don’t necessarily want to allow every key to be re-definable, and in this case, we always want the user to press space to continue when the game ends so there is no need to make it re-definable.
5. Creating a graphical user interface to re-define the game controls
At this point, two of the three issues listed at the start of the article have been tackled, and they can be dealt with in a fairly generic re-usable way as shown. Once again – and as with the high score table code – creating the user interface to let the user edit controls is the most complex and awkward of the problems, and there is no generic solution as it highly depends what game/rendering engine you are using. I will illustrate below how to produce a working user interface if you are using my Simple2D library and how it hooks into the methods provided by
GameControls. If you are using another rendering library you will need to make significant changes, but hopefully still see the principle.
Adding a Redefine Controls button to the main menu
The previous version of SimpleTetris had a single Play button on the main menu. We will ditch that code (from the SimpleTetris main constructor) and replace it with a ButtonGroup. This is a class defined by Simple2D which handles creating, rendering and dispatching mouse click and hover events on a row or column of buttons of similar appearance. This convenience class makes the entire process of creating a user interface much easier.
First we’ll add a new game state, EditControls:
class SimpleTetris : public Simple2D { public: .... // Possible game states enum GameStates { Menu, Playing, GameOver, Pause, EnterName, EditControls };
We’re going to use Boost.Bind – a library which allows parameters to be bound to function arguments before they are called – to create function references that will be called when the Play or Redefine Controls buttons are clicked with the mouse, so first include the relevant header file:
#include <boost/bind.hpp>
Then, create the menu and its actions in the game’s constructor:
// Set colour for menu buttons ButtonColour = MakeBrush(Colour::BlueViolet, Colour::DarkBlue); // Set menu button region for mouse input int ButtonSizeX = 200; int ButtonSizeY = 50; ButtonTemplate menuOptions[] = { // Start new game { "Play", boost::bind(&SimpleTetris::newGame, this) }, // Redefine the controls { "Redefine Controls", boost::bind(&SimpleTetris::SetGameState, this, EditControls) } }; // Create main menu MainMenu = ButtonGroup(this); MainMenu.AddItemColumn( (ResolutionX - ButtonSizeX) / 2, (ResolutionY - ButtonSizeY) / 2 + 130, ButtonGroupTemplate( ButtonSizeX, ButtonSizeY, 10, 20, MakeBrush(Colour::DarkBlue), ButtonColour, MakeTextFormat(L"Verdana", 14.0f), MakeBrush(Colour::Yellow)), menuOptions, 2, 5);
This effectively generates the menu shown in Figure 1. First we set the menu button colour to a graduated fill, then the size of each button. Next, we create the list of options with button captions and the corresponding functions they call in the game code. Clicking Play begins a new game, while clicking Redefine Controls sets the game state to
EditControls. The arguments to
AddItemColumn merely set the position and remaining aspects of the appearance of each button.
Note that no actual interface processing code is required. Simple2D monitors the menu as long as it is switched on, and dispatches any mouse click events as appropriate. The rendering is also done automatically.
Switching between menus
The switching on and off of menus (the main menu, and the redefine controls screen) is done when the game state is changed as follows:
// Game state transition void SimpleTetris::SetGameState(GameStates state) { gameState = state; switch (gameState) { case Menu: gameKeys.Menu.Off(); MainMenu.On(); break; case EditControls: gameKeys.StartMenu(); break; ... }
Adding the redefine controls interface to the custom game controls class
We now extend
TetrisControls – our specialized game controls class – with all the necessary interface code:
class TetrisControls : public GameControls { public: enum Keys { Left, Right, Down, FastDrop, Rotate, Shift, Pause }; private: Simple2D *renderer; typedef boost::unordered_map<int, Keys> ButtonMapping; ButtonMapping buttonIds; DrawingObject keyCapture; int currentlyEditing; public: ButtonGroup Menu; void Init(); void StartMenu(); virtual void SetDefaults(); TetrisControls() {} TetrisControls(string path, Simple2D *r) : renderer(r), GameControls(path) { load(); } };
Refer to Figure 2 below. The
buttonIds object maintains a mapping between the unique ID of each button on the user interface and which game action it is supposed to edit, so that when an edit is made via the interface, we can edit the correct key.
keyCapture is a Simple2D object which defines an area of the screen to capture and dispatch keyboard events for. The idea is that when you click a button on the Redefine Controls screen, you can then choose a new key by pressing it, and
keyCapture will grab that key press for us.
currentlyEditing is the index of the key currently being edited.
Figure 2. The edit controls interface (the key names are shown in the user’s locale – Norwegian here)
The intended process is as follows:
- The menu is created with the names of the current keys assigned to each action.
- The user clicks one of the keys (in the right-hand menu column) to redefine it. This sets
currentlyEditingand enables
keyCapture.
- The user presses a key on the keyboard to make the edit. This updates the key map, re-creates the menu, resets
currentlyEditingand disables
keyCapture.
If you are confused about the process flow, I would recommend you download the game and try it, as it will likely make much more sense then.
Accomplishing steps 2 and 3 is pretty simple. We add an initialization function which sets up key capture and makes the edits:
void TetrisControls::Init() { keyCapture = DrawingObject(renderer, NULL, [this] (int key, int, bool) -> bool { setKey(currentlyEditing, key); StartMenu(); return true; }, NULL ); }
This creates a key capture covering the whole screen, which changes the key currently being edited to the pressed key and re-creates the menu whenever a key is pressed (if the object is enabled). The 1st and 3rd parameters here are functions called when a normal character (not special keys such as SHIFT or CTRL) is pressed and when a key is released – we’re not interested in those so we just set them to
NULL. The 2nd parameter is a C++11 lambda function which does the main work.
The control setup in SimpleTetris’s constructor now becomes:
// Set game controls gameKeys = TetrisControls(DataPath, this); gameKeys.Init();
Creating the Redefine Controls display
Our final task is the mini-nightmare of generating the display and its behaviour. Let’s go through this piece by piece.
void TetrisControls::StartMenu() { int BSizeX = 200, BSizeX2 = 140; int BSizeY = 30; int BGapX = 10; int StartX = (renderer->ResolutionX - (BSizeX + BSizeX2 + BGapX)) / 2; int StartY = 140; keyCapture.Off(); Menu.Off();
We set the width of buttons in the first and second columns with
BSizeX and
BSizeX2 respectively. The height is set in
BSizeY, the horizontal gap between each button in
BGapX and the top-left position is calculated centerized based on the display resolution, then stored in
StartX.
Finally, key capture and the main menu are both disabled.
Menu = ButtonGroup(renderer, false); ButtonTemplate *menuOptions = new ButtonTemplate[keyMap.size()]; int o = 0; for (auto i = keyMap.begin(); i != keyMap.end(); i++, o++) { menuOptions[o] = ButtonTemplate(); menuOptions[o].text = i->second.displayName; menuOptions[o].onClick = [] (Button &) {}; }::White), false), menuOptions, keyMap.size(), 5);
Here we create the buttons for the left-hand column – with action names from
keyMap[X]->second.displayName – and tell Simple2D to do nothing when they are clicked on with the lambda function
[] (Button &) {}, which effectively turns them into non-interactive labels.
o = 0; char keyText[256]; for (auto i = keyMap.begin(); i != keyMap.end(); i++, o++) { getKeyName(i->second.keyCode, keyText, 256); menuOptions[o].text = keyText; menuOptions[o].onClick = [this] (Button &b) { for (auto i = buttonIds.begin(); i != buttonIds.end(); i++) Menu[i->first].SetActive(false); currentlyEditing = buttonIds[b.GetID()]; b.SetText("Press New Key"); b.SetBrush(renderer->MakeBrush(Colour::Green)); keyCapture.On(); }; }
We now create the second column of buttons by fetching the human-readable name of each key currently assigned via
i->second.keyCode. When one of the buttons is clicked, the lambda function first disables all of the buttons on the screen so that clicking has no further effect for now, sets
currentlyEditing so that we know the index of the key to edit, changes the text to prompt he user to press a key, and turns key capture on.
StartX += BSizeX + BGapX; BSizeX = BSizeX2; // Make buttons with key names and get a list of the button IDs vector<int> bIds =::Yellow)), menuOptions, keyMap.size(), 5); // Store a mapping of button IDs to corresponding keys to redefine o = 0; for (auto i = bIds.begin(); i != bIds.end(); i++, o++) buttonIds[*i] = static_cast<Keys>(o); delete [] menuOptions;
We set the starting position of the 2nd column and add it to the interface, retrieving the button IDs as we go, and creating a mapping between them and the corresponding key they cause to be re-defined when clicked on.
ButtonTemplate rowOptions[] = { // Default settings { "Defaults", [this] (Button &) { SetDefaults(); StartMenu(); } }, // Accept changes { "OK", [this] (Button &) { keyCapture.Off(); save(); static_cast<SimpleTetris *>(renderer)->SetGameState(SimpleTetris::Menu); } }, // Ignore changes { "Cancel", [this] (Button &) { keyCapture.Off(); load(); static_cast<SimpleTetris *>(renderer)->SetGameState(SimpleTetris::Menu); } } }; // Create bottom row of controls BSizeX = 100; BSizeY = 40; Menu.AddItemRow( (renderer->ResolutionX - (BSizeX + 5) * 3 + 5) / 2, (renderer->ResolutionY - BSizeY) - 20, ButtonGroupTemplate( BSizeX, BSizeY, 10, 20, renderer->MakeBrush(D2D1::ColorF(0.0f, 0.0f, 0.3f)), renderer->MakeBrush(Colour::BlueViolet, Colour::DarkBlue), renderer->MakeTextFormat(L"Verdana", 14.0f), renderer->MakeBrush(Colour::Yellow)), rowOptions, 3, 5); Menu.On(); }
Finally, we come to the creation and behaviour of the row of buttons at the bottom of the interface. The first one resets all the controls to the defaults and re-creates the menu (line 69); the second disables key capture, saves the changes and changes the game state so that we are returned to the main menu (line 72); the third disables key capture, discards any changes by re-loading the saved controls and changes the game state back to the main menu.
The remaining code adds the row of buttons to the interface, and finally, switches the menu on with
Menu.On().
It’s pretty messy, but that’s the way we have to roll on this one…
The End
Do of course feel free to copy and paste the relevant parts of this article’s code into your own games, and do check out the full source code at the top of the page. While I have shown every line of code needed here, you will perhaps get a better idea of how it all fits together by looking at the program as a whole.
I hope you enjoyed the tutorial. Next time we are going to look at sprucing up SimpleTetris with some cool animations! | https://katyscode.wordpress.com/2012/09/29/tutorial-enabling-re-definable-controls-in-windows-games/ | CC-MAIN-2018-17 | refinedweb | 4,534 | 56.08 |
07 – Packages
We’re nearly ready to write some code on our own now. The last thing we must understand before doing so is how packages work in Java. Packages are simply a way to organize your classes in a hierarchical structure, grouped however you want, but hopefully with the intention of making management of your source code easier.
To place a class into a package you must first make a directory structure that looks like the package hierarchy you wish to employ. Typically you would encode information about who you are and the application you are coding for within the hierarchy at the same time. For example if you were writing an email agent for your non-profit you might choose a base structure like org.myorg.email From there you would create subdirectories depending upon your programs requirements, like org.myorg.email.app, org.myorg.email.gui, etc.
Then as you create a class within a package, the first line of the class file must define where the package is in the hierarchy. For example, in our app package for our eGate monitor the main class might look like this:
package org.myorg.email.app;
public class MainApp {
...
As long as you remember that the package definition must be the first line in the class file you’re well on your way to creating your own Java classes.
Now we can finally create some Java code on our own. First we must put our directory structure in place. Make a folder in your home drive called javatut. Inside that make a directory with your initials, like ~/javatut/abc/ or c:\
Beneath the app directory create a .java file called TestApp.java. Edit the file so that it looks like this:
package yourinitials.app;
public class TestApp {
public static void main(String[] args) {
System.out.println(“Hiâ€);
}
}
Obviously, change yourintials to whatever you entered for your initials. Next we open a command prompt and compile and run the program with the following lines, for windows:
C:\
C:\
C:\
>cd javatut \javatut>javac -cp . yourinitials\app\TestApp.java \javatut>java -cp . yourinitials.app.TestApp
Or in Unix:
~ >cd javatut
~/javatut > javac -cp . yourinitials/app/TestApp.java
~/javatut > java -cp . yourinitials/app/TestApp
Since I use Unix most often, a shortcut that I used to compile and run in one step is to use the && shell operator to do both if the first succeeds:
~/javatut > javac -cp . yourinitials/app/TestApp.java && java -cp . yourinitials/app/TestApp
Then using the command line history, you can quickly recompile and retest. Later on we’ll learn how to use ant to automate building and running.
Compiling the Java files produces files with a .class extension. These files contain the bytecode that the Java virtual machine (JVM) executes.
If for some reason these lines fail, please make sure you have a Java 2 version 1.4 or higher SDK installed. You might also need to update your Path information or fully qualify the path to the javac and java commands. These commands could also fail if there was a typo either in the command or the code you entered above. Please double-check these and once the program is running it will simply display “Hi†as its output.
Packages Exercise
Now with packages under our belts, so to speak, we can actually test the code we have written. Put your code for the Methods Exercise to the test, by saving it to your app package location and placing an appropriate package declaration at the top. Then compile your .java file and execute it. | http://nule.org/wp/?page_id=147 | CC-MAIN-2017-13 | refinedweb | 600 | 65.01 |
The proposed method for accessing Jetpack features that are still in development and may be added in the future is inspired by python's future module. In Python, you can call
from __future__ import foo
which adds the functionality that
foo yields to the script. In Jetpack, we propse adding a new function to the base namespace called
importFromFuture.
Methods
jetpackbase, the feature will be mounted. To get a list of mount paths that are available, see the method below. string
Here is an example of how to import a feature (the clipboard) from the future.
jetpack.future.import("clipboard");
The goal here is to be able to remove the
jetpack.future.import() call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration).
stringMountPathas used in
jetpack.future.import().
This is an example of how to get this array. A quick way of displaying the list is to write it to the console.log.
var list = jetpack.future.list(); console.log(list);
Open the firebug console to view. | https://developer.mozilla.org/en-US/docs/Archive/Mozilla/Jetpack/Meta/Future_auto | CC-MAIN-2017-17 | refinedweb | 181 | 66.84 |
Cement your knowledge of objects
Note: There is no speech on the video above, and all of the steps in the video are described below.
So far, you have learnt that an object has attributes (or pieces of data) stored inside it, and methods we can call on it to give it instructions.
As I mentioned briefly.
Imagine you have created a
Cookie class in a module called
baking which accepts a list of toppings.
You could create some cookies using the following code.
from baking import Cookie sprinkled = Cookie(["sprinkles"]) iced_chocolate = Cookie(["icing", "chocolate chips"])
Think back to the turtle race program that you wrote. You created four instances of turtle objects from the
Turtle class and customised the attributes of each turtle object by changing its colour and position. You used the
forward method to move each turtle object, which drew a line across the screen based on that turtle’s colour attribute.
Next steps
Over the next few steps you’ll use some different objects and combine them into a single program. | https://www.futurelearn.com/courses/object-oriented-principles/0/steps/31482 | CC-MAIN-2020-45 | refinedweb | 175 | 69.11 |
In our testing, we have uncovered that the ACL permissions for users with the 'A' credential do not hold after the upgrade to 0.96.x.
This is because in the ACL table, the entry for the admin user is a permission on the 'acl' table with permission 'A'. However, because of the namespace transition, there is no longer an 'acl' table. Therefore, that entry in the hbase:acl table is no longer valid.
Example:
hbase(main):002:0> scan 'hbase:acl' ROW COLUMN+CELL TestTable column=l:hdfs, timestamp=1384454830701, value=RW TestTable column=l:root, timestamp=1384455875586, value=RWCA _acl_ column=l:root, timestamp=1384454767568, value=C _acl_ column=l:tableAdmin, timestamp=1384454788035, value=A hbase:acl column=l:root, timestamp=1384455875786, value=C
In this case, the following entry becomes meaningless:
_acl_ column=l:tableAdmin, timestamp=1384454788035, value=A
As a result,
Proposed fix:
I see the fix being relatively straightforward. As part of the migration, change any entries in the 'acl' table with key 'acl' into a new row with key 'hbase:acl', all else being the same. And the old entry would be deleted.
This can go into the standard migration script that we expect users to run. | https://issues.apache.org/jira/browse/HBASE-9973 | CC-MAIN-2020-34 | refinedweb | 203 | 50.06 |
C++ <cstdio> - fputc() Function
The C++ <cstdio> fputc() function writes a character ch to the output stream stream and advances the position indicator. Internally, the character is converted to unsigned char just before being written.
Syntax
int fputc ( int ch, FILE * stream );
Parameters
Return Value
On success, the character ch is returned. On failure, returns EOF and sets the error indicator ferror(). ABCDEFGHIJKLMNOPQRSTUVWXYZ in the file before closing it.
#include <cstdio> int main (){ //open the file in write mode FILE *pFile = fopen("test.txt", "w"); //writes character in the file for(char ch = 'A'; ch <= 'Z'; ch++) fputc(ch,; }
The output of the above code will be:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
❮ C++ <cstdio> Library | https://www.alphacodingskills.com/cpp/notes/cpp-cstdio-fputc.php | CC-MAIN-2021-43 | refinedweb | 111 | 55.95 |
What to make it a reality.
Looking for the source code to this post?
Jump right to the downloads section.
Previous Posts:
Before we get too far into detail, here are some previous posts you can look over for context and more detail on building our Pokedex:
Step 2: Scraping our Pokemon Database
Prior to even starting to build our Pokemon search engine, we first need to gather the data. And this post is dedicated to exactly that — scraping and building our Pokemon database. I’ve structured this post to be a Python web scraping tutorial; by the time you have finished reading this post, you’ll be scraping the web with Python like a pro.
Our Data Source
I ended up deciding to scrape Pokemon DB because they have the some of the highest quality sprites that are easily accessible. And their HTML is nicely formatted and made it easy to download the Pokemon sprite images.
However, I cheated a little bit and copied and pasted the relevant portion of the webpage into a plaintext file. Here is a sample of some of the HTML:
You can download the full HTML file using the form at the bottom of this post.
Scraping and Downloading
Now that we have our raw HTML, we need to parse it and download the sprite for each Pokemon.
I’m a big fan of lots of examples, lots of code, so let’s jump right in and figure out how we are going to do this:
Lines 2-4 handle importing the packages we will be using. We’ll use
BeautifulSoup to parse our HTML and
requests to download the Pokemon images. Finally,
argparse is used to parse our command line arguments.
To install Beautiful soup, simply use pip:
Then, on Lines 7-12 we parse our command line arguments. The switch
--pokemon-list is the path to our HTML file that we are going to parse, while
--sprites is the path to the directory where our Pokemon sprites will be downloaded and stored.
Now, let’s extract the Pokemon names from the HTML file:
On Line 16 we use
BeautifulSoup to parse our HTML — we simply load our HTML file off disk and then pass it into the constructor.
BeautifulSoup takes care of the rest. Line 17 then initializes the list to store our Pokemon
names.
Then, we start to loop over all link elements on Line 20. The href attributes of these links point to a specific Pokemon. However, we do not need to follow each link. Instead, we just grab the inner text of the element. This text contains the name of our Pokemon.
Now that we have a list of Pokemon names, we need to loop over them (Line 25) and format the name correctly so we can download the file. Ultimately, the formatted and sanitized name will be used in a URL to download the sprite.
Let’s examine each of these steps:
- Line 28: The first step to sanitizing the Pokemon name is to convert it to lowercase.
- Line 32: The first special case we need to handle is removing the apostrophe character. The apostrophe occurs in the name “Farfetch’d”.
- Line 37: Then, we need to replace the occurrence of a period and space. This happens in the name “Mr. Mime”. Notice the “. ” in the middle of the name. This needs to be removed.
- Lines 40-45: Now, we need to handle unicode characters that occur in the Nidoran family. The symbols for “male” and “female” are used in the actual game, but in order to download the sprite for the Nidorans, we need to manually construct the filename.
Now, we can finally download the Pokemon sprite:
Line 49 constructs the URL of the Pokemon sprite. The base of the URL is — we finish building the URL by appending the name of the Pokemon plus the “.png” file extension.
Downloading the actual image is handled on a single line (Line 50) using the
requests package.
Lines 53-55 check the status code of the request. If the status code is not 200, indicating that the download was not successful, then we handle the error and continue looping over the Pokemon names.
Finally Lines 58-60 saves the sprite to file.
Running Our Scrape
Now that our code is complete, we can execute our scrape by issuing the following command:
This script assumes that the file that containing the Pokemon HTML is stored in
pokemon_list.html and the downloaded Pokemon sprites will be stored in the
sprites directory.
After the script has finished running, you should have a directory full of Pokemon sprites:
Figure 1: After
parse_and_download.py has finished running, you should have a directory filled with Pokemon sprites, like this.
It’s that simple! Just a little bit of code and some knowledge on how to scrape images, we can build a Python script to scrape Pokemon sprites in under 75 lines of code.
Note: After I wrote this blog post, thegatekeeper07 suggested using the Veekun Pokemon Database. Using this database allows you to skip the scraping step and you can download a tarball of the Pokemon sprites. If you decide to take this approach, this is a great option; however, you might have to modify my source code a little bit to use the Veekun database. Just something to keep in mind!
Summary
This post served as a Python web scraping tutorial: we downloaded sprite images for the original 151 Pokemon from the Red, Blue, and Green versions.
We made use of the
BeautifulSoup and
requests packages to download our Pokemon. These packages are essential to making scraping easy and simple, and keeping headaches to a minimum.
Now that we have our database of Pokemon, we can index them and characterize their shape using shape descriptors. We’ll cover that in the next blog post.
If you would like to receive an email update when posts in this series are released, please enter your email address in the form below:
Great post!! I did the scraping like a boss!! 🙂
Looking forward to the next post.
Glad you liked it!
Brilliant.
Thanks a lot!! Very informative article.
Thanks Jeni!
Thanks Adrian
Finally learnt a bit of BeautifulSoup after reading this blog.The website structure has changed I guess. Hence took me a while to figure out how to scrape the website
Thanks again
BeautifulSoup is a great package, I definitely encourage readers to play with and use it. Great job re-scraping the website!
Hi Adrian,
I skipped the scraping and used the downloaded sprites in the archive. However while updating the code to Py3, I encountered a strange error during the indexing: at one point a sprite has failed to load.
It happened to be due to special Unicode characters in the end of a couple of sprites, Venus and Mars:
nidoran♀.png
nidoran♂.png
After renaming them to ordinary symbols, it run fine: 🙂
nidoran1.png
nidoran2.png
Thanks for sharing, Todor!
how is parsing donw if i am pycharm user
You should read up on how to set command line arguments with PyCharm. You could also:
1. Hardcode the values and ignore the command line argument code.
2. Code in PyCharm and execute via command line (which I think is the best way).
I think its worth mentioning that if someone is using BeautifulSoup4,
the import code should be
from bs4 import BeautifulSoup
thanks for post. but how do you know link.text have the name of pokemon | https://www.pyimagesearch.com/2014/03/24/building-pokedex-python-scraping-pokemon-sprites-step-2-6/ | CC-MAIN-2020-05 | refinedweb | 1,254 | 72.56 |
Introduction to Segment Trees
Introduction
This blog will discuss a problem based on a Segment Tree. A segment tree is an advanced data structure used to solve range-based queries. For example, finding the minimum in the subarray A[L, R] (also known as Range Minimum Query Problem) and finding the sum of all elements from index L to R in an array.
What is a Segment Tree?
A Segment Tree is a binary tree used to store intervals or segments. In the Segment Tree, each node represents an interval. The height of the segment tree is Log2N, where N is the number of leaves in the tree.
Representation of Segment Trees
Consider an array A[ ] of length N and a corresponding segment tree T.
1. Each leaf node contains an element A[i] of the input array where 0 <= i < N.
2. The root node represents the whole array A[0: N-1].
3. Internal represents merging of some leaf nodes i.e. some segment A[i: j] for 0 <= i < j < N.
4. An array is used to represent the segment tree T. T[0] represents a node that contains information about array A[0: N-1].
5. For a node in the segment tree at index i, the left child is at index 2*i, the right child is at index 2*i + 1, and the parent at index i/2.
Operations in Segment Trees
Segment supports two operations.
1. Update: To update a particular element in the array A[ ] and reflect the corresponding changes in the associated segment tree T.
2. Query: To query over an interval or segment of array A[ ] and return the answer to our problem ( it may be minimum/maximum/summation etc.)
Implementation
Build()
We start building the segment tree from the root node and go down recursively. The root node represents the whole array. Then we divide the array range into two halves recursively. When only one element is left in the segment, it is considered a base case, and we update tree[node] as A[index].
When both left and right child are built, value of parent node is updated
(tree[parent] = tree[left] + tree[right]).
void build(int node, int start, int end){ if(start == end){ // Leaf node will have a single element tree[node] = A[start]; return; } int mid = (start + end) / 2; // Recurse on the left child build(node << 1, start, mid); // Recurse on the right child build(node << 1 | 1, mid+1, end); // Internal node will have the sum of both of its children tree[node] = tree[node << 1] + tree[node << 1 | 1]; }
Update()
This function updates the value at a specific index in the array. It also updates the corresponding segment tree.
We search for a node that contains the element to update. It is done recursively by going left or right according to the position of idx.
When coming back from recursion value of nodes on the path is also updated.
void update(int node, int start, int end, int idx, int val){ // Base Case if(start == end){ A[idx] += val; tree[node] += val; return; } int mid = (start + end) >> 1; // If is idx is present in the left child, recurse on [start, mid] if(start <= idx and idx <= mid){ update(node << 1, start, mid, idx, val); } // If is idx is present in the right child, recurse on [mid+1, start] else{ update(node << 1 | 1, mid+1, end, idx, val); } // Parent node will be sum of left & right child. tree[node] = tree[node << 1] + tree[node << 1 | 1]; }
Query()
Query function is usually called over a range (here ‘l’ to ‘r’). It returns the answer to the problem in a given range (maximum/minimum/summation etc.).
Three conditions are checked to query over a range.
i). If the range represented by the node is completely outside the given range: Simple return 0.
ii). If the range represented by the node is entirely inside the given range: Then we can simply return the value of this node and need not recurse further.
iii). If the range represented by the node is partially inside the given range, we further recurse to the right and left child of the current node. Finally, return the sum of both children.
int query(int node, int start, int end, int l, int r){ // Query range & node range are completely disjoint. if(r < start || end < l) return 0; // Complete overlap if(l <= start and end <= r){ return tree[node]; } // Some overlap. int mid = (start + end) >> 1; int p1 = query(node << 1, start, mid, l, r); int p2 = query(node << 1 | 1, mid+1, end, l, r); return (p1 + p2); }
You can use mentioned templates of Segment tree and Lazy Segment tree in competitive programming contests( Segtree, LazySegtree )
FAQs
- What is a Segment Tree?
A Segment tree is a data structure that stores information about array segments and allows efficient processing of range queries along with updates.
- What is the time complexity of insertion and query in a Segment Tree?
The time complexity of insertion and deletion in a Binary Indexed Tree containing N elements is O(logN).
- What is the advantage of Fenwick tree over Segment tree?
The main advantage of the Fenwick tree is that it requires less space, is relatively simple to implement, and has concise code.
- What is the disadvantage of the Fenwick tree over the Segment tree?
We can only use the Fenwick tree in queries where L=1. Therefore it cannot solve many problems.
Key Takeaways
Cheers if you reached here!!
This article gave a simple introduction on the Segment tree. Segment tree!! | https://www.codingninjas.com/codestudio/library/introduction-to-segment-trees | CC-MAIN-2022-27 | refinedweb | 936 | 70.13 |
How can I overcome this key word error?
enter code here # -*- coding: utf-8 -*- import math import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.animation as animation fig1=plt.figure() ax=plt.axes(xlim=(-10,10), ylim=(-10,10)) line,=ax.plot([],[],lw=1) """def init (): line.set_data([],[]) return line,""" dt=0.001 X=[] Y=[] r=float(input("Enter the radius :: ")) w=float(input("Enter angular frequency :: ")) def run(data): t=0 while w*t<=2*math.pi: x=r*math.cos(w*t) y=r*math.sin(w*t) X.append(x) Y.append(y) t=t+dt line.set_data(X,Y) return line, line,=ax.plot(X,Y,lw=2) FFMpegWriter = animation.writers['ffmpeg'] writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800) anim=animation.FuncAnimation(fig1,run,frames=200,interval=20,blit=True) anim.save('amim.mp4',writer=writer)
The error message shown is ::
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/tathagata/anaconda3/lib/python3.4/site- packages/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile execfile(filename, namespace) File "/home/tathagata/anaconda3/lib/python3.4/site- packages/spyderlib/widgets/externalshell/sitecustomize.py", line 85, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace) File "/home/tathagata/Documents/Python scripts/circleamim.py", line 35, in <module> FFMpegWriter = animation.writers['ffmpeg'] File "/home/tathagata/anaconda3/lib/python3.4/site-packages/matplotlib/animation.py", line 81, in __getitem__ return self.avail[name] KeyError: 'ffmpeg'
I use anacoda distribution and SPYDER as my IDE. I have seen the many solutions related to key errors. But the movie wont run. How can I make the movie to run? I hope there are no other logical errors.
First install
ffmpeg and add path to
ffmpeg
# on windows plt.rcParams['animation.ffmpeg_path'] = 'C:\\ffmpeg\\bin\\ffmpeg.exe' # on linux plt.rcParams['animation.ffmpeg_path'] = u'/home/username/anaconda/envs/env_name/bin/ffmpeg'
Note for linux users: The path for
ffmpeg can be found by simply using
which:
which ffmpeg
Also instead of
FFMpegWriter = animation.writers['ffmpeg'] writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800)
I just used
writer = animation.FFMpegWriter()
How can I overcome this key word error?, First install ffmpeg and add path to ffmpeg # on windows plt.rcParams['animation.ffmpeg_path'] = 'C:\\ffmpeg\\bin\\ffmpeg.exe' # on linux plt. You can help protect yourself from scammers by verifying that the contact is a Microsoft Agent or Microsoft Employee and that the phone number is an official Microsoft global customer service number. Site Feedback
It seems that
ffmpegis not installed on your system. Try the following code:
import matplotlib.animation as animation print(animation.writers.list())
It will print out a list of all available MovieWriters. If
ffmpegis not among it, you need to install it first from the ffmpeg homepage.
What is the use of the 'this' keyword in Java?, Java "THIS" Keyword Keyword 'THIS' in Java is a reference variable that of constructor otherwise compiler will raise compilation error and only one this() In this article, we are going to describe some of the most common SQL syntax errors, and explains how you can resolve these errors.
If you have Homebrew, literally just run the command
brew install ffmpeg
And Homebrew will take care of the rest (dependencies, etc). If you don't, I would recommend getting Homebrew or something like it (apt-get on Linux is built in, or an alternative on OS X would be Macports)
CodeNotes for C#, As a result, the aforementioned error is generated. The Base Keyword One way to overcome this problem is to simply give the Fruitclass a default noargument First, let's distinguish between the types of errors: most compilers will give three types of compile-time alerts: compiler warnings, compiler errors, and linker errors. Although you don't want to ignore them, compiler warnings aren't something severe enough to actually keep your program from compiling.
I have also posed with same problem(keyError: 'ffmpeg') but instead of using anakonda, I used IDLE3. So, first i checked for 'ffmpeg' in terminal it wasn't installed so installed it.
Using:
sudo apt install ffmpeg
and when I run my
save_animation program, it worked generating animation files in '.mpeg' format.
Wrong Page Ranking for a Keyword? Here's How to Correct It, Wrong Page Ranking for a Keyword? Here's How to Overcome It. February 14, 2020. Wrong page ranking for the keyword. John is furious. Looking at the screen The first line searches for any event that has "error" in it, providing a first approximation to what you want. The second line uses a regular expression to find exactly the string "** ERROR =>". Note that '\s' denotes whitespace.
Security with Intelligent Computing and Big-data Services: , The well-known open problem in public key encryption with keyword search is To overcome this problem, the original framework must be changed slightly. If you have moved all the way up to the website's home page, try to run a search for the information you're looking for. If the site doesn't have a search function, try navigating to the page you want using category links to dig deeper into the site.
Java Software Errors: How to Avoid 50 Code Issues in Java, This Java software error message is one of the more helpful error messages. It explains how the method signature is calling the wrong.
Gentle Explanation of "this" in JavaScript, It provides better security and stronger error checking. To enable the strict mode place the directive 'use strict' at the top of a function body. Once. | http://thetopsites.net/article/50884871.shtml | CC-MAIN-2020-40 | refinedweb | 938 | 50.84 |
The single biggest problem in the WS space today is data and service versioning. I've been thinking about this problem for years now, and I finally came to an answer that is simple, straight-forward and plays by all the rules. The inspiration came from Henry Thompson's presentation at the XSD workshop that happend last year. I also reread some pieces of the XSD spec, where he dropped some hints about this model. My current, and I hope final, solution to this problem grew from there.
Most OO folks assume that an XML instance is associated with a single XSD. Most XML people do not. Rather an XML instance may be valid according to a whole range of XSDs. In the case of versioning, those XSDs are related in a simple way. They all share the same target namespace. Each new version may add new top-level constructs (elements, types, groups, etc.) and extend existing constructs with optional content. The first sort of change is okay because it doesn't change the transitive closure of any existing constructs so it won't break clients (with a little caveat that a wildcard matching the target namespace has to be assume match things that may be added in a future version). The second sort of change is okay because the extensions are optional. Instances created based on an earlier schema version don't have those elements, but that's okay. Any other changes to existing definitions require a new schema with a new target namespace.
The next problem is what to do about instances of a new version of the schema that are sent to a consumer built with an old version of the schema. In this case there may be extra elements that the consumer didn't know about when it was created. This case arises all the time with Web services, where a new service has to return data to the old client. The solution to this problem is for the client to ignore the extra data. Both the .NET XML-to-object mappers (XmlSerializer and DataContractSerializer) do this. JAXB 2.0 (which is used by JAX-WS) has an option to do this. In other words, if your code doesn't do this already, it will be able to soon.
Ah, but what about schema validation? If an application built with the older version of the schema attempts to validate data sent based on the newer version of the schema, there may be extra elements in the instance that will cause validation to fail. The first attempt to fix this involved adding a wildcard to accept this extra content and then to introduce either hierarchical or inline delimiters to work around the determinism constraint of schema. The goal was to stop the schema validation error from occurring. This solution leads to schemas and marshalers that are too clever by half and create real issues for interoperability between toolkits. Luckily, there is another solution.
The XSD spec does not define validity as a single boolean value. Nor does it say how a system has to react to validation issues. When you validate a document, the processor tells you whether validation was attempted for a given element. If it was attempted, it tells you what schema component was used, and whether the element was valid, invalid, or unknown (because it isn't in the schema). You can decide what to do with that information.
Most of the time, today, people build validation logic that treats anything other than valid elements as an error and throw an exception. But you could be more flexible. For instance, you could build a validator that, upon encountering an unknown element in a sequence, could simply ignore it and all others in the sequence until the parent element's closing tag. “Ignore“ could mean either don't throw an exceptions or it could mean actually filter that data out of the element stream. The important thing is that during validation, if you detect extra stuff, you let it slide. Of course, for the elements you do know about, you can validate their content up until you hit extra unexpected data. I have a .NET 2.0 implementation of this working now, hopefully I'll have time to clean it up and post it soon.
So, my model for versioning comes down to these points:
Really, this is simply another variation of Postel's law: be careful in what you produce and flexible with what you receive, which is the basis for all the successful distributed systems I know of.
I'm very happy with this model. I think it is pretty intuitive and it works with today's tools. It also doesn't attempt to twist instance around the XSD UPA requirement nor does it attempt to change the semantics of XSD or XSD validation. It only argues for a different reaction to issues that arise during validation, which is totally reasonable.
8MKuQu <a href="nrpxxkflogmo.com/.../a>, [url=]ffrbqxpyiuyv[/url], [link=]pqqwnjgzfsgd[/link],
ex2LOL <a href="gygjqkgdnaky.com/.../a>, [url=]mhlgyxcdvhhl[/url], [link=]gkwkdedhxutz[/link],
orfbj8 <a href="agergrgkasuy.com/.../a>, [url=]kpugblsakbri[/url], [link=]agdkwtoxwdgm[/link], | http://www.pluralsight.com/community/blogs/tewald/archive/2006/04/14/21733.aspx | crawl-002 | refinedweb | 864 | 63.59 |
Name | Synopsis | Description | Return Values | Errors | Usage | Attributes | See Also
#include <stdlib.h> void exit(int status);
void _Exit(int status);
#include <unistd.h> void _exit(int status);
The exit() function first calls all functions registered by atexit(3C),(3C) function is made that would terminate the call to the registered function, the behavior is undefined.
If a function registered by a call to atexit(3C) fails to return, the remaining registered functions are not called and the rest of the exit() processing is not completed. If exit() is called more than once, the effects are undefined.
The exit() function then flushes all open streams with unwritten buffered data, closes all open streams, and removes all files created by tmpfile(3C).
The _Exit() and _exit() functions are functionally equivalent. They do not call functions registered with atexit(), do not call any registered signal handlers, and do not flush open streams.
The _exit(), _Exit(), and exit() functions terminate the calling process with the following consequences:
All of the file descriptors, directory streams, conversion descriptors and message catalogue descriptors open in the calling process are closed.(). A zombie process only occupies a slot in the process table; it has no other space allocated either in user or kernel space. The process table slot that it occupies is partially overlaid with time accounting information (see <sys/proc.h>) to be used by the times(2) function.
Termination of a process does not directly terminate its children. The sending of a SIGHUP signal as described below indirectly terminates children in some circumstances.
A SIGCHLD will be sent to the parent process.
The parent process ID of all of the calling process's existing child processes and zombie processes is set to 1. That is, these processes are inherited by the initialization process (see Intro(2)).
Each mapped memory object is unmapped.
Each attached shared-memory segment is detached and the value of shm_nattch (see shmget(2)) in the data structure associated with its shared memory ID is decremented by 1.
For each semaphore for which the calling process has set a semadj value (see semop parent process has set its SA_NOCLDWAIT flag, or set SIGCHLD to SIG_IGN, the status will be discarded, and the lifetime of the calling process will end immediately.
If the process has process, text or data locks, an UNLOCK is performed (see plock(3C) and memcntl(2)).
All open named semaphores in the process are closed as if by appropriate calls to sem_close(3C). All open message queues in the process are closed as if by appropriate calls to mq_close(3C). Any outstanding asynchronous I/O operations may be cancelled.
An accounting record is written on the accounting file if the system's accounting routine is enabled (see acct(2)).
An extended accounting record is written to the extended process accounting file if the system's extended process accounting facility is enabled (see acctadm(1M)).
If the current process is the last process within its task and if the system's extended task accounting facility is enabled (see acctadm(1M)), an extended accounting record is written to the extended task accounting file.
These functions do not return.
No errors are defined.
Normally applications should use exit() rather than _exit().
See attributes(5) for descriptions of the following attributes:
The _exit() and _Exit() functions are Async-Signal-Safe.
acctadm(1M), Intro(2), acct(2), close(2), memcntl(2), semop(2), shmget(2), sigaction(2), times(2), waitid(2), atexit(3C), fclose(3C), mq_close(3C), plock(3C), signal.h(3HEAD), tmpfile(3C), wait(3C), wait3(3C), waitpid(3C), attributes(5), standards(5)
Name | Synopsis | Description | Return Values | Errors | Usage | Attributes | See Also | http://docs.oracle.com/cd/E19082-01/819-2241/6n4huc7j4/index.html | CC-MAIN-2016-50 | refinedweb | 610 | 54.32 |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello :)
I am trying to map light sensor readings to the range 0-255, and draw an interactive circle from the values. What I am experiencing is that the values look a bit odd (either 10.0 or 119.0) and they are blinking together with the blinking TX light on my arduino uno. There seems to be no effect when covering the light sensor or exposing it to more light.
Originally, I set up the arduino arrangement using the Arduino IDE just reading and mapping the values and sending them to the Serial monitor. They seemed reasonable; highest light value about 700 and lowest value with my hand covering about 100. These were mapped well to 0-255. I could, however, only manage to display these with Serial.println and when I tried Serial.write black diamond shapes with question marks appeared instead.
I have closed the Arduino IDE, I have double checked that usb port is the right one... I am using a mac and the exercise workbook that advised I might need to add the following code to Terminal.app
sudo mkdir -p /var/lock
sudo chmod 777 /var/lock
which I also added (hope this is sensible and that I haven't messed up my computer).
The code I am trying with is:
import processing.serial.*; Serial port; float value=0; float maxsize=200; int ysize=int(maxsize+100); int xsize=int(maxsize+100); float diam; void setup() { size(200,200); stroke(0,255,0); noFill(); strokeWeight(2); smooth(); println(Serial.list()); port=new Serial(this,Serial.list()[11],9600); //have doubled checked that the port is the right one } void draw() { background(107,17,77); if(0<port.available()) { value=port.read(); } println(value); diam=map(value,0,255,0,maxsize); pushMatrix(); translate(width/2,height/2); ellipse(0,0,diam,diam); popMatrix(); }
I am quite new to programming and any help will be very much appreciated! Thank you so much and happy holidays.
Answers
Your reading your arduino data from processing without splitting your data input. You might need something like:
or to manually check the content of value @ line 29 to split the data stream into valid tokens. I am guessing you are appending every value with a new line separator. I will also suggest to move line 25 into the if block in line 27: you want to update the diameter only upon receiving new data. Otherwise if your data stream rate is slower than draw() rate, you effect will be displayed for short periods of time. This is just a suggestion but you might use it the way it is right now.
The mapping from range [100,700] to [0,255] is being done in your arduino code?
Kf | https://forum.processing.org/two/discussion/19931/mapping-light-sensor-readings-and-drawing-interactive-circle-from-values | CC-MAIN-2020-45 | refinedweb | 478 | 65.22 |
I?
#!/usr/bin/perl
use strict;
use warnings;
use Address;
my $c = new Address;
$c->address( [
'137 PR 1101',
'Sun Valley MHP - FM 205',
'FooHaHa, TX 76401' ] );
print $c->state;
[download];
[download];
[download]
A bit of paranoia can be healthy.
One of the more robust and interesting AUTOLOADs I've seen is in CGI.pm (actually, in CGI::_compile, which CGI::AUTOLOAD delegates to). I recommend it for careful study. It shows a few edge cases that many examples don't cover.
I see that your AUTOLOAD doesn't actually introduce any new symbols in a package's namespace. Rather, it's just a backstop that make indirect subroutine calls. Is this what you intended?
Rather, it's just a backstop that make indirect subroutine calls. Is this what you intended?
Yes, I originally wrote the AUTOLOAD for Address.pm and thought, "Hey, I could stick this in a base class and use it to supply automatic methods for other classes as well." Extending Laziness with OO.
HTH,
Charles K. | http://www.perlmonks.org/index.pl?node_id=142852 | CC-MAIN-2015-18 | refinedweb | 170 | 68.67 |
25 April 2013 17:16 [Source: ICIS news]
HOUSTON (ICIS)--?xml:namespace>
Earlier this week,
“[The measure] is clearly a positive sign of more support from the government; they realise that the profitability of ethanol needs to be higher for millers to invest,” Bunge CEO Alberto Weisser said during the company’s 2013 first-quarter results conference call.
Bunge, for its part, is in a good position as it managed to reduce costs, but for
At this time, Bunge cannot yet quantify the effects the measure will have on its sugar and bioenergy business, Weisser said.
“It’s too early [to say], because the devil is in the details,” he said.
The stimulus involves a tax reduction – partially among millers, partially among distributors – as well as a tax credit for millers and distributors, he added.
Earlier on Thursday, Bunge reported a sharp increase in 2013 first-quarter gross profit in its sugar and bioenergy segment – to $57m (€44m), up from $8m in the 2012 first quarter. The segment’s sales were $1.1bn, up from $881m in the year-earlier | http://www.icis.com/Articles/2013/04/25/9662708/brazil-ethanol-stimulus-a-positive-sign-for-industry-bunge.html | CC-MAIN-2014-52 | refinedweb | 180 | 58.32 |
Name
CYGPKG_DEVS_FLASH_M68K_MCFxxxx_CFM — eCos Flash Driver for MCFxxxx CFM On-chip Flash
Description
Some members of the Freescale MCFxxxx family, for example the MCF5213,
come with on-chip flash in the form of a ColdFire Flash Module or CFM.
This package
CYGPKG_DEVS_FLASH_M68K_MCFxxxx_CFM
provides an eCos flash device driver for CFM hardware. Normally the
driver is not accessed directly. Instead application code will use the
API provided by the generic flash driver package
CYGPKG_IO_FLASH, for example by calling functions
like
cyg_flash_program.
Configuration Options
The CFM flash driver package will be loaded automatically when
configuring eCos for a target with suitable hardware. However the
driver will be inactive unless the generic flash package
CYGPKG_IO_FLASH is loaded. It may be necesary to
add this generic package to the configuration explicitly before the
driver functionality becomes available. There should never be any need
to load or unload the CFM driver package.
The driver contains a small number of configuration options which application developers may wish to tweak.
Misaligned Writes
The CFM hardware only supports writes of a whole 32-bit integer at a
time. For most applications this is not a problem and the driver
imposes this restriction on higher-level code, so when calling
cyg_flash_program the destination address must be
on a 32-bit boundary and the length must be a multiple of four bytes.
If this restriction is unacceptable then support for misaligned writes
of arbitrary lengths can be enabled via configuration option
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_MISALIGNED_WRITES.
The implementation involves reading in the existing flash contents and
or'ing in the new data. The default behaviour is to leave this
disabled since most applications do not require the functionality and
it just adds to the code size.
Locking
CFM has a somewhat unusual approach to implementing lock and unlock
support. The first 1K of on-chip flash is normally reserved for the
M68K exception vectors, on the assumption that the processor will or
may boot from here. This is immediately followed by a
hal_mcfxxxx_cfm_security_settings data
structure at offset 0x400. The structure has a 32-bit field
cfm_prot which determines the initial
locking status. The whole CFM flash array is split into 32 sectors.
Each bit in
cfm_prot determines the initial
locked state of all blocks within that sector, with 1 for locked and 0
for unlocked. Locking and unlocking can only affect a whole sector at
a time, not individual flash blocks (unless of course the flash is
organized such that there exactly 32 flash blocks).
In typical usage the on-chip flash will be used for bootstrap and hence the security settings are part of the boot image. The default security settings are supplied by the processor or platform HAL and will be such that all flash sectors are unlocked. This is the most convenient setting when developing software. However an application can override this and thus lock part or all of the flash.
The driver provides two configuration options related to flash
locking.
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_AUTO_UNLOCK
causes all of flash to be unlocked automatically during driver
initialization. This gives simple and deterministic behaviour
irrespective of the current contents of the flash security settings
structure. However it leaves the flash more vulnerable to accidental
corruption by an errant application.
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_SUPPORT_LOCKING
enables support for fine-grained locking using the generic functions
cyg_flash_lock and
cyg_flash_unlock. This provides more protection
against errant applications, at the cost of increased application
complexity.
RAM Functions and Interrupts
When performing a flash erase or program operation part or all of the flash may become inaccessible. The exact details of this vary between ColdFire processors. Obviously this means that the low-level functions which manipulate the flash cannot reside in the same area of flash as any blocks that may get erased or programmed. Worse, if an interrupt happens during an erase or program operation and the interrupt handler involves code or data in the same area of flash, or may cause a higher priority thread to wake up which accesses that area of flash, then the system is likely to fail. To avoid problems the flash driver takes two precautions by default:
- The low-level flash functions are located in RAM. If necessary they are copied from ROM from RAM during system initialization.
- The low-level flash functions disable interrupts around any code which may leave parts of the flash inaccessible.
This combination avoids problems but at the cost of increased RAM
usage and often increased interrupt latency. In some circumstances
these precautions are unnecessary. For example suppose there is 512K
of flash split into two logical blocks of 256K each, such that an
erase or program operation affects all of one logical block but not
the other. If the application has been arranged such that all code and
constant data resides in the bottom 256K and flash operations are only
performed on the remaining 256K then there is no need to place the
low-level flash functions in RAM. The configuration option
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_FUNCTIONS_IN_RAM
can then be disabled. In a similar scenario, if the top 256K of flash
are only ever accessed via the flash API then there is no need to
disable interrupts: the generic flash layer ensures only one thread
can perform flash operations on a given device via a mutex. The
configuration option
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_LEAVE_INTERRUPTS_ENABLED
can then be enabled.
Additional Functionality
The driver exports two functions which offer functionality not accessible via the standard flash API:
#include <cyg/io/mcfxxxx_cfm_dev.h> externC void cyg_mcfxxxx_cfm_unlockall(void); externC cyg_bool cyg_mcfxxxx_cfm_is_locked(const cyg_flashaddr_t addr);
The first can be used to unlock all flash sectors, effectively bypassing any locking set by the hal_mcfxxxx_cfm_security_settings structure. The second can be used to query whether or not the block containing the specified address is currently locked. Both functions should be called only after flash has been initialized.
Instantiating a CFM Flash device
The CFM package only provides the device driver functions needed for manipulating CFM flash. It does not actually create a device instance. The amount of on-chip flash varies between ColdFire processors and the driver package does not maintain any central repository about the characteristics of each processor. Instead it is left to other code, usually the processor HAL, to instantiate the flash device. That makes it possible to add support for new processors simply by adding a new processor HAL, with no need to change the flash driver package.
The CFM package provides a utility macro for instantiating a device. Typical usage would be:
#include <cyg/io/mcfxxxx_cfm_dev.h> CYG_MCFxxxx_CFM_INSTANCE(0x00000000, 0x0003FFFF, 2048);
The first two arguments specify the base and end address of the flash in the memory map. In this example there is 256K of flash mapped to location 0. Typically the base address is set via the FLASHBAR system register and the size is of course determined by the specific ColdFire processor being used. The final argument is the size of a flash block, in other words the unit of erase operations. This will have to obtained from the processor documentation.
The
CYG_MCFxxxx_CFM_INSTANCE macro may
instantiate a device with or without software locking support, as
determined by the driver configuration option
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_SUPPORT_LOCKING
.
If for some reason the
CYG_MCFxxxx_CFM_INSTANCE
is inappropriate for a specific processor then the mcfxxxx_cfm_dev.h
header file exports all the device driver functions, so code can
create a flash device instance explicitly. | http://doc.ecoscentric.com/ref/mcfxxxx-cfm.html | CC-MAIN-2019-30 | refinedweb | 1,212 | 52.7 |
See also: IRC log
<Marsh> Introductions
<Marsh> We go around the room
<plh-wsaddr> Scribe: GlenD
David gets "volunteered" as our first Scribing Victim
(logistics discussion)
Agenda Review
<plh-wsaddr> Absent: Harris
Hugo steps resolutely to the front of the room, pulls out his +5 Vorpal Laptop, and proceeds to give a presentation
<plh-wsaddr> Presentation at
Jonathan: Mark, are you also representing BEA on this group?
Mark: I'd hesitate to represent BEA and would rather stay neutral since we're on a tight schedule. Will make technical commentary at times, but leave representing BEA to David.
Input comes from variety of places (as per presentation)
Jonathan describes WS Coordination Group
Mark: What does it mean to "refine" the spec?
Bob: OED says basically every option short of recreating every
molecule....
Bob: Hope is that we can start with this raw material and shift it into
a direction that works for us. Hopefully we can have a mature attitude
towards how much we can do to it - should be open to good tech
discussion, but in the spirit of getting it done quickly.
Mark: My reading is that it's the starting point. We can't say refine
means you can't change it... we've already got specific issues, so it
seems like we're in agreement there. On the other hand, we're on a
tight schedule so we can't refine forever.
Mark: "comment and review"...how about that in terms of meaning?
Hugo: WS-MD has some different solutions. If there are things that are
in-scope that MD does differently/better than WSA, then we should
address the issue.
Mark: +1. MD is a significant source of use-cases and issues. It
informs us, but we don't simply choose between the two - we start with
WSA.
Discussion of deliverable scoping
Jeff: How abstract is this supposed to be? Has to assume some
addressing model (URLs, TCP/IP...), right?
Mark: This is pretty much a bag for anything above SOAP/WSDL.
Anish: Abstract refers to message properties, not EPR, right? EPR is
syntax...
Mark and Gudge : EPR is abstract
systinet: How do we talk about compliance to abstract spec?
Mark: Good question. We'll talk about this tomorrow when we discuss how
to go from here to there (get the spec to rec).
Anish: separate out SOAP 1.2 and SOAP 1.1 bindings?
Mark: That brings out another issue. It's not common W3C policy to talk
about non-W3C specifications/recs....
Philippe: SOAP 1.1 is already normatively referred to in SKMS. As long
as it's optional, it's OK to have these things in W3C recommendations.
Discussion of what's out of scope, including how to coordinate with
external groups which are working on things like new MEPs, callback, etc
Marc: Are we going to explicitly design extensibility for this stuff, or
just assume it'll work?
Paco: Definitely shouldn't be a closed set of MEPs...
Marc: Typically there are explicit extensibility methods built into a
spec...
Gudge: Addressing has implicit extensibility, since it's build on SOAP
Marc: That only applies to SOAP binding
Jeff: Where are these MEPs defined?
Various: WSDL...
Jeff: OK, if we agree that certain MEPs are out there and reasonable,
and we can't do them, that's the time we need to make changes.
(general nodding of heads)
"The Scary Slide" - Schedule
David: Have seen schedules slip before, but perhaps this time since we
have so much previous interop work, that can help us.
Mark boldly cuts off the schedule discussion, and suggests we simply
suspend disbelief for now and work towards the schedule we have in front
of us.
Jonathan: The editor's copies will be available on the web, right?
(nodding)
Jeff: First public WD is a good thing because of patent policy, in
addition to other reasons. We should do one before LC.
Jonathan: Maybe let's do that immediately? Change namespace, get it in
XML, etc...
(Dave makes fabulous joke)
<scribe> ACTION: Hugo to research patent implications of publishing first WD
Mark: proposed first task is to take WSA and split it into three specs.
Will discuss that in broadest possible terms here, then instruct the
editors to go ahead.
Mark: Editors should do split, then we should publish initial drafts.
OK?
(nodding heads)
(brief discussion on good standing - is it OK to attend f2f's by phone?
consensus is yes)
(discussion of security in the abstract spec)
(discussion of SOAP binding - "how to stick properties into a
SOAP: Envelope" and SOAP faults)
(discussion of WSDL binding)
Mark: Is that enough for now?
Jeff: Is it obvious to everyone which pieces of WSA go where?
Mark: That's something we should let the editors try.
Gudge: Already taken a first stab at which sections go where. Will mail
it out as soon as the network works....
BREAK
Marc: What's the relationship between the address, the sub-address, and
the architecture of the WWW?
Gudge: All will be made clear in a few slides...
Discussion of endpoints, ref props
Address URI always gets you to a transport listener somewhere.
Refprops/params always do dispatch within that (and do not relate to the
transport)
Anish: is order of refprops/params significant?
Gudge: nope
Discussion of the fact that wsa:Address URIs don't necessarily map
directly to network addresses
Marc: Can't have this be vague - if I see an EPR with an Address, I
should be able to go to it without knowing anything extra about lookup
repositories, etc.
Glen: This isn't really germaine, since the spec doesn't say anything
about it and it's also true for browsers/etc....
Anish: Relationship between URI in address field and URI in WSDL
port/endpoint?
Gudge: we need to define that. In our experience it's the same.
Marc: are ref props/params relatively static?
Gudge: params are dynamic, props are static... could argue it ether way
though
Anish: Why isn't the To header an EPR?
Gudge: Because we wanted to leverage the SOAP processing model to
process RefProps
Anish: In an EPR you can have service/port qnames. Wouldn't it be
better to have To be an EPR so this stuff can be conveyed to the
listener?
Paco: EPR is a package for runtime info. Different from actual usage...
Gudge: Anish, are you looking for additional headers for service/port?
Anish: We need to decide how that might work, but maybe.
jonathan: Coudn't you use refP's for this?
Anish: Yes, but you're duplicating a separate (in the EPR) concept
Marc: What's the processing model of the To header?
Gudge: Almost like URL's and Host: header in HTTP. Software checks the
To against some concept of "me".
Jonathan: Redundant info for detecting errors
Marc: is this meant for the "next" role, or really at the ultimate
receiver? Should SOAP intermediaries be able to see this?
ISSUE: Marc: It's an issue that wsa:To must be there if it might be
duplicate information....
Anish: You could compose a lot of info into the URI (service/port/etc)
Gudge: Yes, but there's no fixed line which says "this stuff goes in the
To, this stuff is ref props"
Anish: Sender generally decides on mustUnderstand/role/etc for
headers... how does he decide for ref props?
Gudge: He doesn't - if they're there, they must be parroted exactly,
including attributes like MU/role?
Gudge: Because you'd need to reproduce the SOAP processing model incl
role/MU/etc
Glen: I don't see why that would be the case. I'd like to see some
cases that prove that assertion
Anish: +1
(discussion of using ref props which overload WS-Security, etc)
(discussion of sending updated EPRs)
Marc: This seems like it might warrant a standard "continueTo" header,
or "redirectTo"...
Gudge: PortType might change - for instance, transaction might give you
back an EPR to a different PortType with commit/rollback....
Marc: Transaction is only one usage...
Rebecca: How do I know how to construct a message for the new endpoint?
Gudge: If they're the same (differing only in refparams), you send the
same msgs as the original endpoint. Otherwise, it's
application-specific... you get WSDL hints.
(discussion of using WSDL <service> as EPR)
(discussion of using <replyTo> to implement WSDL inout)
Anish: Seems like we should have a constraint that says ReplyTo
shouldn't violate the WSDL binding.... (shouldn't send response over
SMTP for an HTTP request if WSDL says SOAP-over-HTTP)
Gudge: Yes, but I'm not sure what that would look like.
(anonymous address URIs)
Marc: Why not just omit the address instead of using a special anonymous
one?
Gudge: That might work....
END PRESENTATION
LUNCH
Anish will present WS-MD, focussing on some of the differences between WS-MD and WS-A.
<dorchard> I did a comparison at
Anish: Four parts to WS-MD.
- WSRef
- Abstract Message Delivery Properties
- Mapping of abstract properties to WSDL 1.1/2.0 MEPs
- Composite MEPs. Combining WSDL MEPs to build higher-level patterns, including callback pattern (out of scope in the WS-A charter.
scribe: WSRef determines where to send the
message, what messages can be sent, and how to send the message (binding)
... Reuses syntax defined in WSDL 2.0/1.1, backporting WSDL 2.0 service reference concepts to WSDL 1.1.
... Doesn't invent new stuff, just reuses whats in WSDL.
... Rationale is that written code can be repurposed.
... Abstract Message Delivery Properties enable message to be delivered to the right place, enabling correlation within an MEP.
... Seven properties: MessageOriginator, MessageDestination, ReplyDestination, FaultDestination, MessageID, MessageReference, OperationName
... The mapping of AMDP to SOAP is simple - each property maps to a header block. Not opaque, you can stick in mustUnderstand, reinsert.
... The mapping of AMDP to WSDL MEPs says what properties must be present for each message participating in a MEP.
... Callback pattern is an example of a composite MEP. It implements the WS-I Basic callback scenario, which correlates two 'in-out' MEPs or two 'in' MEPs.
... You can figure out how two separate WSDL operations are correlated.
... Similarities between WS-MD, WS-A. Intention is very close. Both define a way to reference an endpoint. Both define Message Information Headers/Abstract Message Delivery Properties.
... 6 of the 7 properties do essentially the same thing.
... OperationName is sort of similar to wsa:Action.
... you can have the same Action value for two different operations. OperationName is required to be unique.
... Biggest difference is between EPR and WSRef. They do things in quite a different way.
... The obvious difference is that EPR has a WS-Policy element. WSRef allows you to put in whatever WSDL allows you to put in.
... EPR allows you to specify additional information that must be sent with a message. WS-MD relies on WSDL to provide sufficient information to talk to a service.
Paco: If you were doing sessions or something
stateful, would you regenerate the WSDL>
... Some stuff that differentiates my interaction from someone elses, I'd add some more information to the existing WSDL?
Anish: You may, or you might have a spec for contextualization of interactions.
Paco: Would that show in the service reference or not?
Anish: If it's coming back to the same service,
you don't need to generate a new service element.
... You could generate a separate service for each interaction, but that would be difficult.
... Various use cases - could be completely dynamic, sender doesn't know what is coming back in the service element, or it may expect something.
... WSRef is the minimal thing you would need to reference a Web service. Doesn't allow you to package in additional parameters or properties.
... That doesn't keep you from building params/props at the application layer.
Greg: Now you've pushed that complexity to the application level, and complicated the programming model there.
Anish: That reflects the different points of
view of the two specs.
... You could write another spec (see WS-RF at OASIS) to build a layered architecture on this.
... Those who don't need more complex stuff can use this.
DaveO: Cookies are a good analogy. Web site
might want cookies, browser might not support them. There is a separation
between URIs and cookies, same in WS-A between Ref Props and URI.
... It is layered in EPR in a similar way as in the Web architecture.
Marc: Is the expectation that if I don't use Ref Props/Params I will get a lower level of service>?
DaveO: You might provide a fallback. I don't think you would. I think you will require Props/Params in order to enable the full quality interaction.
Marc: Is support for Props/Params a conformance requirement?
Anish: Set Cookie and Cookie Header is a separate spec. Can be the same in addressing.
Paco: Many people made an assumption that WS-A is making contextualized URIs, the Cookie analogy shows that this is information you wouldn't provide iin the URI.
DaveO: Many applications take advantage of cookies for good reasons (sometimes bad). Site authors have the choice of using URIs, or URIs + cookies.
Anish: But the specs are independent.
... At one level EPR allows you to do things very simply, only mandatory thing is the Address.
... The WS-MD approach is that in order to communicate with a Web Service you need a whole lot more information than just the URL.
... Maybe there's already metadata available through some other means.
... If there's more information you need, the addressing spec should provide you a way to get it.
... If a service already has the information, great. If not, you should be able to go get it.
Rebecca: Need to include that information.
Philippe: Or provide a query mechanism.
Jeff: Query is inefficient.
Anish: Several approaches to get metadata -
WS-MD takes one. You can go fetch the data.
... MEX defines some operations. Maybe that's another way.
<RebeccaB> Need to include that information in dynamic EPRs or additional roundtrips required
Anish: Another big difference. Porttype name
is optional in WS-A. You might not be able to do anything with it.
... You might have to query UDDI or something.
Paco: There are two different viewpoints, loosely coupled or allowing tightly coupled. Do we want everyone to pay the price for loose coupling.
Anish: WS-A defines some specific faults (WS-MD
does not), which appears to be a good thing,
... WS-MD specifies MEP mappings.
... WS-MD has callbacks - we should keep in mind that we don't preclude someone from using WS-A to define composite MEPs.
... Summary:
... Substantial similarities.
... EPRs and WSRefs come from two different places. WSRef is a reference to a _service_, EPR is a reference to an _enpoint_.
Rebecca: Given thought to other patterns such as high-availability; mulitple services behind a single endpoint?
Anish: Yes, but it's questionable as to whether
this should be exposed to the client.
... A session ID could tell where to go, or a service group could be exposed to the consumer.
... We should explore whether this mechanism needs to be within Addressing or built on top of it.
Jonathan: Worried about believing WSDL is sufficient for an interaction. Semantics is missing.
Glen: Might have a prequalified set of WSDLs.
Jeff: You need to distinguish between the
business and trust issues from the infrastructure issues.
... Semantic issue is kind of a red herring to this WG. It's not a solvable problem today.
... The dynamic case, once you've established the business and legal issues, is still interesting.
Rebecca: You might get back several choices,
e.g. bindings, which you can choose from. There might be alternatives within
the infrastructure part.
... Some might require multiple ports in a single reference. Talking to MQ takes multiple URIs.
... You can model it in WSDL but not in WS-A.
Paco: Why not?
Marc: Set your endpoint reference address to "anonymous" and include the portType and service.
[apologizes for not understanding this scenario and botching the minutes on it.]
Marc: Both have the same capabilities but they come from different viewpoints?
Anish: In terms of referencing a service they have the same capabilities.
Paco: In WS-MD you have a WSDL service element you restrict to a single port.
Anish: WSDL 2.0 there is no restriction. In WSDL 1.1 every port in that service must support the same portTYpe.
Paco: So the intention is that WS-MD can support more than one port.
MarkN: We have an issues list, we'll start populating it tomorrow. I'll maintain it for now.
MarkN: Let's continue some of the use cases
we've touched on earlier.
... Paco suggests we have different assumptions about URIs, which we'll talk about tomorrow.
... Can we talk now about what other people want out of WS-Addressing - lightweight? full-featured?
... From WS-A, it purports
"to identify Web service endpoints",
Paco: An example which may shed some light.
... BPEL life cycle model - you're going to interact with a long-running stateful interaction.
... typically you don't have a factory method, you just send a message and a business process interaction is spawned.
... From the BPEL process perspective, you spawn a process, how are you going to make sure the messages reach the right places?
... BPEL uses application data (correlation sets) to route messages.
... It would be better to have a solution that could be managed by the infrastructure, instead of the applciation, but supports the same model.
... For example, you may have a message that returns a customer number or some other important data. It would be nice to carry this in an EPR.
... Without the ability to qualify your reference you lose the context of the specific conversation.
... This is a very general, protocol-independent, mechanism that supports long-running conversations.
Rebecca: Sounds like your sending context information.
Greg: Could be context or something.
Glen: What do you mean by context? Something specific or general?
Paco: The example is that of a long-running conversation, which may have specific transaction contexts within it.
Glen: But the conversation itself has a long-running context.
MarkN: Can you see a service and a service instance having a different address?
Paco: Could be but...
Anish: Are you talking about a factory pattern?
Paco: No, explicitly no factory. There is no explicit instantiation mechanism.
Anish: What is the difference between service and service instance?
Paco: They share the front end. They share a WSDL definition, they may have different cookies.
Anish: If I have a service, I can send messages to that service. One of the fields might be a customer ID, going to the same service.
Paco: Then the application has to take care of it, which is fine, but we also want to allow the infrastructure to deliver the message correctly.
[Some discussion about terminology of "service" and "service instance" as relates to scoping of interactions.]
Paco: This is a use case, this is one pattern of use that we should support.
Anish: As long as you don't call it an instance of the service.
Paco: Use case has the same address, same service, same portType, same port, possibly different endpoint references.
Jeff: Do I have two instances of a service? Or one?
Glen: Mu, grasshopper.
Paco: In BPEL you'd say you have the same service.
Jeff: What's the identity model?
Paco: In BPEL, each instance is identified by a correlation set - a set of properties that are unique to that conversation.
David: You call those BPEL process instance.
... You can define in BPEL a service, you get a process instance when you get a correlation set.
Marc: Struggling with the difference between
ref props and ref params. Sounds like we're talking sessions here.
... Are different sessions different ref props or ref params.
Gudge: Depends on whether you want to change the metadata or not.
Paco: you have the same address, and
properties, you have the same portType.
... I'd typically use a ref property.
Gudge: Can't draw a line saying precisely which things should be params & props.
Anish: Can you have 2 EPRs with the same wsa:Address, same ref props but different porttype? The spec doesn't seem to restrict this.
Gudge: I'd say yes, but only if that endpoint accepts both sets of messages (portType A union portType B).
Anish: So if address is mapped, could it not be mapped differently depending on portType.
Gudge: You could, though that's a different question.
Anish: For equivalence of 2 EPRs, only address and ref props matter. Service, portType, etc. don't matter.
Gudge: Yes.
Jeff: All these questions about BPEL. This version came out a year after BPEL.
Paco: Yes, this model is a usecase, I already acknowledged that BPEL.
Jeff: There is a question about the identity model is, there's an implicit one in BPEL...
Gudge: There is one in WS-A also.
Jeff: we need to have a general architecture for an identity model for Web services. You see this converstation all over,.
Gudge: We don't need to do that here.
Glen: If we say these are the rules, you don't care about what happens within your machine. That's the magic of interop.
Jeff: You absolutely need to have that
agreement.
... Undocumented assumptions will make your app fall over, even if the infrastructure doesn't.
DaveO: I'm struck with the similarities with
URIs and Cookies. Tons of flexibility in constructing URIs, e.g the choices
between query params and frag IDs.
... If they want to compare URIs, put identity data before the #.
... There are about four different places you can extend.
... We've got similarities in WS-A.
... You must interpret an address from the context (<a href=""> vs. xmlns="".)
... Same in WS-A. We don't need to document the model sa long as they follow the rules of WS-A.
MarkN: Another use case: DNS-EPD.
... DNS Endpoint discovery - a mechanism for using DNS to discover and EPR for anything.
<hugo>
MarkN: We can identify specs that need thesse capabilities.
DaveO: And there may be use cases that aren't satisfied by the current raft of specs.
--- break ---
Telcon poll results: Monday UTC 8PM (Noon Pacific)
--- resuming ---
paco just stepped out...
Hang on.
Telcon exception next week Thursday Nov 3rd 12 Pacific. See mail.
After that we'll go with the Monday 12 Pacific slot.
MarkN: Requests for planning for Tech Plenary
Feb 28-March 4
... in Boston.
We have lots of overlap with WSDL, we'll avoid overlap and try for a joint session.
MarkN: We talked about BPEL for a while, and
DNS-EPD about discovery.
... other specs?
DaveO: There are WS-ReliableMessaging, WS-Reliability which we might be able to consider generically without prejudice.
<dims> ws-resource stuff in wsdm?
Paul: EPRs might be reused in other contexts.
Would we consider making EPRs a black-box, so you could replace our EPR
format with another one.
... How loose is our coupling with the EPR format?
Anish: An extensible addressing mechanism? WS-Reliability does that.
Glen: For interop, we should have one true way to do addressing. My company doesn't support having extensibility at this point.
Marc: We already have extensible props and params, the address is a URI. How much more do you need.
DaveO: What would motivate or demotivate it?
Glen: I can give you a demotivator.
... We don't want the outermost syntax for EPRs to be swappable - just as the SOAP envelope has a single format.
... This allows us to build a system with intermediary forwarding.
DaveO: Glen is focussing on EPRs and routing, previous use cases highlight other areas. A good list of use cases highlights different aspects.
Dims: Management, e.g. monitoring how much time
it takes for a message to go and come back.
... A single way to do things helps with management.
Glen: Products from different vendors will work with a generic manager.
Greg: Don't you want a single standard in all areas?
Glen: No, only for four things: policy, soap, wsdl, addressing.
Marc: Redirect use case.
... I'd like to see redirects at an application level rather than at the application level.
... e.g. session initiation.
e.g. I can use URI rewriting to encode a session identifier in the URI.
Glen: I may want to send you a redirect with
the "hi" response to the first interaction.
... Or I might want my session manager to dispatch round-robin to a set of other services.
MarkN: Anyone going to talk about asynchrony?
Glen: Later :-)
Goodner: WS-Eventing, WS-Management, use reference parameters.
<goodner> WS-Management: msdn.microsoft.com/ws/2004/10/ws-management
Goodner: and properties.
Glen: Asynch?
MarkN: We're chartered to make existing MEPs work asynchronously.
Glen: If you're using WSDL SOAP over HTTP binding, you can't really change that to get a response on SMTP.
DaveO: Don't know if that's true.
MarkN: WSDL 2.0 isn't a Rec yet.
DaveO: I asked XMLP, haven't gotten a response yet.
Glen: As it stands, I think the request message maps to the HTTP request, the response maps to the HTTP response.
Anish: You could imagine a binding to SMTP, which points to our WSDL MEP mapping spec.
MarkN: The WSDL bindings are not a close spec, and we need to coordinate with WSDL.
Anish: Asynch scenario: you want to send an EPR as part of the application data. EPRs enabling application-level asynch responses.
Gudge: WS-Eventing works like that.
MarcH: Do we need time-to-live on asynch EPRs?
MarkN: Might have to get into that...
DaveO: Use case session timeout...
Paco: You might want to enable different models to be used with EPRs.
DaveO: Use case: stateless services. One use of cookies is to enable stateless web pages. Use of ref params/props may fill that need as well.
MarkN: Stateless = all information to contextualize a conversation is given in the message.
MarcH: You can also move state around.
DaveO: Difference between stateless and self-describing. I was proposing truly stateless.
Paul: The point of the spec is that SOAP/HTTP
has implicit correlation, other transports like MQ requires a mechanism to
correlate.
... Transport has a state.
MarkN: We've listed use cases that carry EPRs.
... We've talked about carrying metadata.
... talked about async and stateless.
... talked about reply-to
... talked about ref props/ref params some.
Paul: How many EPRs can you have in an
addressing envelope?
... Use email as an example. I can address to multi-cast the message.
... I'd be happy to punt that to higher-level specs.
Gudge: WS-A defines a bunch of headers, doesn't prevent other specs from defining other headers, or sticking EPRs in message bodies. Which are you trying to prevent?
Marc: You don't want to support a list of endpoints?
Paul: There are complexities: what if I fail on the third addressee?
Gudge: A message can only be sent to a single
endpoint. That endpoint could represent a group.
... You don't want multiple endpoints baked into the spec.
Paul: Good. Lists of endpoints gets complex, esp. what happens when things go wrong.
MarcH: Not sure I agree.
Paul: Could use more than address in your EPR.
Gudge: From a security perspective there's no guarantee their sec requirements are the same.
MarcH: No guarantee they won't be.
Paul: Trying to fill in a potential rathole.
... You can use other mechanisms.
Rebecca: You use SMTP as a bad example. We want to support HTTP, SMTP, MQ.
DaveO: If I'm sending an SMTP does the message
as you recieve it have more than one To:?
... You might be able to have a Multi-address To: header that lists everyone else the message has gone to. Layered on top.
Rebecca: Sounds like your trying to restrict the transports we can use. Why disallow SMTP.
MarkN: You can think of this in several different ways: push it down into the address, or you could expand it at the application layer. Paul says multiple To:s adds complexity.
Anish: Doesn't this also apply to other headers? E.g multiple reply-to, relates-to.
Gudge: Absolutely you can have multiple of those.
Philippe: How does this work with reliability? Reply-to means the response might go somewhere else.
Gudge: Third party scenario. So far this handoff has been modelled at a different layer.
MarkN: Audit scenario. The headers are very useful for audit.
Paul: We've implemented a ReplyTo as part of an
end-to-end structure which logs the message exchange.
... Don't know how deep we should go, there's an endless list of things that can go in there.
... Beyond some point lie dragons.
Rebecca: Similar to redirection, what about high availability?
Gudge: Like a server farm?
Rebecca: Lots of ways to implement.
Gudge: There's a primary address, and I then acquire a specific address.
Rebecca: Or there is a single EPR that gets routed internally.
Glen: Or, here are five endpoints, try them out.
DaveO: There's two ways to handle: if you send
me two EPRs and I can try them in some order.
... Or you can give me a single EPR which enables you to redirect to another endpoint.
Rebecca: Or you might have all the information you need to make an informed decision.
MarkN: Common in HTTP to use cookies for this.
... Thoughts on wsa:Action?
DaveO: We've got a straight up
application-level action. We might need a more complicated one.
... In the case of ReliableMessaging, there is a case where the components may be sent as a header block, or as the body.
... There is not a one-to-one correspondence between the body and the action (?)
Glen: Use case: use the EPR to talk to a node
that itself doesn't support WS-A.
... Like a SOAP node which doesn't understand WS-A.
MarkN: Backward compatibility with non-WS-A aware nodes.
Greg: Up to us to define the semantics of what
can and cannot be done.
... We need to disambiguate what can and can't be expected.
MarkN: If EPRs are required to be understood, do we need an EPR mustUnderstand capability.
Rebecca: Use case of having multiple transports mapped to a single EPR.
Glen: But you really mean the service
reference.
... Represents multiple WSDL endpoints within a single service reference.
Rebecca: Alternate transports - all are available at the same time.
DaveO: If you offer a transport over multiple endpoints, isn't that for availability?
Glen: Not necessarily, might be for accelleration of a single interaction.
Philippe: There's a slippery slope. What if
those transports don't have the same policy?
... So you should be able to associate different policies with them?
[Yes.}
Glen: Here are your options, use the ones you
want.
... Use case(?) I'm an intermediary, and I'd like to be able to distinguish what's ref props and what aren't.
... I'm interested in security and semantics of what's going past.
... I may want to remove optional headers. How do I know which are ref props/params?
Paul: When we started out, we built a security proxy. You need to know what action the message is going to take at the destination.
Glen: Yes. Even if I'm not security, I may want to pick out the reference properties.
Paul: If you have a man-in-the-middle doing access control, you'd want to make sure that there isn't an unknown mechanism that dispatches the message.
Paco: Man-in-the-middle would do that on a per-contract basis.
Dims: ReliableMessaging has a create-sequence. SecureConversation has a create token. I want to send a single message that does both of them.
Glen: Boxcarring scenario.,
Gudge: It hurts. Don't do that.
... I think there is a composition pattern for that particular pattern.
Dims: Other protocols might come up that use actions.
Gudge: We already have that issue: what happens when actions collide.
Bob: Have we explicitly stated that there is a
DoS, firewalling characteristic we'd like to enable.
... Want to enable applicances that permit or deny certain things.
MarkN: Is there a corrollary in the Cookie World?
Bob: The utility would be enhanced to pass/block/route based on characteristics of the WS-A headers.
Paco: How much does that affect interop?
Bob: From a spec point of view if we were to
define something that made the creation of such an appliance impractical,
that would be unfortunate.
... Be mindful we don't prevent that.
Rebecca: Dynamic generation of EPRs brought up
a number of issues.
... Should track that as a use case.
MarkN: Chartered to accommodate different MEPs
with WS-A. Like to get an idea of what we have in mind for that.
... Multicast, async, callback. Any others?
Paco: Multi-protocol requirement: before we get
there it may be useful to cache metadata.
... Enough information to interact with the endpoint.
MarkN: Lifetime model for metadata?
Paco: We may want the EPR more self-contained.
... MetadataExchange use case, where you don't know enough metadata to know how to interact.
Rebecca: Do you get all the pieces up front or
do you have to go get the metadata and process it.
... Different processing models in these two cases.
... MQ Series introduces a lot of concerns.
Anish: Use case for implementing existing MEPs using EPRs.
MarkN: Explicit in our charter.
... Will write down the list of use cases and make them available to the WG. We can expand on these and help guide our decisions.
... Trying to develop WG shared understanding.
... Tomorrow, issues!
Philippe: SMTP isn't on the list.
MarkN: Thought that was a corrollary. But I'll add email as a use case.
Reconvene at 9AM. | http://www.w3.org/2002/ws/addr/4/10/25-minutes.html | crawl-001 | refinedweb | 5,678 | 68.47 |
In this article I would be trying to explain what SignalR is and would try to give a walkthrough using an ASP.NET MVC5 example. So even if you don't have any previous knowledge on SignalR, its fine as long as you know the basics of ASP.NET MVC, C# and Javascript.
SignalR is an web based real time bi-directional communication framework. By real time, we mean the clients get the messages being sent in real time as and when the server has something to send without the client requesting for it. And bi-directional because both the client and server can send messages to each other.
In the simplest terms, the way it works is the client is able to call methods on the server and the server likewise is able to call methods in the client.
Lets see some cases where SignalR can be used so that we can better appreciate the technology.
1. Chat Room application
This is an example where users keep sending messages to each other in a ChatRoom.
2. Broadcasting
This is an example where the server needs to broadcast messages to the clients.
E.g. Sports website where we keep getting live updated scores, Stock applications or News websites or even Facebook, Twitter updates.
3. Internet Games
This is where many players play some game online where each player does some action turn by turn.
History of Real time communication and challenges
In the first liner introduction to SignalR, we used the term real time and bi-directional.
Now why do we need an entirely new technology for implementing real time communication. The reason is because of the way HTTP protocol works. So those of you who have some experience with web technologies know that HTTP works on a request/response mechanism. So a client(typically a web browser) makes an HTTP request to the Web Server and the Web Server sends an HTTP response back to the client. Unless the client makes a request to the server, the server has no knowledge of who its clients are and so it can't send a message to the client. We must have heard that HTTP is a stateless protocol, which essentially means that it doesn't remember which client made a request to it and how many times. For HTTP every request to the Web Server is an independant one. So for these reasons a bi-directional real time communication was a challenge before SignalR.
But this doesn't mean that we didn't had such applications like a sports news update site or a chat site before SignalR. Lets try to look at some techniques to achieve such real time communication before SignalR.
AJAX polling
Here as we can see the client makes some periodic requests to the server at some periodic intervals of time. In this way we keep the client updated with the latest data. As we can see from the image, when the client makes a request to the server, we don't know for sure that the server has something new to send so in a way those requests might be unnecessary. On the other hand when the server has something new to serve the client it can't send it unless the client makes a request, so we can't term this communication exactly real time.
Another technique which is a bit better than AJAX polling is long polling as shown above in the image. Here too the client makes a request to the server but it doesn't do so in periodic intervals of time. The client makes a request but the server doesnt respond immediately, rather it keeps the clients request open unless it has something new to serve. The client makes the new request after it gets a response back from the server. So this technique eliminates some of the drawbacks of the previous one and sounds a bit real time. But this technique needs some customization both on the client and server side to manage the client connections to the server and also managing timeouts.
Plugins
Plugins like flash or silverlight are some other technologies which can be used to implement real time communication. However in this world of mobility and HTML5 some mobile devices doesn't support plugin's so we have to be mindful of that. Speaking of mobility and HTML5, HTML5 actually brings in a concept of Web Sockets which also addresses the need of bi-directional communication. However we have to be using a modern browser for that.
As we can see that we have a number of options to implement real time bi-directional communication between client and server lets see how SignalR address these needs by creating a tunnel between client and server which is bi-directional in nature so that server can happily send messages to its attached clients whenever it wants to.
Lets get started
Now lets try to see some introduction concepts of SignalR.
WebSocket
WebSocket is a bi-directional TCP socket connection in which the client can send messages to the server and also the server can send messages to the client. Only IIS8+ webserver supports WebSockets.
SignalR Hub
The SignalR Hub is the server side part of the technology which exposes public methods to the connected clients.
Client
The client which is a web browser(also can be mobile native apps) uses Javascript to send and receive messages from the server.
Connectivity
SignalR uses a couple of different technologies to support real time communication between client and server.
- WebSockets
The first approach it would try for connection is WebSockets because its the most efficient one.
- Server Sent Events
If this doesn't work(say because of browser compatibility issues), then it would try falling back to "Server Sent Events(SSE)". SSE is an HTML5 specification where the server can sent updates to the client using an HTTP connection.
- Iframe
This method uses a hidden iframe in the browser and server keeps sending script blocks to the iframe. The scripts have knowledge to maintain the connection to the server.
Read about Hidden iframe here
- Long polling
We have already read about Long polling mechanism in this history section above.
So in this way SignalR based on the infrastructure will try to achive real time communication in the most efficient way and fallback to another one if needed.
Web Browser requirements -- taken from
Lets get practical
1. Create a new ASP.NET MVC5 web project. Select the MVC template and set Authentication to "Individual User Accounts". You are actually free to use any authentication you want but selecting "Individual User Accounts" gives us a Startup class which otherwise you would have to write yourself.
2. Install Nuget package Microsoft.AspNet.SignalR.
This nuget package contains both the server and client side dependencies needed to run SignalR.
3. After installing the Nuget package, it shows us a readme.txt file which mentions that to enable SignalR in our application, we have to do some OWIN/Katana configuration. If you are new to OWIN/Katana, you might want to read my article
So basically, we have a Startup class in out project and a Configuration(IAppBuilder app) method. Now inside the ConfigureAuth class add this line of code to enable SignalR as shown in the code snippet end.
app.MapSignalR(););
//Enables SignalR
app.MapSignalR();
4. In our project, Add a New item and select SignalR tab. We have 2 templates here. One SignalR hub class which we would select here. There is another template SingalR Persistent Connection Class which we can use if we want to do something at a connection level(a bit lower level)
So this MyHub class derives from the SignalR "Hub" class which exposes a public method Hello() which the clients can call to using WebSockets etc.
public class MyHub : Hub
{
public void Hello()
{
Clients.All.hello();
}
}
Inside the Hub's Hello method, we are doing Clients.All.hello(); which means the for all clients that are connected, call the hello() method on the client(a Javascript method).
Please note that "All" is a dynamic property of Clients and so we can call any method we want, e.g. in this case instead of hello() method we can call any other method say helloworld().
Clients.All.helloworld();
Ok, so now lets write some SignalR code which will broadcast the server time every 3 seconds to the clients, a simple example.
For that, in the above MyHub class, lets write a constructor and create a long running task in an infinite loop and send the server time to all the connected clients by calling the client method(a Javascript method on the client called from C# server side) after a delay of every 3 seconds. I am using TPL for this to make it asynchronous. If you are new to TPL and would like to know more, please visit the following link.
public MyHub()
{
// Create a Long running task to do an infinite loop which will keep sending the server time
// to the clients every 3 seconds.
var taskTimer = Task.Factory.StartNew(async () =>
{
while(true)
{
string timeNow = DateTime.Now.ToString();
//Sending the server time to all the connected clients on the client method SendServerTime()
Clients.All.SendServerTime(timeNow);
//Delaying by 3 seconds.
await Task.Delay(3000);
}
}, TaskCreationOptions.LongRunning
);
}
Now that we have a hub defined and wrote the server code to send the server time to the clients, lets try writing some client side code.
We'll need a view to display the server time. I'll use the Contact view from the default ASP.NET MVC5 template project and delete its contents to keep it clean. Please feel free to use any view :).
cshtml View code
@section scripts{
<script src="~/Scripts/jquery.signalR-2.1.1.js"></script>
<script src="~/SignalR/hubs"></script>
<script src="~/Scripts/Custom/timer.js"></script>
}
<span id="newTime"></span>
In the view snippet above, we have referenced the signalR jquery library jquery.signalR-2.1.1.js and a custom javascript file timer.js which we'll use to write our own custom code to define the connection to the hub and the client side methods.
The script in the middle <script src="~/SignalR/hubs"></script> is not really a script but an endpoint exposed by the hub for the clients to consume. Its a kind of proxy on the client similar to a WCF proxy for those who have used WCF. We also need the jquery library but i haven't included it here as its alreay there in the _layout.cshtml view which this view inherits.
And we have a span defined with an id so that we can use Jquery to write the server send time there in the span which we'll see later.
Lets browse the url to have a look at the proxy contents.
Here in the proxy code, we can see that, we have the myHub proxy which we defined as a hub in the server side.
We also see the hello() function defined on the server side here.
The last piece of code left to be written is the timer.js Javscript code.
);
};
}());
In the Javascript code snippet above, we have written an anonymous self executing Javascript method(self executing means we don't have to call it explicitly) where we defined the connection to the hub, started the hub and also wrote the client side method which the server hub calls.
To know more about Javascript self executing function(technically termed IIFE-Immediately-invoked function expression), please visit
We are using the connection property on the $ object. Yes $ sounds like JQuery and the signalR client side library is actually a jquery plugin which makes this possible. Using the connection property we can access to the server side hubs.
Now we are ready to run our program, excited!!!
Here we can see that the time keeps updating every 3 seconds. Try spinning up multiple browsers and see that the time gets updated for all the browsers. So its SignalR broadcasting the server time as a message to all connected clients.
If you remember that we had set logging to true in our client side javascript $.connection.hub.logging = true;.
So if you open up the Console window of the browser(F12 key for most of the ones) we will see the communication as shown in the snapshot below. In this case, its using WebSockets for communication as I am using the latest version of Chrome, but if you use an older browser, the communication may actually fall back to something else.
The last piece of thing I wanted to show is the client making a call to a server function defined in the Hub. This would show the true piece of bi-directional communication between the client and server.
We'll try sending a message to all connected clients on a button click. So a button click method on the client will call a server hub method which inturn will call a client method to all its connected clients. So one client will essentially call the server method which will broadcast to all the clients.
public class MyHub : Hub
{
public void HelloServer()
{
Clients.All.hello("Hello message to all clients");
}
}
So here we have a HelloServer() method defined in our hub which sends a message to all the clients.
Lets add a button and another span to our view. Button to click and span to display the message.
@section scripts{
<script src="~/Scripts/jquery.signalR-2.1.1.js"></script>
<script src="~/SignalR/hubs"></script>
<script src="~/Scripts/Custom/timer.js"></script>
}
<span id="newTime"></span><br />
<input type="button" id="btnClick" value="Send Message" /><br />
<span id="message"></span>
Now lets change our timer.js file to include 2 more functions.
1. Client method hello() which is called from server hub as shown below.
Clients.All.hello("Hello message to all clients");
2. Button click handler which calls server hub method helloServer().
);
};
// Client method to broadcast the message
myHub.client.hello = function (message) {
$("#message").text(message);
};
//Button click jquery handler
$("#btnClick").click(function () {
// Call SignalR hub method
myHub.server.helloServer();
});
}());
With this code in place now if we open up 2 or more browser windows and click on the button on one browser, all the browsers will receive the message real time. We can easily tweak this code to actually make a chat room by sending a proper message written by one client instead of a hardcoded message sent by server. So this is a brief introduction of the possibilities of SignalR.
History
Some of my other articles which you might be interested.
Download sample
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
HelloServer();
helloServer();
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. | https://www.codeproject.com/Articles/806919/SignalR-with-ASP-NET-MVC | CC-MAIN-2017-22 | refinedweb | 2,500 | 62.68 |
Spring Security – What happens after /you/ log in?
Update: Check out PicketLink Security for Java EE
The login formHere is a basic JSF/Spring Security login form. It would be nice if we could enable or disable the redirect functionality, so we’ll add a hidden form field that is only rendered on demand (here we use Facelets ui:param functionality for our on-off switch.)
The login action methodFirst, check to make sure that we actually want to do a redirect after login. Do this by testing for the existence of our hidden form parameter. Find the full LoginBean code here.
Before forwarding to the Spring Security /j_security_login_check intercepting filter chain, we’ll need to set the current URL into a Session attribute: “LoginRedirectFilter.LAST_URL_REDIRECT_KEY”. This will be used in our custom filter after the user successfully authenticates with Spring Security.
The login filterHere is where we’ll check for the existence of our session attribute: “LAST_URL_REDIRECT_KEY”. If this key contains a value, then we should redirect the user to that URL. If the key does not contain a value, then we should not perform any redirect, and continue as normal. One other concern is: what if authentication failed? Let’s assume that Spring Security will redirect the user to the Login Page if they send invalid credentials. We don’t want to trigger a redirect as they try to access the login page, so we also check to make sure we have a successfully authenticated user before redirecting.
Web.xmlSome specific configuration is required to ensure the proper ordering of our filters. LoginRedirectFilter’s filter-mapping must be placed after any Spring Security filters – otherwise we will redirect too soon, and authentication will never occur. You probably want to place it before any filters that apply business logic.
Try one of these highly-recommended books:
I am not sure why you need to do this because this comes out of the box with spring-security. If spring detects an access to the secured resource it will automatically redirect to the login page storing the original request URL in the session – i.e. what you have done manually.
This article does not describe how to redirect after attempting to access a secure URL — it describes how to authenticate from a PUBLIC URL and send the user back to the page they were viewing, instead of being sent to the default-login-url.
Hi Lincoln!
Here can I see the FacesUtils java code?
Thank’s a lot.
FacesUtils can be found here:
Hi Lincoln,
Is there a way you can hide/protect URLs after a user logs in depending on user’s credentials or characteristics?
If you have an example, that’d be great.
Thanks
I usually defer to the non-filter security mechanisms for such use-cases. PrettyFaces allows you to do just that with URL actions. In the action you would check the user’s credentials / business scenario and decide whether or not to continue to process and render, or redirect to a different page. There are other ways, but… this is one.
How about when I want to hide certain links/buttons for certain users? Would I go thru a similar process, or something different.
Sorry, I’m fairly new to this whole programming in Spring Security.
Thanks for your response, Lincoln. 🙂
No problem. You’d do something very similar. You’d want to create a JSF Action Method in a JSF Managed Bean – something like:
public class MyBean {
public boolean isUserGrantedAccess()
{…}
}
This method would check the logged in user’s preferences, permissions, the state of the system or whatever logic needed.
Then you would disable or render the link by referencing that action method in your Facelet view.
<h:commandButton …
Notice the “is” should be omitted. See “JEE Unified Expression Language Syntax” for more details on that.
BTW where can I download your HelloWorld example?
By Hello World, I meant your Basic Login example presented in this article and the previous one.
Sorry if I confused you in any way.
Thanks!
Unfortunately, there is no example, sorry. But you can download the sources for that and take a look.
Do you think it’s possible to utilize taglibs/tld file in order to create URL protection?
I’m currently using JSF 1.2 so I can utilize a tld file that would have security tag defined.
If you could give me a quick example, that’d really be fabulous.
Thanks~!
How can I get the logged user object on the “doLogin” bean method?
Or exists another alternative for use rendered=”#{myBean.userGrantedAccess}
Thank’s
Marcos
Redirecting back to the source URL comes out of the box with Spring Security 3 – see
Hi Lincoln!
Can you provide a examples for enable or disable the redirect functionality use Facelets ui:param ?
Thank’s a lot.
I am wondering what this is (in LoginBean): PrettyContext.getCurrentInstance().getOriginalRequestUrl();
I guess it is part of PrettyFaces, but it seems that is no longer in the API. I’m using 3.2.0 of PrettyFaces and can’t find it.
Hi Jo,
The methods you are looking for are now called:
Hope this helps!
~Lincoln
hello,
Using your code sample and SpringSecurity 3.0.5, I cant seem to get access denied to work correctly. I seem to be getting this JSPG0036E: Failed to find resource /faces/protected.jsf.
Any ideas?
Hi i’m new to Spring Security, …
do you know how do I detect if the user currently have an active session so that
I can display a warning message and provide option for user to open a new session
or close the current active session. Please advise
hi Lincoln! Though you might have posted it long time back and you might not even remember the context but just a question. Does it work for the url with hash(#)? like somthing like this where i need to navigate to the sub nav bar of foo.com page.
Hi Krishna,
You would need to implement something like that yourself. I believe there is some stuff coming from Jboss about that soon, but nothing yet.
~Lincoln | https://www.ocpsoft.org/java/jsf-java/spring-security-what-happens-after-you-log-in/ | CC-MAIN-2019-47 | refinedweb | 1,023 | 65.22 |
June 27, 2019 Single Round Match 760 Editorials
NBAFinals
Solution:
We fill all the missing places greedily. Whenever a character in team is missing its always beneficial to fill it with W because giving some points to Warriors is always better than giving them to Raptors. Now, that we have no missing characters in team, whenever score is missing, if Raptors scored it, we want to give them the minimum possible (i.e 1) and for Warriors maximum possible (i.e 4). This is the best possible way of filling a Warriors fan could have done. So after filling team and score accordingly we can check if Warriors have more points in this optimistic way of filling. If they have more then answer is 1, otherwise any other filling cannot give Warriors the lead. Hence answer is 0.
Code:
public int dubsAgain(int[] scores, String team1){ char[] team = team1.toCharArray(); int n = scores.length; int i; for(i=0;i<n;i++){ if(team[i]=='?') team[i]='W'; } int ans=0; for(i=0;i<n;i++){ if(scores[i]==0){ if(team[i]=='R') scores[i]=1; else scores[i]=4; } if(team[i]=='R') ans-=scores[i]; else ans+=scores[i]; } if(ans>0) return 1; else return 0; }
Time Complexity: O(n) where n is number of characters in team
FrogJumps
Firstly we need to observe that we do not need the diagonal moves. We can simulate any diagonal move using two of the moves from (left, right, top, down). Now, we can see that for a frog at (x1,y1) which can jump such that its either coordinates change by k1, all the points it can reach will be of the form (x1 + a*k1, y1 + b*k1) , where a,b are integers.
Similarly frog at (x2,y2) which can jump such that its either coordinates change by k2, all the points it can reach will be of the form (x2 + c*k2, y2 + d*k2) , where c,d are integers.
So now for them to meet, x1+a*k1 = x2+c*k2, and y1+b*k1 = y2+d*k2,
Now x1-x2 = -a*k1 + c*k2 (This is true only when abs(x1-x2) is divisible by gcd(k1,k2))
Similarly abs(y1-y2) must also be divisible by gcd(k1,k2).
So now we can check these two conditions and return appropriate answer.
Code:
public long gcd(long a,long b){ if(a<b){ long temp=a; a=b; b=temp; } if(b==0) return a; return gcd(b,a%b); } public int canMeet(long x1,long y1,long x2,long y2,long k1,long k2){ long val = x2-x1; if(val < 0){ val*=-1; } long gg = gcd(k1,k2); if(val%gg!=0){ return 0; } val=y2-y1; if(val < 0){ val*=-1; } if(val%gg!=0){ return 0; } return 1; }
Time Complexity: O(log(k1) + log(k2) ) for calculating the gcd. Rest are O(1) operations.
HomeAwayLeague
Solution:
Firstly let us select the n/2 teams which host the home game in first round. This can be done in C(n,n/2) ways.
Next, we need to assign away teams for the home games in the first round. For this we can assume home teams are lined in some order (for example lexicographic). And we can take n! possible orderings of away teams and allot ith home team with ith away team and so on. So now, each of the n! orderings give different schedule for first round.
Hence , first round can be organised in n! * C(n,n/2) ways.
Now given a first round, home teams for second round are already decided which will be away teams of first round. We can assume there is some ordering among home teams again. Now , we want to take orderings of away teams such no team plays the same team they played in previous round. This is same as counting number of derangements of size n/2 because each one does not go to exactly one place(let us represent by D(n/2) ).
Derangements can be calculated using recursion D(n) = (n-1)*(D(n-1)+D(n-2)).
Therefore , total ways are n! * C(n,n/2)* D(n/2).
Code:
int N = 500005; long[] fact = new long[N]; long[] derang = new long[N]; long mod = (1000*1000*1000+7); public long powe(long a, long b){ long ans=1; while(b>0){ if(b%2==1){ ans*=a; ans%=mod; } a*=a; a%=mod; b/=2; } return ans; } public long inver(long val){ return powe(val,mod-2); } public long range(int l,int x,int r){ if(l<=x && x<=r){ return 1; } return 0; } public int matches(int n){ int i; fact[0]=1; for(i=1;i<N;i++){ fact[i]=fact[i-1]*i; fact[i]%=mod; } derang[1]=0; derang[2]=1; for(i=3;i<N;i++){ derang[i]=(derang[i-1]+derang[i-2])*(i-1); derang[i]%=mod; } long ans=fact[n]; ans*=inver(fact[n/2]); ans%=mod; ans*=derang[n/2]; ans%=mod; return (int)ans; }
Time Complexity: O(n).
CatAndMice (author : misof)
Solution:
Firstly let us handle case C = N, then the only rays are either diagonals or vertical or horizontal. We will prove soon that for other rays, number of lattice points is less than N.
So from here on lets assume C!=N.
We can first see that we can calculate the number of rays in first quadrant and see that due to symmetry it will be same in the rest of the quadrants.And since C!=N,each ray uniquely belongs to a single quadrant. So we can find number of rays in first quadrant and multiply answer with 4.
Now, we have reduced to counting rays in first quadrant. We can further use symmetry along line x=y and reduce question to finding number of rays in the first 45 degrees. And multiply it by 2.
Now any ray equation in the first 45 degrees looks like y = a*x/b where (0<a<b and a and b are co prime). Different pairs of (a,b) give different rays. (we are not considering diagonal and horizontal directions because for them C=N).
Now, we can notice from 0<a<b constraint that b>=2. (remember this we will use later).
Next number of lattice points on the ray y = a*x/b. x can take values b,2*b and so till floor(n/b). Since a<b, y will always be less than x and hence if x is in the range then y is also in the range. Hence number of lattice points on the ray will be floor(n/b).
Now , since b>=2, maximum number of lattice points on such a ray will be floor(N/2) (< N) (Proof that C=N cases are completely described above).
Since number of lattice points on a ray does not depend on a, we can iterate on b. And see what for all values of b we have floor(N/b) = C.
Now we want to count for a particular b , number of values possible for a such that a>=1 and a<b and a is co prime to b. This is exactly phi(b) (euler totient function).
So now answer will be sum of phi(b) over all b that satisfy floor(N/b) = C.
Code (By misof ):
public long countDirections(int N, int C) { int[] primeDivisor = new int[N+1]; for (int n=2; n<=N; ++n) if (primeDivisor[n] == 0) for (int i=n; i<=N; i+=n) primeDivisor[i] = n; int[] phi = new int[N+1]; phi[1] = 1; for (int n=2; n<=N; ++n) { int x = n, p = primeDivisor[n]; phi[n] = p - 1; x /= p; while (x % p == 0) { phi[n] *= p; x /= p; phi[n] *= phi[x]; if (C == N) return 8; long answer = 0; for (int b=2; b<=N; ++b) if (1L*C*b <= N && 1L*(C+1)*b > N) answer += 8*phi[b]; return answer;
Time Complexity:
O(nlogn) to calculate euler totient function for the first n natural numbers.
ComponentsForever
Solution:
First thing is (x+y)modulo 2 value is constant across hops. So a frog at (x1,y1) cannot reach a frog (x2,y2) in any number of hops if (x1+y1) modulo 2 != (x2+y2) modulo 2.
So let us separate the frogs based on (x+y)modulo 2 and add the answers of the both cases. Because there will not be any common promise among both groups because they cannot talk to each other ever.
Case 1:
Now, we will work with group where all the frogs have (x+y)modulo 2 =0. From now on, in this case whenever we refer to a frog,we assume its coordinates are such that sum of them is even.
For, two frogs at (x1,y1) and (x2,y2)
if (x2-x1) modulo 2 =1, then frog 1 can reach second frog only after odd number of hops. Similarly, for (x2-x1)modulo 2 =0, we can reach only in even number of hops.
Minimum number of hops needed for frog 1 to reach frog 2 is max(abs(x2-x1),abs(y2-y1)).
Proof: this minimum cannot be less than this because each hop x and y coordinate will change atmost by 1. Now, we will show a construction. Lets assume abs(x2-x1) > = abs(y2-y1). Now, first abs(y2-y1) moves we move y1 towards y2 and x1 towards x2. For rest of the moves we oscillate y1 near y2 (like move from y2 to y2+1 and back from y2+1 to y2) and move x1 to x2.
Also now we can see that if minimum number of hops is d, there always exist a path of length d+2k for any whole number k because after minimum hops we can move to adjacent vertex and back. And we have proved above that parity of path lengths is always same. Hence, these are the only path lengths possible.
So now, Let us take a walkie talkie with range (L<R) . Now this can connect frog 1 and 2 only if
R>=max(abs(x2-x1),abs(y2-y1)) because [L,R] will consist of atleast two consecutive integers and in every two consecutive integers above minimum hops one of them can be path lengths. So now, connectivity does not depend on L.
Since L is not important for us. We will just focus on R and for each R , for every valid L answer will be same.
Now, for each R, we will construct a connectivity graph and compute number of components in it. Since in each component we can make different promise,we need expected number of components in the graph.
We can start from R = a, and keep increasing R gradually and add edges as they become eligible (an edge becomes eligible only when min hops between the two frogs <= R). If you can see this procedure is very close to kruskal algorithm to finding MST. Also another parallel is only when an MST edge is added, count of components changes. So, the only important R values where number of components change will be the edge weights of MST edges.
So now, we will have n-1 important R values and between each pair of adjacent R values components do not change. So we can count number of [L,R] pairs with that number of components and use it for finding expectation.
Finally we are left with finding MST in this graph. Now, there will be O(n*n) edges. Hence, it is not feasible to construct the graph and use kruskal algorithm.
For two points (x1,y1) and (x2,y2), max(abs(x2-x1),abs(y2-y1)) is called Chebyshev distance .
Let us consider transformation of point (x,y) to ((x+y)/2,(x-y)/2)
Now, if we take ((x1+y1)/2,(x1-y1)/2) and ((x2+y2)/2,(x2-y2)/2), manhattan distance between them will turn out to be max(abs(x2-x1),abs(y2-y1)). Hence, graph constructed with edge length as manhattan distance between the transformed points will be same as previous graph. Now since the graph is same, MST will also be same. So we need Manhattan MST between these transformed points which is a standard problem (Link here).
Hence, we can now construct the MST fastly and solve the problem.
A small trick to avoid doubles, the case where points have (x+y)modulo 2 as odd, we can move all the points 1 unit right. This will not change anything in the problem since all distances will remain same.
counting number of pairs of [L,R] such that R is between R1 and R2 . Assume a<=R1<=R2<=b.
Number of pairs will be (R1-a)+(R1+1-a)+…(R2-a) = R2*(R2+1)/2 – (R1-1)*R1/2 – a*(R2-R1+1).
Code (C++):
//teja349 #include <bits/stdc++.h> > > ll xx[212345],yy[212345]; const int maxn = 2e5 + 5; const int oo = (int) (1e9+10); struct Point { int x, y, idx; Point() {x = y = idx = 0;} Point(const Point& rhs) : x(rhs.x), y(rhs.y), idx(rhs.idx) {} int operator < (const Point& rhs) const { return make_pair(x, make_pair(y, idx)) < make_pair(rhs.x, make_pair(rhs.y, rhs.idx)); } }; pair<int, int> fen[maxn]; void upd(int p, pair<int, int> val) { p++; for (; p > 0; p -= p & -p) fen[p] = min(fen[p], val); } int query(int p) { p++; pair<int, int> res = make_pair(oo, -1); for (; p < maxn; p += p & -p) { res = min(res, fen[p]); } return res.second; } int dj[maxn]; void init() { for (int i = 0; i < maxn; i++) dj[i] = i; } int find(int u) { return dj[u] == u ? dj[u] : dj[u] = find(dj[u]); } int join(int u, int v) { int p = find(u); int q = find(v); if (p != q) { dj[p] = q; return 1; } return 0; } int n; Point p[maxn]; priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq; int dist(Point a, Point b) { return abs(a.x - b.x) + abs(a.y - b.y); } void add(int u, int v, int d) { pq.push(make_pair(d, make_pair(u, v))); } void manhattan() { while(!pq.empty()) pq.pop(); for (int i = 0; i < n; i++) p[i].idx = i; for (int dir = 0; dir < 4; dir++) { for (int i = 0; i < maxn; i++) { fen[i] = make_pair(oo, -1); } if (dir == 1 || dir == 3) { for (int i = 0; i < n; i++) swap(p[i].x, p[i].y); } else if (dir == 2) { for (int i = 0; i < n; i++) p[i].x = -p[i].x; } sort(p, p + n); vector<int> v; static int a[maxn]; for (int i = 0; i < n; i++) v.push_back(a[i] = p[i].y - p[i].x); sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); for (int i = 0; i < n; i++) a[i] = lower_bound(v.begin(), v.end(), a[i]) - v.begin(); for (int i = n - 1; i >= 0; i--) { int pos = query(a[i]); if (~pos) add(p[i].idx, p[pos].idx, dist(p[i], p[pos])); upd(a[i], make_pair(p[i].x + p[i].y, i)); } } } ll getgg(ll a,ll b,ll Llo,ll Rhi){ a=max(a,Llo); b=min(b,Rhi); if(b<a){ return 0; } ll ans=b*(b+1)/2-a*(a-1)/2 - Llo*(b-a+1); ans%=mod; return ans; } ll solve(int nn,int Llo,int Rhi){ n=nn; manhattan(); ll comps=n; init(); ll ans = 0; ll prevr=1; while (pq.size()) { int u = pq.top().second.first; int v = pq.top().second.second; int w = pq.top().first; pq.pop(); if (join(u, v)) { ans+=comps*getgg(prevr,w-1,Llo,Rhi); ans%=mod; comps--; prevr = w; } } ans+=comps*getgg(prevr,Rhi,Llo,Rhi); ans%=mod; return ans; } ll powe(ll a,ll b){ ll ans=1; while(b){ if(b%2){ ans*=a; ans%=mod; } b/=2; a*=a; a%=mod; } return ans; } class ComponentsForever{ public: int countComponents(int nn, vector<int> Xprefix, vector<int> Yprefix, int seed, int Xrange, int Yrange, int Llo, int Rhi){ int sz=Xprefix.size(); int i; for(i=0;i<sz;i++){ xx[i] = Xprefix[i]; yy[i] = Yprefix[i]; } ll state = seed; ll bigmod = (1LL<<31); for(i=sz;i<nn;i++){ state = (1103515245 * state + 12345); xx[i] = state%Xrange; state=state%bigmod; state = (1103515245 * state + 12345); yy[i]=state%Yrange; state=state%bigmod; } int cnt=0; int j=0; for(i=0;i<nn;i++){ if((xx[i]+yy[i])%2==0){ p[j].x = (xx[i]+yy[i])/2; p[j].y = (xx[i]-yy[i])/2; j++; cnt++; } } ll ans=0; if(cnt) ans = solve(cnt,Llo,Rhi); cnt=0; j=0; for(i=0;i<nn;i++){ if((xx[i]+yy[i])%2==1){ xx[i]--; p[j].x = (xx[i]+yy[i])/2; p[j].y = (xx[i]-yy[i])/2; j++; cnt++; } } if(cnt) { ans += solve(cnt,Llo,Rhi); } ll val=getgg(Llo,Rhi,Llo,Rhi); ans*=powe(val,mod-2); ans%=mod; return ans; } };
Time Complexity: Constructing Manhattan MST takes O(nlogn) time.
counting number of pairs of [L,R] such that R is between two consecutive change points (that is for all these R number of components is constant) is O(1). Since its just some formulas. And there are O(n) such intervals . So O(n) complexity
Hence, total time complexity is O(nlogn).
teja349
Guest Blogger | https://www.topcoder.com/blog/single-round-match-760-editorials/ | CC-MAIN-2022-40 | refinedweb | 2,967 | 71.55 |
The QHttpHeader class contains header information for HTTP. More...
#include <QHttpHeader>
This class is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.
This class is not part of the Qt GUI Framework Edition. value() and setValue(), e.g.
header.setValue("content-type", "text/html"); QString contentType = header.value("content-type");
Some fields are so common that getters and setters are provided for them as a convenient alternative to using value() and setValue(), e.g. contentLength() and contentType(), setContentLength() and setContentType().
Each header key has a single value associated with it. If you set the value for a key which already exists the previous value will be discarded.
See also QHttpRequestHeader. | https://doc.qt.io/archives/4.6/qhttpheader.html | CC-MAIN-2020-24 | refinedweb | 121 | 53.58 |
How do i view pdf file from url (internet)? can you help me? thanks
in Your .ts file use this code.
import { DomSanitizer} from '@angular/platform-browser'; @Component({ ... }) export class XYZ { pdfLink:any; constructor(private sanitizer: DomSanitizer) { this.pdfLink = this.sanitizer.bypassSecurityTrustResourceUrl(''+YOUR_PDF_URL_GOES_HERE); } }
in your HTML file
<iframe *</iframe>
This doesnt work in android device
I used this plugin will allow you to render a canvas with the pdf file, works good for me. And to add some of other capabilities like zoom, I use.
It works in every android and iphone devices. I have checked it and it’s also running in my live app.
Maybe you are missing something.
it is not working in device. through cors error in console log.
for CORS related issues,CORS has to configure from Server end.Just check with your backend team.
Now I am downloading and view pdf in available pdf viewer in phone.
I can confirm that this method (iframe method) works in debug mode, with IonicDevApp and on Android devices, thank you.
I’ve tried ng2-pdf-viewer as suggested by @leonardoss but I’m not able to make it work on my app. I’ve not found an example that explains how to use this library with Ionic3.
Claudio
Its working fine with pdf links files hosted on firebase but when i add gdrive pdf file link it only show html document as i attached the document | https://forum.ionicframework.com/t/view-pdf-from-remote-link/92076 | CC-MAIN-2021-31 | refinedweb | 239 | 77.03 |
errno
Global error variable
Synopsis:
#include <errno.h> extern int errno; char * const sys_errlist[]; int sys_nerr;
Since:
BlackBerry 10.0.0
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The errno variable is set to certain error values by many functions whenever an error has occurred. This variable may be implemented as a macro, but you can always examine or set it as if it were a simple integer variable.
- You can't assume that the value of errno is valid unless the function that you've called indicates that an error has occurred. The runtime library never resets errno to 0.
- The documentation for a function might list special meanings for certain values of errno, but this doesn't mean that these are necessarily the only values that the function might set.
- Each thread in a multi-threaded program has its own error value in its thread local storage. No matter which thread you're in, you can simply refer to errno — it's defined in such a way that it refers to the correct variable for the thread. For more information, see " Local storage for private data " in the documentation for ThreadCreate().
The following variables are also defined in <errno.h>:
- sys_errlist
- An array of error messages corresponding to errno.
- sys_nerr
- The number of entries in the sys_errlist array.
The values for errno include at least the following. Some are defined by POSIX, and some are additional:
Last modified: 2014-11-17
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/e/errno.html | CC-MAIN-2018-17 | refinedweb | 273 | 57.57 |
This Julia package is an interface between MathOptInterface.jl and AMPL-enabled solvers.
A list of AMPL-enabled solvers is available here.
Development of AmplNLWriter.jl is community driven and has no official connection with the AMPL modeling language or AMPL Optimization Inc.
AmplNLWriter.jl can be installed using the Julia package manager with the following command:
import Pkg Pkg.add("AmplNLWriter")
AmplNLWriter.jl provides
AmplNLWriter.Optimizer as a usable solver in JuMP.
The following Julia code uses the Bonmin solver in JuMP via AmplNLWriter.jl:
using JuMP, AmplNLWriter model = Model(() -> AmplNLWriter.Optimizer("bonmin"))
You can then model and solve your optimization problem as usual. See JuMP.jl for more details.
The
AmplNLWriter.Optimizer() constructor requires as the first argument the
name of the solver command needed to run the desired solver.
For example, if the
bonmin executable is on the system path, you can use
this solver using
AmplNLWriter.Optimizer("bonmin"). If the solver is not on
the path, the full path to the solver will need to be passed in. This solver
executable must be an AMPL-compatible solver.
The second (optional) argument to
AmplNLWriter.Optimizer() is a
Vector{String} of solver options. These options are appended to the solve
command separated by spaces, and the required format depends on the solver that
you are using. Generally, they will be of the form
"key=value", where
key is
the name of the option to set and
value is the desired value.
For example, to set the NLP log level to 0 in Bonmin, you would run
AmplNLWriter.Optimizer("bonmin", ["bonmin.nlp_log_level=0"]).
For a list of options supported by your solver, check the solver's
documentation, or run
/path/to/solver -= at the command line, e.g., run
bonmin -= for a list of all Bonmin options.
Note that some of the options don't seem to take effect when specified using the
command-line options (especially for Couenne), and instead you need to use an
.opt file.
The
.opt file takes the name of the solver, e.g.
bonmin.opt, and each line
of this file contains an option name and the desired value separated by a space.
For instance, to set the absolute and relative tolerances in Couenne to 1 and
0.05 respectively, the
couenne.opt file should be
allowable_gap 1 allowable_fraction_gap 0.05
In order for the options to be loaded, this file must be located in the current working directory whenever the model is solved.
A list of available options for the respective
.opt files can be found here:
NOTE: AmplNLWriter v0.4.0 introduced a breaking change by removing
BonminNLSolver,
CouenneNLSolver, and
IpoptNLSolver. Users are now expected
to pass the path of the solver executable to
AmplNLWriter.Optimizer.
The easiest way to obtain a solver executable for Bonmin, Couenne, or Ipopt is to download one from AMPL.
To use SCIP with AmplNLWriter.jl, you must first compile the
scipampl binary
which is a version of SCIP with support for the AMPL .nl interface. To do this,
you can follow the instructions here,
which we have tested on OS X and Linux.
After doing this, you can access SCIP through
AmplNLWriter.Optimizer("/path/to/scipampl"). Options can be specified for SCIP
using a
scip.set file, where each line is of the form
key = value. For
example, the following
scip.set file will set the verbosity level to 0:
display/verblevel = 0
A list of valid options for the file can be found here.
To use the
scip.set file, you must pass the path to the
scip.set file as the
first (and only) option to the solver:
AmplNLWriter.Optimizer("/path/to/scipampl", ["/path/to/scip.set"])
01/29/2015
1 day ago
195 commits | https://juliaobserver.com/packages/AmplNLWriter | CC-MAIN-2021-17 | refinedweb | 622 | 59.3 |
Please work out the pre-lab problems before your next lab section. The GSI/IAs will go over all problems during the lab section.
RAII (Resource Acquisition Is Initialization) is a programming idiom that is commonly used to acquire/release mutexes in concurrent programs. The basic idea is to create a class (often called a lock guard) whose constructor acquires the mutex and whose destructor releases the mutex. The program can then define the lock guard as a local variable when it needs to acquire the lock, then let the compiler automatically call the destructor (and release the lock) whenever that local variable leaves scope. This idiom makes it easy to release the mutex, regardless of how the program leaves the scope (e.g., return statement, exception). You will find this idiom handy when you write Project 2 and 4.
A. Modify the following program (from the Project 1 handout) to use RAII. Remember that you can create a new scope anywhere in your program, even if it doesn't correspond nicely to a function, if-statement, or loop.
#include <iostream> #include "thread.h" using std::cout; using std::endl; mutex mutex1; cv cv1; int child_done = 0; // global variable; shared between the two threads void child(void *a) { char *message = (char *) a; mutex1.lock(); cout << "child called with message " << message << ", setting child_done = 1" << endl; child_done = 1; cv1.signal(); mutex1.unlock(); } void parent(void *a) { intptr_t arg = (intptr_t) a; mutex1.lock(); cout << "parent called with arg " << arg << endl; mutex1.unlock(); thread t1 ((thread_startfunc_t) child, (void *) "test message"); mutex1.lock(); while (!child_done) { cout << "parent waiting for child to run\n"; cv1.wait(mutex1); } cout << "parent finishing" << endl; mutex1.unlock(); } int main() { cpu::boot((thread_startfunc_t) parent, (void *) 100, 0); }
B. Think about what resources are acquired and released in Project 2, and consider using RAII to acquire/release these resources.
Solve question 5 from the Fall 2016 midterm. | https://web.eecs.umich.edu/~pmchen/eecs482/homework/raii.html | CC-MAIN-2018-51 | refinedweb | 315 | 65.83 |
On Wed, 4 Aug 2010, Valerie Aurora wrote:> > Another idea is to use an internal inode and make all fallthroughs be> > hard links to that.> > > > I think the same would work for whiteouts as well. I don't like the> > fact that whiteouts are invisible even when not mounted as part of a> > union.> > I don't know if this helps, but I just wrote support for removing ext2> whiteouts and fallthrus using tune2fs and e2fsck. I think this does> what people want from a "visible" whiteout feature without adding more> complexity to the VFS. It also takes away all consideration of race> conditions and dentry conversion that happens with online removal of> whiteouts and fallthrus.> > What are your thoughts on what a visible whiteout/fallthru would look> like?Best would be if it didn't need any modification to filesystems. Allthis having to upgrade util-linux, e2fsprogs, having incompatiblefilesystem features is a pain for users (just been through that).What we already have in most filesystems: - extended attributes, e.g. use the system.union.* namespace and denote whiteouts and falltroughs with such an attribute - hard links to make sure a separate inode is not necessary for each whiteout/fallthrough entry - some way for the user to easily identify such files when not mounted as part of a union e.g. make it a symlink pointing to "(deleted)" or whateverLater the extended attributes can also be used for other things likee.g. chmod()/chown() only copying up metadata, not data, andindicating that data is still found on the lower layers.Miklos | http://lkml.org/lkml/2010/8/5/163 | CC-MAIN-2016-22 | refinedweb | 261 | 62.07 |
Microsoft .NET executables аre different from typicаl Windows executables in thаt they cаrry not only code аnd dаtа, but аlso metаdаtа (see Section 2.3 аnd Section 2.5 lаter in this chаpter). In this section, we stаrt off with the code for severаl .NET аpplicаtions, аnd discuss the .NET PE formаt.
Let's stаrt off by exаmining а simple Hello, World аpplicаtion written in Mаnаged C++, а Microsoft .NET extension to the C++ lаnguаge. Mаnаged C++ includes а number of new CLR-specific keywords thаt permit C++ progrаms to tаke аdvаntаge of CLR feаtures, including gаrbаge collection. Here's the Mаnаged C++ version of our progrаm:
#using <mscorlib.dll> using nаmespаce System; void mаin( ) { Console::WriteLine(L"C++ Hello, World!"); }
As you cаn see, this is а simple C++ progrаm with аn аdditionаl directive, #using (shown in bold). If you hаve worked with the Microsoft Visuаl C++ compiler support feаtures for COM, you mаy be fаmiliаr with the #import directive. While #import reverse-engineers type informаtion to generаte wrаpper classes for COM interfаces, #using mаkes аll types аccessible from the specified DLL, similаr to а #include directive in C or C++. However, unlike #include, which imports C or C++ types, #using imports types for аny .NET аssembly, written in аny .NET lаnguаge.
The one аnd only stаtement within the mаin( ) method is self-explаnаtoryit meаns thаt we аre invoking а stаtic or class-level method, WriteLine( ), on the Console class. The L thаt prefixes the literаl string tells the C++ compiler to convert the literаl into а Unicode string. You mаy hаve аlreаdy guessed thаt the Console class is а type hosted by mscorlib.dll, аnd the WriteLine( ) method tаkes one string pаrаmeter.
One thing thаt you should аlso notice is thаt this code signаls to the compiler thаt we're using the types in the System nаmespаce, аs indicаted by the using nаmespаce stаtement. This аllows us to refer to Console insteаd of hаving to fully quаlify this class аs System::Console.
Given this simple progrаm, compile it using the new C++ commаnd-line compiler shipped with the .NET SDK:
cl hello.cpp /CLR /link /entry:mаin
The /CLR commаnd-line option is extremely importаnt, becаuse it tells the C++ compiler to generаte а .NET PE file insteаd of а normаl Windows PE file.
When this stаtement is executed, the C++ compiler generаtes аn executable cаlled hello.exe. When you run hello.exe, the CLR loаds, verifies, аnd executes it.
Becаuse .NET is serious аbout lаnguаge integrаtion, we'll illustrаte this sаme progrаm using C#, а lаnguаge especiаlly designed for .NET. Borrowing from Jаvа аnd C++ syntаx, C# is а simple аnd object-oriented lаnguаge thаt Microsoft hаs used to write the bulk of the .NET bаse classes аnd tools. If you аre а Jаvа (or C++) progrаmmer, you should hаve no problem understаnding C# code. Here's Hello, World in C#:
using System; public class MаinApp { public stаtic void Mаin( ) { Console.WriteLine("C# Hello, World!"); } }
C# is similаr to Jаvа in thаt it doesn't hаve the concept of а heаder file: class definitions аnd implementаtions аre stored in the sаme .cs file. Another similаrity to Jаvа is thаt Mаin( ) is а public, stаtic function of а pаrticulаr class, аs you cаn see from the code. This is different from C++, where mаin( ) itself is а globаl function.
The using keyword here functions similаr to using nаmespаce in the previous exаmple, in thаt it signаls to the C# compiler thаt we wаnt to use types within the System nаmespаce. Here's how to compile this C# progrаm:
csc hello.cs
In this commаnd, csc is the C# compiler thаt comes with the .NET SDK. Agаin, the result of executing this commаnd is аn executable cаlled hello.exe, which you cаn execute like а normаl EXE but it's mаnаged by the CLR.
Here is the sаme progrаm in Visuаl Bаsic .NET (VB.NET):
Imports System Public Module MаinApp Public Sub Mаin( ) Console.WriteLine ("VB Hello, World!") End Sub End Module
If you аre а VB progrаmmer, you mаy be in for а surprise. The syntаx of the lаnguаge hаs chаnged quite а bit, but luckily these chаnges mаke the lаnguаge mirror other object-oriented lаnguаges, such аs C# аnd C++. Look cаrefully аt this code snippet, аnd you will see thаt you cаn trаnslаte eаch line of code here into аn equivаlent in C#. Whereаs C# uses the keywords using аnd class, VB.NET uses the keywords Import аnd Module, respectively. Here's how to compile this progrаm:
vbc /t:exe /out:hello.exe hello.vb
Microsoft now provides а commаnd-line compiler, vbc, for VB.NET. The /t option specifies the type of PE file to be creаted. In this cаse, since we hаve specified аn EXE, hello.exe will be the output of this commаnd.
And since Microsoft hаs аdded the Visuаl J# compiler, which аllows progrаmmers to write Jаvа code thаt tаrgets the CLR, we'll show the sаme progrаm in J# for completeness:
import System.*; public class MаinApp { public stаtic void mаin( ) { Console.WriteLine("J# hello world!"); } }
If you cаrefully compаre this simple J# progrаm with the previously shown C# progrаm, you'll notice thаt the two lаnguаges аre very similаr. For exаmple, the only difference (other thаn the obvious literаl string) is thаt the J# version uses the import directive, insteаd of the using directive. Here's how to compile this progrаm:
vjc hello.jsl
In this commаnd, vjc is the J# compiler thаt comes with the .NET SDK. The result of executing this commаnd is аn executable cаlled hello.exe, tаrgeting the CLR.
A Windows executable, EXE or DLL, must conform to а file formаt cаlled the PE file formаt, which is а derivаtive of the Common Object File Formаt (COFF). Both of these formаts аre fully specified аnd publicly аvаilаble. The Windows OS knows how to loаd аnd execute DLLs аnd EXEs becаuse it understаnds the formаt of а PE file. As а result, аny compiler thаt wаnts to generаte Windows executables must obey the PE/COFF specificаtion.
A stаndаrd Windows PE file is divided into а number of sections, stаrting off with аn MS-DOS heаder, followed by а PE heаder, followed by аn optionаl heаder, аnd finаlly followed by а number of nаtive imаge sections, including the .text, .dаtа, .rdаtа, аnd .rsrc sections. These аre the stаndаrd sections of а typicаl Windows executable, but Microsoft's C/C++ compiler аllows you to аdd your own custom sections into the PE file using а compiler #prаgmа directive. For exаmple, you cаn creаte your own dаtа section to hold encrypted dаtа thаt only you cаn reаd.
To support the CLR, Microsoft hаs extended the PE/COFF file formаt to include metаdаtа аnd IL code. The CLR uses metаdаtа to determine how to loаd classes аnd uses the IL code to turn it into nаtive code for execution. As shown in Figure 2-2, the extensions thаt Microsoft hаs аdded to the normаl PE formаt include the CLR heаder аnd CLR dаtа. The CLR heаder mаinly stores relаtive virtuаl аddresses (RVA) to locаtions thаt hold pertinent informаtion to help the CLR mаnаge progrаm execution. The CLR dаtа portion contаins metаdаtа аnd IL code, both of which determine how the progrаm will be executed. Compilers thаt tаrget the CLR must emit both the CLR heаder аnd dаtа informаtion into the generаted PE file, otherwise the resulting PE file will not run under the CLR.
If you wаnt to prove to yourself thаt а .NET executable contаins this informаtion, use the dumpbin.exe utility, which dumps the content of а Windows executable in reаdаble text.[1]
[1] Note thаt you cаn dump the sаme informаtion, in а more reаdаble formаt, using the ildаsm.exe utility, to be discussed lаter in this chаpter.
For exаmple, running the following commаnd on the commаnd prompt:
dumpbin.exe hello.exe /аll
generаtes the following dаtа (for brevity, we hаve shown only the mаin elements thаt we wаnt to illustrаte):
Microsoft (R) COFF/PE Dumper Version 7.1O.2292 Copyright (C) Microsoft Corporаtion. All rights reserved. Dump of file hello.exe PE signаture found File Type: EXECUTABLE IMAGE FILE HEADER VALUES /* 128-BYTE MS-DOS/COFF HEADER */ 14C mаchine (x86) . . . OPTIONAL HEADER VALUES /* FOLLOWED BY PE AND OPTIONAL HEADERS */ 1OB mаgic # (PE32) . . . SECTION HEADER #1 /* CODE SECTION */ .text nаme . . .
Looking аt this text dump of а .NET PE file, you cаn see thаt а PE file stаrts off with the MS-DOS/COFF heаder, which аll Windows progrаms must include. Following this heаder, you will find the PE heаder thаt supports Windows 32-bit progrаms. Immediаtely аfter the PE heаders, you cаn find the code section for this progrаm. The rаw dаtа (RAW DATA #1) of this section stores the CLR heаder, аs follows:
RAW DATA #1 . . . clr Heаder: /* CLR HEADER */ 48 cb 2.OO runtime version 2O7C [ 214] RVA [size] of MetаDаtа Directory 1 flаgs 6OOOOO1 entry point token O [ O] RVA [size] of Resources Directory O [ O] RVA [size] of StrongNаmeSignаture Directory O [ O] RVA [size] of CodeMаnаgerTаble Directory O [ O] RVA [size] of VTаbleFixups Directory O [ O] RVA [size] of ExportAddressTаbleJumps Directory Section contаins the following imports: mscoree.dll . . . O _CorExeMаin . . .
As mentioned eаrlier, the CLR heаder holds а number of pertinent detаils required by the runtime, including:
Indicаtes the runtime version thаt is required to run this progrаm
Is importаnt becаuse it indicаtes the locаtion of the metаdаtа needed by the CLR аt runtime
Is even more importаnt becаuse, for а single file аssembly, this is the token thаt signifies the entry point, such аs Mаin( ), thаt the CLR executes
Below the CLR Heаder, note thаt there is аn imported function cаlled _CorExeMаin, which is implemented by mscoree.dll, the core execution engine of the CLR.[2] At the time of this writing, Windows 98, 2OOO, аnd Me hаve аn OS loаder thаt knows how to loаd stаndаrd PE files. To prevent mаssive chаnges to these operаting systems аnd still аllow .NET аpplicаtions to run on them, Microsoft hаs updаted the OS loаders for аll these plаtforms. The updаted loаders know how to check for the CLR heаder, аnd, if this heаder exists, it executes _CorExeMаin, thus not only jumpstаrting the CLR but аlso surrendering to it. You cаn then guess thаt the CLR will cаll Mаin( ), since it cаn find the entry point token within the CLR heаder.[3]
[2] We invite you to run dumpbin.exe аnd view the exports of mscoree.dll аt your convenience. You will аlso find _CorDllMаin, _CorExeMаin, _CorImаgeUnloаding, аnd other interesting exports. It's interesting to note thаt this DLL is аn in-process COM server, аttesting thаt .NET is creаted using COM techniques.
[3] For brevity, we've covered only the importаnt content of this heаder. If you wаnt to leаrn the meаnings of the rest, see this chаpter's exаmple code, which you cаn downloаd fromаtаlog/dotnetfrmess3/.
Now thаt we've looked аt the contents of the CLR heаder, let's exаmine the contents of the CLR dаtа, including metаdаtа аnd code, which аre аrguаbly the most importаnt elements in .NET. | http://etutorials.org/Programming/.NET+Framework+Essentials/Chapter+2.+The+Common+Language+Runtime/2.2+CLR+Executables/ | crawl-001 | refinedweb | 1,866 | 64.1 |
import "github.com/rackspace/gophercloud/openstack/networking/v2/networks"
Package networks contains functionality for working with Neutron network resources. A network is an isolated virtual layer-2 broadcast domain that is typically reserved for the tenant who created it (unless you configure the network to be shared). Tenants can create multiple networks until the thresholds per-tenant quota is reached.
In the v2.0 Networking API, the network is the main entity. Ports and subnets are always associated with a network.
doc.go errors.go requests.go results.go urls.go
func ExtractNetworks(page pagination.Page) ([]Network, error)
ExtractNetworks accepts a Page struct, specifically a NetworkPage struct, and extracts the elements into a slice of Network structs. In other words, a generic collection is mapped into a relevant slice.
func IDFromName(client *gophercloud.ServiceClient, name string) (string, error)
IDFromName is a convenience function that returns a network's ID given its name.
func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager
List returns a Pager which allows you to iterate over a collection of networks. It accepts a ListOpts struct, which allows you to filter and sort the returned collection for greater efficiency.
AdminState gives users a solid type to work with for create and update operations. It is recommended that users use the `Up` and `Down` enums.
var ( Up AdminState = &iTrue Down AdminState = &iFalse )
Convenience vars for AdminStateUp values.
CreateOpts is the common options struct used in this package's Create operation.
func (opts CreateOpts) ToNetworkCreateMap() (map[string]interface{}, error)
ToNetwork..
Extract is a function that accepts a result and extracts a network resource.
type DeleteResult struct { gophercloud.ErrResult }
DeleteResult represents the result of a delete operation.
func Delete(c *gophercloud.ServiceClient, networkID string) DeleteResult
Delete accepts a unique ID and deletes the network associated with it.
GetResult represents the result of a get operation.
func Get(c *gophercloud.ServiceClient, id string) GetResult
Get retrieves a specific network based on its unique ID.
Extract is a function that accepts a result and extracts a network resource.
type ListOpts struct { Status string `q:"status"` Name string `q:"name"` AdminStateUp *bool `q:"admin_state_up"` TenantID string `q:"tenant_id"` *bool `q:"shared"` ID string `q:"id"` Marker string `q:"marker"` Limit int `q:"limit"` SortKey string `q:"sort_key"` SortDir string `q:"sort_dir"` }
ListOpts allows the filtering and sorting of paginated collections through the API. Filtering is achieved by passing in struct field values that map to the network attributes you want to see returned. SortKey allows you to sort by a particular network attribute. SortDir sets the direction, and is either `asc' or `desc'. Marker and Limit are used for pagination.
ToNetworkListQuery formats a ListOpts into a query string.
ListOptsBuilder allows extensions to add additional parameters to the List request.
type Network struct { // UUID for the network ID string `mapstructure:"id" json:"id"` // Human-readable name for the network. Might not be unique. Name string `mapstructure:"name" json:"name"` // The administrative state of network. If false (down), the network does not forward packets. AdminStateUp bool `mapstructure:"admin_state_up" json:"admin_state_up"` // Indicates whether network is currently operational. Possible values include // `ACTIVE', `DOWN', `BUILD', or `ERROR'. Plug-ins might define additional values. Status string `mapstructure:"status" json:"status"` // Subnets associated with this network. Subnets []string `mapstructure:"subnets" json:"subnets"` // Owner of network. Only admin users can specify a tenant_id other than its own. TenantID string `mapstructure:"tenant_id" json:"tenant_id"` // Specifies whether the network resource can be accessed by any tenant or not. bool `mapstructure:"shared" json:"shared"` }
Network represents, well, a network.
type NetworkPage struct { pagination.LinkedPageBase }
NetworkPage is the page returned by a pager when traversing over a collection of networks.
func (p NetworkPage) IsEmpty() (bool, error)
IsEmpty checks whether a NetworkPage struct is empty.
func (p NetworkPage) NextPageURL() (string, error)
NextPageURL is invoked when a paginated collection of networks has reached the end of a page and the pager seeks to traverse over a new one. In order to do this, it needs to construct the next page's URL.
UpdateOpts is the common options struct used in this package's Update operation.
func (opts UpdateOpts) ToNetworkUpdateMap() (map[string]interface{}, error)
ToNetworkUpdateMap casts, networkID string, opts UpdateOptsBuilder) UpdateResult
Update accepts a UpdateOpts struct and updates an existing network using the values provided. For more information, see the Create function.
Extract is a function that accepts a result and extracts a network resource.
Package networks imports 4 packages (graph) and is imported by 147 packages. Updated 2016-07-23. Refresh now. Tools for package owners. | https://godoc.org/github.com/rackspace/gophercloud/openstack/networking/v2/networks | CC-MAIN-2019-39 | refinedweb | 750 | 51.24 |
downloading through proxy not working
Bug Description
I'm working on a suse unix system, and I have an environment variable:
http_proxy=http://
When I do a python ./bootstrap, I get the following error:
Traceback (most recent call last):
File "/tmp/tmpXwJvtd
user_defaults, windows_restart, command)
File "/tmp/tmpXwJvtd
data[
File "/tmp/tmpXwJvtd
eresult = _open(base, extends.pop(0), seen, dl_options, override)
File "/tmp/tmpXwJvtd
eresult = _open(base, extends.pop(0), seen, dl_options, override)
File "/tmp/tmpXwJvtd
path, is_temp = download(filename)
File "/tmp/tmpXwJvtd
local_path, is_temp = self.download(url, md5sum, path)
File "/tmp/tmpXwJvtd
tmp_path, headers = urllib.
File "/usr/lib64/
return _urlopener.
File "/usr/lib64/
fp = self.open(url, data)
File "/usr/lib64/
return getattr(self, name)(url)
File "/usr/lib64/
h.endheaders()
File "/usr/lib64/
self.
File "/usr/lib64/
self.send(msg)
File "/usr/lib64/
self.connect()
File "/usr/lib64/
socket.
IOError: [Errno socket error] (-2, 'Name or service not known')
After a little debugging it seems that urllib.urlretrieve seems to be the culprit. It can't handle this kind of proxy setting. I have also tried this in a little standalone python script, and it has the same bad result.
urllib2 handles the proxy setting just fine. So if I change this line:
tmp_path, headers = urllib.
into this:
import urllib2
tmp_sock = urllib2.
tmp_file = open(tmp_path, 'w')
tmp_file.
tmp_file.close()
then all works fine.
Now this code might not be great, but is it possible that urllib2 will be used as a workaround for this proxy issue?
Cheers, Huub
The above tests were done on Ubuntu 11.04 and 12.04.
Clayton
This sounds like a bug in the Python standard library. Have you reported it at http://
The problem I think is that I used a proxy with authentication, which is not supported in urllib:
"Proxies which require authentication for use are not currently supported; this is considered an implementation limitation."
http://
Still, the error message from urllib is misleading. Is it trying to resolve a host named 'user:password@
Please file a urllib bug at http://
This error is not detected in machines with python2.4.
The error is detected in zc.buildout 1.4.4 and 1.5.2 with python2.6.
When I use cntlm version 0.35 I dont't detect the problem, but when i use cntlm version > 0.9 the error occurs.
With ntlmaps it's working.
I did what is described above and it worked.
Clayton | https://bugs.launchpad.net/zc.buildout/+bug/484735 | CC-MAIN-2017-47 | refinedweb | 405 | 69.99 |
Table of Contents
Adding Facets
These directions are based on the excellent documentation provided by the Solrmarc project. Below is a simplified version. For more detailed information about custom indexing and translation, See the Solrmarc wiki.
Adding a facet to the Narrow Search box is a relatively straightforward procedure. Because facets rely on an index field, these instructions assume we are beginning with one of three possible scenarios:
1. The index field to be used already exists
2. No index field currently exists; the data in the MARC record will be indexed directly (i.e. data is already a text string with no need or desire for normalization)
3. No index field currently exists; data is encoded and will need to be translated into text strings first
Index field exists
Example used: Adding the date of publication as a facet
First verify existence of the index field and make sure it contains the data you want. $VUFIND_HOME/import/marc.properties contains the default mapping of MARC fields to the Solr index. Each line of the file populates a single index field. The name of the Solr index field is before the equal sign. Immediately following the equal sign is one or more combinations of the three digit MARC tag number and any subfields that are indexed together. A colon separates different MARC fields or subfields to be indexed separately. A number in brackets indicates the byte-position to be indexed. “First” at the end of the line means only the first value will be indexed.
In our example, the publishDate index is a custom index not pulled directly from a MARC tag. The DateOfPublication custom indexing routine provided the date to the indexer, but we do not need to know how it does that to proceed. We have identified that the index in question is called publishDate, which is all we need right now.
The file facets.ini contains the lists of facets to be viewed. Each line is a facet, in the form:
SolrIndexName = Facet Display Name
(In a clean installation, this includes the first two facets, Institution and Library, which may not be needed. They can be commented out by inserting a semicolon at the beginning of the line). To add publication date as a facet, simply add the following line to the file:
publishDate = Publication Year
*Note that the facets are displayed in order; if publishDate is added at the bottom of the list, it will appear at the bottom of the Narrow Search box below the rest.
That's it. Changes are immediately reflected on the search results page.
If, due to typos, etc, a non-existent index field is added to the list, this may break the Narrow Search box completely and prevent facets from displaying.
Index field does not exist, no translation needed
Example: a customized genre facet based on the genre heading fields and subfields
If the desired facet is not already an existing index field, we must first create the field. This will require re-indexing of all of your records.
The file $VUFIND_HOME/import/marc.properties maps MARC fields and subfields to an index. For a more detailed description of the file format than provided above, see the SolrMarc documentation.
In this example, we want to use the strings found in the 655 subfield a, and the subfield v data from the 650, 651, and 600 fields. The index will be called “allgenre”. To do this, we add the following line to marc.properties:
allgenre = 655ab:650v:600v:651v
We now need to tell Solr what to do with the new index. File $VUFIND_HOME/solr/vufind/biblio/conf/schema.xml defines the fields in Solr. In the <fields> section, we add
<field name="allgenre" type="textFacet" indexed="true" stored="true" multiValued="true" termVectors="true"/>
After the database has been re-indexed, the allgenre index field will exist. The facet can be added to the facets.ini file as described above.
A Useful Shortcut -- Dynamic Fields
If you are using VuFind 1.3 or newer, you can take advantage of dynamic Solr fields to avoid modifying your schema. VuFind is configured to recognize certain field suffixes and treat them as new fields without requiring explicit definitions. In the example above, you could use the field name allgenre_txtF_mv instead of allgenre in marc.properties and skip the schema.xml step.
See this page for all of the available suffixes.
A Best Practice -- Local Settings Directory
While the example above suggests editing marc.properties directly, VuFind 2.0 and later supports a local settings directory which isolates your custom changes from the core VuFind code. If you put your customizations in $VUFIND_LOCAL_DIR/import/marc_local.properties instead of $VUFIND_HOME/import/marc.properties, then the lines in marc_local.properties will override the equivalent lines in marc.properties. This allows you to specify your changes in one place, but makes it easier to upgrade changes and additions to the core configuration during future upgrades.
See local MARC mappings for more details.
Index field does not exist, translation needed
Example: Instrument types for music
For encoded data (such as data found in the 007, 008, or several 04X fields), we must first map the data to text strings. If the language translation system is used, the values can also be indexed without mapping (see below). Luckily, the MARC format is well documented and lists of what each code means are readily available on the MARC Code Lists and at OCLC's Formats and Standards page.
Mapping values during indexing
Create a text file in $VUFIND_LOCAL_DIR/import/translation_maps and name it “something.properties”. In this case, I have created the file $VUFIND_LOCAL_DIR/import/translation_maps/instrument_map.properties to contain the mapping. The file will translate the two-letter codes used in the MARC 048 field into readable text. Each line of the file contains a single possible code and its translation. Example:
ka = Piano kb = Organ kc = Harpsichord kd = Clavichord
Etc.
In $VUFIND_HOME/import/marc.properties (or the local MARC mappings file, if you want to separate your local changes from the defaults provided by VuFind), we add the following line:
instrument_facet = 048a[0-1], instrument_map.properties
Of note: The numbers in brackets indicate that the system should look at only the first two bytes in the 048 subfield a field (0-1 mean position 0 to position 1). A comma separates the field information from the name of the file used to translate the data, in this case, instrument_map.properties.
A line defining the new index field must be added to Solr's schema.xml file (usually found in $VUFIND_HOME/solr/vufind/biblio/conf) and a line for the new facet will be added to facets.ini (see above for instructions).
Translating values with the language translation system
Strings in facet fields can be translated to user-friendly form and/or to different languages using VuFind's translation support. Steps needed to enable traslation of institution and building facets:
1. Add the facets to translated_facets[] setting in $VUFIND_LOCAL_DIR/config/vufind/facets.ini. Using namespaces as below is recommended so that any values in different facet fields or other translations don't overlap:
[Advanced_Settings] translated_facets[] = institution:institution translated_facets[] = building:building
2. Add translations for institution facet to $VUFIND_LOCAL_DIR/languages/institution/en.ini:
CPL = "Centerville Library"
3. Add translations for building facet to $VUFIND_LOCAL_DIR/languages/building/en.ini:
AV = "Audiovisual" GEN = "General Stacks"
Troubleshooting
string vs. text fields
If you set up a facet field and see individual words instead of complete facet values, this most likely means that you have faceted on an analyzed field (usually of type “text” in VuFind's Solr schema). Solr faceting displays the terms stored in the index, not the original raw text provided at index-time. Thus, if you facet on an analyzed field that tokenizes and manipulates strings, strange facet values may appear to the end user. Most of the time, you only want to facet on simple string fields to avoid this problem. This is why the default schema includes some apparently duplicate values – it is generally necessary to use different fields for search-oriented and facet-oriented tasks. | https://vufind.org/wiki/indexing:adding_facets | CC-MAIN-2022-05 | refinedweb | 1,357 | 55.74 |
BBC micro:bit
Pedestrian Crossing
Introduction
This project simulates some of the traffic lights involved in a pedestrian crossing.
For my version, I used the Pi-Stop, which was designed for use with Raspberry Pi GPIO ports. It is meant for 3V logic and is nice and compact with resistors built into the package. Standard LEDs are fine for this too.
I've set up my simulation with 3 sets of lights. 2 of these sets will be for the cars. The third set is for one direction of the pedestrian crossing. That makes 8 LEDs. A shift register is a good way to leave some GPIO free to add more features to the project later.
Circuit
To get the principle understood and a prototype built, this is set up on a single breadboard. That makes it the same circuit as our shift register with 8 LEDs. The only difference is the choice of colours and a little bit of spacing out.
Diagrams with shift registers always look a little confusing. The other page in this section explains more of the principles and has some text that explains the connections.
Program
We can use binary notation to describe the patterns of lights. This program has a ShiftOut() function to make the process a little easier. The timings are just to give a sense of the process. You can look up the true timings if you want to aim for a hyper-realistic simulation.
The ShiftOut function is a useful general purpose function that you can use with this shift register whenever you want. The statements are executed as quickly as the micro:bit can execute Python statements. That doesn't seem to threaten the limits of the integrated circuit, which correctly notices the changes in pin states.
from microbit import * def ShiftOut(value): pin0.write_digital(0) pin1.write_digital(0) pin2.write_digital(0) bits = [value >> i & 1 for i in range(7,-1,-1)] for i in range(7,-1,-1): pin0.write_digital(bits[i]) pin1.write_digital(1) pin1.write_digital(0) pin2.write_digital(1) pin2.write_digital(0) def NoWalk(): ShiftOut(0b00100110) def FlashAmber(): for i in range(0,9): ShiftOut(0b01001010) sleep(250) ShiftOut(0b00000010) sleep(250) def AmberGambler(): ShiftOut(0b01001010) def Walk(): ShiftOut(0b10010001) def FlashGreen(): for i in range(0,9): ShiftOut(0b10010001) sleep(250) ShiftOut(0b10010000) sleep(250) NoWalk() while True: if button_a.is_pressed(): display.show(Image.NO) sleep(3000) AmberGambler() sleep(3000) display.show(Image.YES) Walk() sleep(3000) FlashGreen() FlashAmber() NoWalk() display.clear()
Check that you can follow how the binary patterns relate to which LEDs are on or off at any one time.
Challenges
- Obviously, there is a set of lights missing. You could add those. You can use GPIO for this or read about how to chain two of these shift registers together.
- Move the pin 0 connection to another GPIO pin and add a buzzer. Play some appropriate beeps in the same style as the real thing.
- Hunt down the toys that could be used to bring this scene to life. Get hacking.
- Forget about traffics, it's mini disco light time. | http://multiwingspan.co.uk/micro.php?page=pedestrian | CC-MAIN-2017-22 | refinedweb | 519 | 74.59 |
I recently upgraded to Intellij-12 and xmlns:ivy="antlib:org.apache.ivy.ant" is no longer recongized Follow
My environment is as follows
1 Intellij Version : 12 IU-129.713
2. Operating System : Software OS X 10.8.4 (12E55)
My ant build file was working fine in Intellij 11.x but after upgrade to 12. Intellij does seem to recongize the antlib: directive the the ant build file.
Any help will be greatly appreciated.
Regards,
Swarn
You need to configure the external resource so IDEA can parse the schema associated with the namespace declaration.
You can alternatively configure this in the settings dialog. You can also edit and previous settings. | https://intellij-support.jetbrains.com/hc/en-us/community/posts/206870495-I-recently-upgraded-to-Intellij-12-and-xmlns-ivy-antlib-org-apache-ivy-ant-is-no-longer-recongized | CC-MAIN-2019-26 | refinedweb | 112 | 52.87 |
Does enumerate() produce a generator enumerate() produce a generator object?
As a complete Python newbie, it certainly looks that way. Running the following...
x = enumerate(['fee', 'fie', 'foe']) x.next() # Out[1]: (0, 'fee') list(x) # Out[2]: [(1, 'fie'), (2, 'foe')] list(x) # Out[3]: []
... I notice that: (a)
x does have a
next method, as seems to be
required for generators, and (b)
x can only be iterated over once, a
characteristic of generators emphasized in this famous
python-tag
answer.
On the other hand, the two most highly-upvoted answers to this
question
about how to determine whether an object is a generator would seem to
indicate that
enumerate() does not return a generator.
import types import inspect x = enumerate(['fee', 'fie', 'foe']) isinstance(x, types.GeneratorType) # Out[4]: False inspect.isgenerator(x) # Out[5]: False
... while a third poorly-upvoted answer to that question would seem to indicate that
enumerate() does in fact return a generator:
def isgenerator(iterable): return hasattr(iterable,'__iter__') and not hasattr(iterable,'__len__') isgenerator(x) # Out[8]: True
So what's going on? Is
x a generator or not? Is it in some sense
"generator-like", but not an actual generator? Does Python's use of
duck-typing mean that the test outlined in the final code block above
is actually the best one?
Rather than continue to write down the possibilities running through my head, I'll just throw this out to those of you who will immediately know the answer. | https://prodevsblog.com/questions/149734/does-enumerate-produce-a-generator-object/ | CC-MAIN-2020-40 | refinedweb | 251 | 56.45 |
Centered spines with arrows¶
This example shows a way to draw a "math textbook" style plot, where the
spines ("axes lines") are drawn at
x = 0 and
y = 0, and have arrows at
their ends.
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() # Move the left and bottom spines to x = 0 and y = 0, respectively. ax.spines[["left", "bottom"]].set_position(("data", 0)) # Hide the top and right spines. ax.spines[["top", "right"]].set_visible(False) # Draw arrows (as black triangles: ">k"/"^k") at the end of the axes. In each # case, one of the coordinates (0) is a data coordinate (i.e., y = 0 or x = 0, # respectively) and the other one (1) is an axes coordinate (i.e., at the very # right/top of the axes). Also, disable clipping (clip_on=False) as the marker # actually spills out of the axes. ax.plot(1, 0, ">k", transform=ax.get_yaxis_transform(), clip_on=False) ax.plot(0, 1, "^k", transform=ax.get_xaxis_transform(), clip_on=False) # Some sample data. x = np.linspace(-0.5, 1., 100) ax.plot(x, np.sin(x*np.pi)) plt.show()
Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery | https://matplotlib.org/3.4.3/gallery/ticks_and_spines/centered_spines_with_arrows.html | CC-MAIN-2022-27 | refinedweb | 199 | 68.16 |
While learning Java, you'll occasionally encounter a language behavior that leaves you puzzled. For example, what does expression
new int[10] instanceof Object returning
true signify about arrays? In this post, I'll examine some of Java's language oddities.
Arrays are objects
A long time ago, while writing about message formatters, I encountered something strange in Java's
java.text.MessageFormat standard library class. Consider the following pair of formatting methods:
StringBuffer format(Object[] arguments, StringBuffer result, FieldPosition pos)
StringBuffer format(Object arguments, StringBuffer result, FieldPosition pos)
According to the Javadoc, either method formats an array of objects. Wait a minute! How can you pass an array of objects to
Object arguments? Is this a Javadoc misprint? The answer is no: you can pass an array of objects to this parameter.
The Java Language Specification explains this oddity. Section 10.1. Array Types states (in the fine print) that
Object is also a supertype of all array types. Hence, each of the following lines of code will output
true:
System.out.println(new int[10] instanceof Object); System.out.println(new String[] { "A", "B" } instanceof Object);
I've created an
ArraysAreObjects application that demonstrates arrays being objects. Listing 1 presents the application's source code.
Listing 1.
ArraysAreObjects.java (version 1)
public class ArraysAreObjects { public static void main(String[] args) { print(new String[] { "A", "B", "C" }); print("Hello"); print(new int[] { 1, 2, 3 }); print(new Integer[] { 1, 2, 3 }); } static void print(Object objects) { if (objects instanceof Object[]) for (Object object: (Object[]) objects) System.out.println(object); else System.out.printf("[%s]%n", objects); System.out.println(); } }
ArraysAreObjects declares a
print() method that prints an object or an array of objects. It differentiates between these cases via
objects instanceof Object[], which returns
true when
objects references an array of objects.
Compile Listing 1 as follows:
javac ArraysAreObjects.java
Run the resulting application as follows:
java ArraysAreObjects
You should observe the following output (with a different hash code):
A B C [Hello] [[I@42d3bd8b] 1 2 3
Perhaps you're surprised to see something like
[[I@42d3bd8b] instead of each integer on a separate line when executing
print(new int[] { 1, 2, 3 });. Section 4.10.3. Subtyping among Array Types provides an answer:
The following rules define the direct supertype relation among array types: If S and T are both reference types, then S[] >1 T[] iff S >1 T. Object >1 Object[] Cloneable >1 Object[] java.io.Serializable >1 Object[] If P is a primitive type, then: Object >1 P[] Cloneable >1 P[] java.io.Serializable >1 P[]
Essentially, this section tells us that
Object and not
Object[] is the supertype of a primitive array type
This information helps to explain why
MessageFormat has two
format() methods that differ only in the type of the first parameter:
Object[] or
Object. The
format() method with
Object[] as its first parameter is called for reference array type arguments (e.g.,
new String[] { "A", "B" }), whereas the other
format() method is called for primitive array type arguments, as in
format(new int[] { 1, 2, 3 }, sb, pos).
Never write code like that shown in Listing 1. Instead, use Java's variable arguments (varargs) language feature (introduced in Java 5 long after Java 1.1's debut of
MessageFormat) to achieve more concise code. Consider Listing 2.
Listing 2.
ArraysAreObjects.java (version 2)
public class ArraysAreObjects { public static void main(String[] args) { print("A", "B", "C"); print("Hello"); print(1, 2, 3); } static void print(Object... objects) { for (Object object: objects) System.out.println(object); System.out.println(); } }
Although this code is straightforward, you might be curious about
print(1, 2, 3);. The compiler generates code to autobox each integer into an
Integer object. These objects are stored in an
Object[] array that's passed to
print().
When you run this application, you should observe the following output:
A B C Hello 1 2 3
The
java.util package's
Arrays and
Objects classes also demonstrate the impact of arrays being objects.
Arrays declares a
boolean deepEquals(Object[] a1, Object[] a2) method to determine whether two arrays are deeply equal (defined in that method's Javadoc). Similarly,
Objects declares
boolean deepEquals(Object a, Object b) to determine whether two nonarray or array objects are deeply equal.
You don't have to use
Objects.deepEquals() to compare a pair of nonarray objects. Instead, you could create a pair of arrays to hold these objects and pass these arrays to
Arrays.deepEquals(). But isn't that a code smell?
In case you're wondering how primitive array types are handled, note that
Objects.deepEquals() and
Arrays.deepEquals() delegate to
Arrays.deepEquals0(). Here's that method's source code:
static boolean deepEquals0(Object e1, Object e2) { assert e1 != null; boolean eq; if (e1 instanceof Object[] && e2 instanceof Object[]) eq = deepEquals ((Object[]) e1, (Object[]) e2); else if (e1 instanceof byte[] && e2 instanceof byte[]) eq = equals((byte[]) e1, (byte[]) e2); else if (e1 instanceof short[] && e2 instanceof short[]) eq = equals((short[]) e1, (short[]) e2); else if (e1 instanceof int[] && e2 instanceof int[]) eq = equals((int[]) e1, (int[]) e2); else if (e1 instanceof long[] && e2 instanceof long[]) eq = equals((long[]) e1, (long[]) e2); else if (e1 instanceof char[] && e2 instanceof char[]) eq = equals((char[]) e1, (char[]) e2); else if (e1 instanceof float[] && e2 instanceof float[]) eq = equals((float[]) e1, (float[]) e2); else if (e1 instanceof double[] && e2 instanceof double[]) eq = equals((double[]) e1, (double[]) e2); else if (e1 instanceof boolean[] && e2 instanceof boolean[]) eq = equals((boolean[]) e1, (boolean[]) e2); else eq = e1.equals(e2); return eq; }
As you can see, each primitive array type is handled as a special case.
Bytes and shorts are second-class citizens
According to Section 4.2. Primitive Types and Values in the Java Language Specification, Java supports five integral types: byte integer, short integer, integer, long integer, and character. These primitive types are represented via keywords
byte,
short,
int,
long, and
char, respectively. Each of the
byte,
short,
int, and
long types represents a signed integer. In contrast,
char represents an unsigned UTF-16 code unit.
Consider
byte,
short,
int, and
long. Each type differs only in its range of values based on the number of bits associated with the type: 8 (
byte), 16 (
short), 32 (
int), or 64 (
long). Because
byte and
short have smaller ranges (-128 through 127 for
byte and -32768 through 32767 for
short), the Java virtual machine (JVM) was designed with limited support for these types (which saved a few instructions).
The JVM provides various
int-only instructions (e.g.,
iadd,
isub, and
imul). Similarly, the JVM provides various
long-only instructions (e.g.,
ladd,
ldiv, and
lneg). In contrast,
byte and
short don't merit similar instructions.
The JVM does provide the following instructions to support
byte and
short:
bipush: Sign-extend 8-bit byte integer operand to 32-bit integer and push the result onto the operand stack.
i2b: Pop the 32-bit integer from the top of the operand stack, truncate this value to an 8-bit byte integer, sign-extend the result to a 32-bit integer, and push the result onto the operand stack.
i2s: Pop the 32-bit integer from the top of the operand stack, truncate this value to a 16-bit short integer, sign-extend the result to a 32-bit integer, and push the result onto the operand stack.
sipush: Sign-extend 16-bit short integer operand to 32-bit integer and push the result onto the operand stack.
The Java language reflects this second-class support for
byte and
short by not supporting
byte or
short integer literals. An integer literal is either of type
int (with no suffix) or of type
long (with the
l or
L suffix). However, it does provide one convenience: when assigning an
int literal to a
byte or a
short variable, you don't have to specify a cast operator when the literal ranges from -128 through 127 (
byte) or -32768 through 32767 (
short). For example, you can specify
byte b = 27; instead of having to specify
byte b = (byte) 27;. Similarly, you can specify
short s = 299; instead of having to specify
short s = (short) 299;.
It's easier to understand this second-class citizen business when you examine the bytecode to a simple application. Consider Listing 3.
Listing 3.
BytesAndShorts.java (version 1)
public class BytesAndShorts { public static void main(String[] args) { byte b = 27; short s = 299; } }=3, args_size=1 0: bipush 27 2: istore_1 3: sipush 299 6: istore_2 7: return
There are three local variables: 0 (
args), 1 (
b), and 2 (
s).
At the source code level,
27 is a 32-bit integer literal. For efficiency,
27 is stored as an 8-bit byte following the operation code (opcode) for the
bipush instruction. As stated earlier, this instruction sign-extends this 8-bit value to a 32-bit value that's stored on the operand stack. This value will be popped off the stack and stored in local variable 1 (via
istore_1) -- recall that 1 refers to
b in the source code.
Here is something interesting: the
istore_1 instruction reveals that
byte variable
b is really of type
int at the JVM level. After all, the
istore instructions store 32-bit values.
Continuing with the disassembly,
sipush 299 sign-extends
299 to a 32-bit value that's stored on the operand stack, and the subsequent
istore_2 instruction stores this 32-bit value in
int variable
s.
It appears that the JVM does not recognize
byte or
short variables, but treats them as if they are of type
int. Listing 4 presents an application that probes deeper into this situation.
Listing 4.
BytesAndShorts.java (version 2)
public class BytesAndShorts { public static void main(String[] args) { int i = 35; byte b = (byte) i; short s = (byte) i; } }=4, args_size=1 0: bipush 35 2: istore_1 3: iload_1 4: i2b 5: istore_2 6: iload_1 7: i2b 8: i2s 9: istore_3 10: return
There are four local variables: 0 (
args), 1 (
i), 2 (
b), and 3 (
s).
The first two instructions convert
35 to a 32-bit integer and store it in
int variable
i. There are no surprises here. In contrast, the next three instructions retrieve this value, convert it to a
byte (via
i2b), and store the result in "
int" variable
b. Even though the JVM doesn't regard
b to be of type
byte, it still treats this variable as if it were a
byte:
i2b ensures that the 32-bit integer value won't lie outside the range -128 through 127.
The instruction sequence from offset 6 through offset 9 is interesting. I could have specified
short s = (short) i; instead of
short s = (byte) i; in the source code, but chose to deviate in order to see what happens at the JVM level. The
i2b instruction at offset 7 first converts the 32-bit integer value stored in
i to an 8-bit byte. The subsequent
i2s instruction converts this result to a 16-bit short integer, which is then sign-extended to a 32-bit integer in preparation for being stored in
s via
istore_3. The bytecode sequence for
short s = (byte) i; ensures that the value stored in "
int" variable
s doesn't lie outside the range -32768 through 32767 (and shows that you should avoid useless casts).
Private fields and methods are accessible without reflection
Under certain circumstances, you can access an object's
private field or call its
private method without having to use Java's Reflection API. Consider Listing 5. | https://www.javaworld.com/article/3252845/java-language/java-language-oddities.html | CC-MAIN-2018-09 | refinedweb | 1,933 | 53 |
A secondary index, put simply, is a way to efficiently access records in a database (the primary) by means of some piece of information other than the usual (primary) key. In Berkeley DB, this index is simply another database whose keys are these pieces of information (the secondary keys), and whose data are the primary keys. Secondary indexes can be created manually by the application; there is no disadvantage, other than complexity, to doing so.. A typical database would use the student ID number as the key; however, one might also reasonably want to be able to look up students by last name. To do this, one would construct a secondary index in which the secondary key was this last name.
In SQL, this would be done by executing something like the following:
CREATE TABLE students(student_id CHAR(4) NOT NULL, lastname CHAR(15), firstname CHAR(15), PRIMARY KEY(student_id)); CREATE INDEX lname ON students(lastname);
In Berkeley DB, this would work as follows (a Java API example is also available):
struct student_record { char student_id[4]; char last_name[15]; char first_name[15]; }; void second() { DB *dbp, *sdbp; int ret; /* Open/create primary */ if ((ret = db_create(&dbp, dbenv, 0)) != 0) handle_error(ret); if ((ret = dbp->open(dbp, NULL, "students.db", NULL, DB_BTREE, DB_CREATE, 0600)) != 0) handle_error(ret); /* * Open/create secondary. Note that it supports duplicate data * items, since last names might not be unique. */ if ((ret = db_create(&sdbp, dbenv, 0)) != 0) handle_error(ret); if ((ret = sdbp->set_flags(sdbp, DB_DUP | DB_DUPSORT)) != 0) handle_error(ret); if ((ret = sdbp->open(sdbp, NULL, "lastname.db", NULL, DB_BTREE, DB_CREATE, 0600)) != 0) handle_error(ret); /* Associate the secondary with the primary. */ if ((ret = dbp->associate(dbp, NULL, sdbp, getname, 0)) != 0) handle_error(ret); } /* * getname -- extracts a secondary key (the last name) student_record *)pdata->data)->last_name; skey->size = sizeof((struct student_record *)pdata->data)->last_name; return (0); }
From the application's perspective, putting things into the database works exactly as it does without a secondary index; one can simply insert records into the primary database. In SQL one would do the following:
INSERT INTO student VALUES ("WC42", "Churchill ", "Winston ");
and in Berkeley DB, one does:
struct student_record s; DBT data, key; memset(&key, 0, sizeof(DBT)); memset(&data, 0, sizeof(DBT)); memset(&s, 0, sizeof(struct student_record)); key.data = "WC42"; key.size = 4; memcpy(&s.student_id, "WC42", sizeof(s.student_id)); memcpy(&s.last_name, "Churchill ", sizeof(s.last_name)); memcpy(&s.first_name, "Winston ", sizeof(s.first_name)); data.data = &s; data.size = sizeof(s); if ((ret = dbp->put(dbp, txn, &key, &data, 0)) != 0) handle_error(ret);
Internally, a record with secondary key "Churchill" is inserted into the secondary database (in addition to the insertion of "WC42" into the primary, of course).
Deletes are similar. The SQL clause:
DELETE FROM student WHERE (student_id = "WC42");
looks like:
DBT key; memset(&key, 0, sizeof(DBT)); key.data = "WC42"; key.size = 4; if ((ret = dbp->del(dbp, txn, &key, 0)) != 0) handle_error(ret);
Deletes can also be performed on the secondary index directly; a delete done this way will delete the "real" record in the primary as well. If the secondary supports duplicates and there are duplicate occurrences of the secondary key, then all records with that secondary key are removed from both the secondary index and the primary database. In SQL:
DELETE FROM lname WHERE (lastname = "Churchill ");
In Berkeley DB:
DBT skey; memset(&skey, 0, sizeof(DBT)); skey.data = "Churchill "; skey.size = 15; if ((ret = sdbp->del(sdbp, txn, &skey, 0)) != 0) handle_error(ret);
Gets on a secondary automatically return the primary datum. If DB->pget() or DBC->pget() is used in lieu of DB->get() or DBC->get(), the primary key is returned as well. Thus, the equivalent of:
SELECT * from lname WHERE (lastname = "Churchill ");
would be:
DBT data, pkey, skey; <para /> memset(&skey, 0, sizeof(DBT)); memset(&pkey, 0, sizeof(DBT)); memset(&data, 0, sizeof(DBT)); skey.data = "Churchill "; skey.size = 15; if ((ret = sdbp->pget(sdbp, txn, &skey, &pkey, &data, 0)) != 0) handle_error(ret); /* * Now pkey contains "WC42" and data contains Winston's record. */
To create a secondary index to a Berkeley DB database, open the database that is to become a secondary index normally, then pass it as the "secondary" argument to the DB->associate() method for some primary database.
After a DB->associate() call is made, the secondary indexes become alternate interfaces to the primary database. All updates to the primary will be automatically reflected in each secondary index that has been associated with it. All get operations using the DB->get() or DBC->get() methods on the secondary index return the primary datum associated with the specified (or otherwise current, in the case of cursor operations) secondary key. The DB->pget() and DBC->pget() methods also become usable; these behave just like DB->get() and DBC->get(), but return the primary key in addition to the primary datum, for those applications that need it as well.
Cursor get operations on a secondary index perform as expected; although the data returned will by default be those of the primary database, a position in the secondary index is maintained normally, and records will appear in the order determined by the secondary key and the comparison function or other structure of the secondary database.
Delete operations on a secondary index delete the item from the primary database and all relevant secondaries, including the current one.
Put operations of any kind are forbidden on secondary indexes, as there is no way to specify a primary key for a newly put item. Instead, the application should use the DB->put() or DBC->put() methods on the primary database.
Any number of secondary indexes may be associated with a given primary database, up to limitations on available memory and the number of open file descriptors.
Note that although Berkeley DB guarantees that updates made using any DB handle with an associated secondary will be reflected in the that secondary, associating each primary handle with all the appropriate secondaries is the responsibility of the application and is not enforced by Berkeley DB. It is generally unsafe, but not forbidden by Berkeley DB, to modify a database that has secondary indexes without having those indexes open and associated. Similarly, it is generally unsafe, but not forbidden, to modify a secondary index directly. Applications that violate these rules face the possibility of outdated or incorrect results if the secondary indexes are later used.
If a secondary index becomes outdated for any reason, it should be discarded using the DB->remove() method and a new one created using the DB->associate() method. If a secondary index is no longer needed, all of its handles should be closed using the DB->close() method, and then the database should be removed using a new database handle and the DB->remove() method.
Closing a primary database handle automatically dis-associates all secondary database handles associated with it. | https://docs.oracle.com/cd/E17275_01/html/programmer_reference/am_second.html | CC-MAIN-2018-09 | refinedweb | 1,144 | 53.31 |
sensor_set_background()
Specify whether the sensor should continue operation when the system goes into standby.
Synopsis:
#include <bps/sensor.h>
BPS_API int sensor_set_background(sensor_type_t type, bool enable_background)
Since:
BlackBerry 10.0.0
Arguments:
- type
The sensor that should continue operation even in standby mode.
- enable_background
If true the sensor continues operation while in standby. If false, the sensor stops operation while the system is in standby.
Library:libbps (For the qcc command, use the -l bps option to link against this library)
Description:
The sensor_set_background() function when enabled allows the sensor to continue operation even when the system goes into standby mode.
If a sensor is set to stay active when the system is in standby mode, battery life is reduced.
Returns:
BPS_SUCCESS upon success, BPS_FAILURE with errno set otherwise.
Last modified: 2014-09-30
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | https://developer.blackberry.com/native/reference/core/com.qnx.doc.bps.lib_ref/topic/sensor_set_background.html | CC-MAIN-2019-35 | refinedweb | 150 | 51.04 |
I have been trying to parse a file with
xml.etree.ElementTree
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ParseError
def analyze(xml):
it = ET.iterparse(file(xml))
count = 0
last = None
try:
for (ev, el) in it:
count += 1
last = el
except ParseError:
print("catastrophic failure")
print("last successful: {0}".format(last))
print('count: {0}'.format(count))
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
from yparse import analyze; analyze('file.xml')
File "C:\Python27\yparse.py", line 10, in analyze
for (ev, el) in it:
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1258, in next
self._parser.feed(data)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1624, in feed
self._raiseerror(v)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1488, in _raiseerror
raise err
ParseError: reference to invalid character number: line 1, column 52459
As @John Machin suggested, the files in question do have dubious numeric entities in them, though the error messages seem to be pointing at the wrong place in the text. Perhaps the streaming nature and buffering are making it difficult to report accurate positions.
In fact, all of these entities appear in the text:
set(['', '', '', '', '', '', '
', '
', '', '', '', '�', '', '', '
', '', '', ' ', '', '', '', '', ''])
Most are not allowed. Looks like this parser is quite strict, you'll need to find another that is not so strict, or pre-process the XML. | https://codedump.io/share/wIodHv7YoWa5/1/why-is-elementtree-raising-a-parseerror | CC-MAIN-2016-50 | refinedweb | 232 | 60.51 |
Do I need an
extern "C" {} block to include standard C headers in a C++ program. Only consider standard C headers which do not have counterparts in C++.
For example:
extern "C" { #include <fcntl.h> #include <unistd.h> }
Do I need an
extern "C" {} block to include standard C headers in a C++ program. Only consider standard C headers which do not have counterparts in C++.
For example:
extern "C" { #include <fcntl.h> #include <unistd.h> }
The system C headers usually already include a
extern "C" block, guarded by
#ifdef __cplusplus. This way the functions automatically get declared as
extern "C" when compiled as C++ and you don’t need to do that manually.
For example on my system
unistd.h and
fcntl.h start with
__BEGIN_DECLS and end with
__END_DECLS, which are macros defined in
sys/cdefs.h:
/* C++ needs to know that types and declarations are C, not C++. */ #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS # define __END_DECLS #endif
The behavior of
<fcntl.h> and
<unistd.h> in C++ is not specified by the standard (because they are also not part of the C89 standard). That said, I have never seen a platform where they (a) exist and (b) actually need to be wrapped in an
extern "C" block.
The behavior of
<stdio.h>,
<math.h>, and the other standard C headers is specified by section D.5 of the C++03 standard. They do not require an
extern "C" wrapper block, and they dump their symbols into the global namespace. However, everything in Annex D is “deprecated”.
The canonical C++ form of those headers is
<cstdio>,
<cmath>, etc., and they are specified by section 17.4.1.2 (3) of the C++ standard, which says:
<cassert> <ciso646> <csetjmp> <cstdio> <ctime> <cctype> <climits> <csignal> <cstdlib> <cwchar> <cerrno> <clocale> <cstdarg> <cstring> <cwctype>
Except as noted in clauses 18 through 27,.
So the standard, non-deprecated, canonical way to use (e.g.)
printf in C++ is to
#include <cstdio> and then invoke
std::printf.
Yes, you do. However, many systems (notably Linux) are already adding an
extern "C" bracketing like you do. See (on Linux) files
/usr/include/unistd.h
/usr/include/features.h and the macro
__BEGIN_DECLS defined in
/usr/include/sys/cdefs.h and used in many Linux system include files.
So on Linux, you usually can avoid your
extern "C" but it does not harm (and, IMHO, improve readability in that case).
No, you should use the C++ wrapper headers (for instance like
<cstdio>). Those take care of all that for you.
If it’s a header that doesn’t have those, then yes, you’ll want to wrap them in
extern "C" {}.
ETA: It’s worth noting that many implementations will include the wrapper inside the .h file like below, so that you can get away with not doing it yourself.
#ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #endif
the macro __BEGIN_DECLS defined in /usr/include/sys/cdefs.h and used in many Linux system include files.
It is a good idea to let the compiler know so that it can expect C code when compiling as C++. You might also find that the header files themselves contain
extern "C" { as guards.
For example,
curses.h on my system contains:
#ifdef __cplusplus extern "C" { ...
I just double checked the stdlib.h for the GNU compiler and the declarations do not use extern “C” as declarations.
edit:
if defined __cplusplus && defined _GLIBCPP_USE_NAMESPACES define __BEGIN_NAMESPACE_STD namespace std {
So including the old headers will place declarations on std provided _GLIBCPP_USE_NAMESPACES is defined? | https://howtofusion.com/about-c-do-i-need-an-extern-c-block-to-include-standard-posix-c-headers.html | CC-MAIN-2022-40 | refinedweb | 597 | 68.16 |
27 January 2012 08:09 [Source: ICIS news]
SINGAPORE (ICIS)--Indian Oil Corp (IOC) has pushed back the closing date for its tender offer of two base oil cargoes, totalling up to 10,000 tonnes, by more than a week to 1 February, traders said on Friday.
The tender was supposed to close on 23 January, but participants were not able to submit bids because of the Lunar New Year holiday in ?xml:namespace>
The extended submission date will delay the delivery of the first cargo, comprising 2,000-2,500 tonnes of SN500, 1,500 tonnes of 150N and 1,000 tonnes of 500N base oils to 7-10 March from 22-25 February, previously.
The second cargo, which consists of 2,000-2,500 tonnes of SN150, 1,500 tonnes of 150N and 1,000 tonnes of 500N, is due for delivery on 14-17 March, traders said.
For more information on base | http://www.icis.com/Articles/2012/01/27/9527291/indian-oil-extends-tender-offer-for-10000t-base-oils-to-1-feb.html | CC-MAIN-2015-22 | refinedweb | 155 | 60.38 |
Part 11: Your Poetry is Served
This continues the introduction started here. You can find an index to the entire series here.
A Twisted Poetry Server
Now that we’ve learned so much about writing clients with Twisted, let’s turn around and re-implement our poetry server with Twisted too. And thanks to the generality of Twisted’s abstractions, it turns out we’ve already learned almost everything we need to know. Take a look at our Twisted poetry server located in twisted-server-1/fastpoetry.py. It’s called fastpoetry because this server sends the poetry as fast as possible, without any delays at all. Note there’s significantly less code than in the client!
Let’s take the pieces of the server one at a time. First, the
PoetryProtocol:
class PoetryProtocol(Protocol): def connectionMade(self): self.transport.write(self.factory.poem) self.transport.loseConnection()
Like the client, the server uses a separate
Protocol instance to manage each different connection (in this case, connections that clients make to the server). Here the
Protocol is implementing the server-side portion of our poetry protocol. Since our wire protocol is strictly one-way, the server’s
Protocol instance only needs to be concerned with sending data. If you recall, our wire protocol requires the server to start sending the poem immediately after the connection is made, so we implement the
connectionMade method, a callback that is invoked after a
Protocol instance is connected to a
Transport.
Our method tells the
Transport to do two things: send the entire text of the poem (
self.transport.write) and close the connection (
self.transport.loseConnection). Of course, both of those operations are asynchronous. So the call to
write() really means “eventually send all this data to the client” and the call to
loseConnection() really means “close this connection once all the data I’ve asked you to write has been written”.
As you can see, the
Protocol retrieves the text of the poem from the
Factory, so let’s look at that next:
class PoetryFactory(ServerFactory): protocol = PoetryProtocol def __init__(self, poem): self.poem = poem
Now that’s pretty darn simple. Our factory’s only real job, besides making
PoetryProtocol instances on demand, is storing the poem that each
PoetryProtocol sends to a client.
Notice that we are sub-classing
ServerFactory instead of
ClientFactory. Since our server is passively listening for connections instead of actively making them, we don’t need the extra methods
ClientFactory provides. How can we be sure of that? Because we are using the
listenTCP reactor method and the documentation for that method explains that the
factory argument should be an instance of
ServerFactory.
Here’s the
main function where we call
listenTCP:
def main(): options, poetry_file = parse_args() poem = open(poetry_file).read() factory = PoetryFactory(poem) from twisted.internet import reactor port = reactor.listenTCP(options.port or 0, factory, interface=options.iface) print 'Serving %s on %s.' % (poetry_file, port.getHost()) reactor.run()
It basically does three things:
- Read the text of the poem we are going to serve.
- Create a
PoetryFactorywith that poem.
- Use
listenTCPto tell Twisted to listen for connections on a port, and use our factory to make the protocol instances for each new connection.
After that, the only thing left to do is tell the
reactor to start running the loop. You can use any of our previous poetry clients (or just netcat) to test out the server.
Discussion
Recall Figure 8 and Figure 9 from Part 5. Those figures illustrated how a new
Protocol instance is created and initialized after Twisted makes a new connection on our behalf. It turns out the same mechanism is used when Twisted accepts a new incoming connection on a port we are listening on. That’s why both
connectTCP and
listenTCP require
factory arguments.
One thing we didn’t show in Figure 9 is that the
connectionMade callback is also called as part of
Protocol initialization. This happens no matter what, but we didn’t need to use it in the client code. And the
Protocol methods that we did use in the client aren’t used in the server’s implementation. So if we wanted to, we could make a shared library with a single
PoetryProtocol that works for both clients and servers. That’s actually the way things are typically done in Twisted itself. For example, the
NetstringReceiver
Protocol can both read and write netstrings from and to a
Transport.
We skipped writing a low-level version of our server, but let’s think about what sort of things are going on under the hood. First, calling
listenTCP tells Twisted to create a listening socket and add it to the event loop. An “event” on a listening socket doesn’t mean there is data to read; instead it means there is a client waiting to connect to us.
Twisted will automatically accept incoming connection requests, thus creating a new client socket that links the server directly to an individual client. That client socket is also added to the event loop, and Twisted creates a new
Transport and (via the
PoetryFactory) a new
PoetryProtocol instance to service that specific client. So the
Protocol instances are always connected to client sockets, never to the listening socket.
We can visualize all of this in Figure 26:
In the figure there are three clients currently connected to the poetry server. Each
Transport represents a single client socket, and the listening socket makes a total of four file descriptors for the select loop to monitor. When a client is disconnected the associated
Transport and
PoetryProtocol will be dereferenced and garbage-collected (assuming we haven’t stashed a reference to one of them somewhere, a practice we should avoid to prevent memory leaks). The
PoetryFactory, meanwhile, will stick around as long as we keep listening for new connections which, in our poetry server, is forever. Like the beauty of poetry. Or something. At any rate, Figure 26 certainly cuts a fine figure of a Figure, doesn’t it?
The client sockets and their associated Python objects won’t live very long if the poem we are serving is relatively short. But with a large poem and a really busy poetry server we could end up with hundreds or thousands of simultaneous clients. And that’s OK — Twisted has no built-in limits on the number of connections it can handle. Of course, as you increase the load on any server, at some point you will find it cannot keep up or some internal OS limit is reached. For highly-loaded servers, careful measurement and testing is the order of the day.
Twisted also imposes no limit on the number of ports we can listen on. In fact, a single Twisted process could listen on dozens of ports and provide a different service on each one (by using a different factory class for each
listenTCP call). And with careful design, whether you provide multiple services with a single Twisted process or several is a decision you could potentially even postpone to the deployment phase.
There’s a couple things our server is missing. First of all, it doesn’t generate any logs that might help us debug problems or analyze our network traffic. Furthermore, the server doesn’t run as a daemon, making it vulnerable to death by accidental Ctrl-C (or just logging out). We’ll fix both those problems in a future Part but first, in Part 12, we’ll write another server to perform poetry transformation.
Suggested Exercises
- Write an asynchronous poetry server without using Twisted, like we did for the client in Part 2. Note that listening sockets need to be monitored for reading and a “readable” listening socket means we can
accepta new client socket.
- Write a low-level asynchronous poetry server using Twisted, but without using
listenTCPor protocols, transports, and factories, like we did for the client in Part 4. So you’ll still be making your own sockets, but you can use the Twisted reactor instead of your own
selectloop.
- Make the high-level version of the Twisted poetry server a “slow server” by using
callLateror
LoopingCallto make multiple calls to
transport.write(). Add the --num-bytes and --delay command line options supported by the blocking server. Don’t forget to handle the case where the client disconnects before receiving the whole poem.
- Extend the high-level Twisted server so it can serve multiple poems (on different ports).
- What are some reasons to serve multiple services from the same Twisted process? What are some reasons not to?
21 thoughts on “Your Poetry is Served”
Good fresh part done! I like figure explaining connections to server 🙂
I still have questions 🙂
How does the Factory (or Reactor loop?) distinct between Protocols? Do they have names with client port number in it?
What if Protocol have things to do after client disconnect? Will be instance destroyed immediately after disconnect?
Thanks again for great tutorial for the rest of us!
Good questions!
In the server in Part 11, the factory does not distinguish between protocols, it just makes a new (identical) protocol for each new connection via
buildProtocol.
Each protocol is connected to a different Transport, but that happens outside of the factory. Note that
buildProtocolis passed the address of the incoming connection, so it could potentially take actions based on that information, but most of the time you want to do the same thing for every client no matter where they might be coming from.
Anyway, once the protocol has been created, it’s really in charge of the specific connection, not the factory.
When a connection is done, the associated protocol receives a
connectionLostcallback, where you can take any cleanup actions you need to.
Thanks! That is useful information!
“Like the client, the server uses a Protocol instance to manage connections (…)”
Shouldn’t that be “instances” instead of “instance”. Current wording suggests there’s one instance of Protocol handling all connections.
Good point, I updated the wording to make that clear.
Hi, Dave! Thank you for such interesting and useful articles! May you help me in one question? I wrote asynchronous non-twisted poetry server (as specified in the first exercise in part 11), this server you be can seen here:. I embarrassed lines 61-62: this is a blocking operations. If to this server connected 2 clients (you can use any of poetry clients, for example twisted-client-4/get-poetry.py) then download speed for each client cut in half (if to server connected 3 clients, then speed cut to 3 times). How do you recommend to replace this code, that it worked equally quickly regardless of the number of clients?
Hi Roman, you’re on the right track using a select loop. In addition, you need to:
1. Set the accepted sockets to be non-blocking.
2. Use send() instead of sendall(). Remember that send may not write all the bytes. It returns the number actually written.
3. Catch socket errors from send() with the EWOULDBLOCK code and ignore them (proceed to the next descriptor from select).
Make sense?
Thank you, Dave.
Hi Dave,
How would you test EWOULDBLOCK on the server in this case? I tried using time.sleep on my client to try but it didn’t trigger it. I’m guessing there is a buffer somewhere that is handling everything smoothly. Thanks for the tutorials.
Hey Phil, you are welcome! I think you’re right about the buffering. I’d try using a much larger amount of data to trigger that case.
Thanks. I did use a larger file and stopped the client from receiving data to trigger it. I did find some peculiar behavior that I think is Windows only. I’ve written about it below if anyone is interested. If anyone finds anything incorrect with what I’ve said, please let me know.
Initially, I was just curious how I would trigger a ‘WOULD BLOCK’ socket.error on a server send. To do this, I found the best way was to stop the client code from ever trying to read the data (i.e. from using recv()) so that the send buffer of the server would fill up (presumably requiring the receive buffer on the client to also fill up). A larger file than the poetry ones had to be used.
I found that on my system (using Windows 7), about 23.3KB worth of small send() commands would then cause a ‘EWOULDBLOCK’ error (presumably that fills both the receive and send buffers on the client and server respectively). However, I also found that I could send a very large file (1.5GB) in one send command() and the (non-blocking) send would return immediately, indicating that ALL the data was sent.
My memory increased by the same amount, though not attributed to any application. The client however would, for a long time afterwards, still indicate that it was receiving data even if the server was closed. The extra memory usage would only subside once the client was closed or the data was transferred. After ballooning to 1.5GB buffer size, if I tried to make another request from a different client, the server would only then trigger EWOULDBLOCK or something similar.
I found a description of why this was happening on some Microsoft support documentation
First, note that data goes to a send buffer SO_SNDBUF first before it actually gets in transit on the network. This buffer and the receive buffer (SO_RCVFUV) are managed by the OS. On Windows at least, a successful send() doesn’t actually mean that the data is now in transit on the network but instead means it has just arrived at the send buffer. The default Winsock (Windows Sockets API) buffer size is only 8K.
One would expected EWOULDBLOCK to occur if the send buffer is exceeded and would only stop when the buffer has free space. However, the Winsock send buffer can actually expand much larger (like 1.5GB in my case) in various circumstances.
So, what actually happened was that the whole 1.5GB file went into the send buffer which expanded to accommodate it. Winsock said success to the send() command but actually it was lying. It was hoarding the data in the send buffer.
In conclusion, Winsock lies.
Nice sleuthing 🙂
Hi,dave! Thank you for such nice tutorials!
would you please help in some questions?
1) Please imaging an application such as file-server: a client send a request like ‘get filename1’, the file server answer the request by returning content of filename1. the server is twisted-style, but as far as i know, reading a file from disk is time-consuming. when the server is transferring file to one client, it couldn’t answer requests from other client. How could I solve this problem? could I read a local file in asynchronous way or …?
2) could you please send me some small programs in twisted-style with GUI (or some links)? what confused me is that, twisted is a event circle running forever, and GUI is also a event circle, how to combine this two circle?I guess callback(using Deffered in twisted) should play a important role.
thank you very much! (I am not a english speaker,my written english is little bit bad (^^)
Hello, glad you like the tutorials!
Thank you very much
Hi Dave,
I’m having a lot of trouble figuring out how I can implement the second exercise. The part I am getting confused by is how to get the accept to work as part of the reactor. The client from Part 4 is very different from the server in this respect. Would I have accept() run in doRead? Thanks.
Hi Kevin, you’ll need to look at the Twisted reactor API. Look for the methods that allow you to add a new socket to the reactor.
Part 11 is at where 2048=2^11, which is undeniably cool!! | http://krondo.com/your-poetry-is-served/?replytocom=4540 | CC-MAIN-2020-10 | refinedweb | 2,663 | 64.51 |
Creating Document Themes with the Office Open XML Formats
Stephanie Krieger, arouet.net
September 2008
Applies to: Microsoft Office PowerPoint 2007, Microsoft Office Word 2007, Microsoft Office Excel 2007, and the Microsoft Office Open XML Formats. Also applies to Microsoft Office PowerPoint 2008 for Mac, Microsoft Office Word 2008 for Mac, and Microsoft Office Excel 2008 for Mac. (13 printed pages)
Summary: Explore the components of a document theme and examine both best practices and the Open XML necessary to create a complete theme from scratch.
Contents
-
The Construction of a Document Theme
Understanding .thmx Files
Walkthrough: theme1.xml file
Creating a Complete Theme
-
-
Overview
Document themes are one of the most important formatting capabilities in the history of Microsoft Office. What makes them so important and what do developers need to know in order to take advantage of the full value of this functionality? This article explains the elements of a theme, discusses what themes mean to users, and demonstrates what you need to know to create a complete custom theme.
Because you can create many elements of a theme from within Microsoft Office Word, Microsoft Office Excel, or Microsoft Office PowerPoint, and because usability and cohesiveness of the design are as important to themes as the quality of your code, this article looks at both the elements that users can create from within the PowerPoint user interface and the elements that Open XML developers require for creating custom themes.
The Construction of a Document Theme
A document theme is a set of fonts, colors, and graphic effects that you can apply to a Word, Excel, or PowerPoint document with one click. New content that you add to the document then automatically takes on the formatting of the applied theme.
It is important to understand that, whether or not the user applies theme formatting elements in a document, every Word 2007, Excel 2007, and PowerPoint 2007 document contains a theme. Theme colors, fonts, and effects are stored in the document in a document part named theme1.xml.
Additionally, when applied in PowerPoint, a theme includes the slide master, slide layouts, and background styles gallery settings. PowerPoint presentations and templates that use multiple slide masters contain a separate theme document part for each master. When this occurs, the additional parts are numbered consecutively using the naming convention theme#.xml.
Users can combine theme fonts, colors, and effects from different themes and save that combination as their own custom theme from within Word, Excel, or PowerPoint. They can also create and apply custom theme font and theme color sets from within programs in the 2007 Office system (and can create theme colors from within Microsoft Office PowerPoint 2008 for Mac). However, creating custom theme effects requires the use of the Open XML format. Compiling a set of theme files also requires some understanding of Open XML and the file format architecture.
Note that the same themes are available in Word, Excel, and PowerPoint. Whenever you save a theme to a global theme folder location (locations are provided later in this article), it is automatically available in all three programs.
Swapping Themes
One of the most important capabilities of themes is that the user can instantly swap out the applied theme. That is, when the user applies a new theme to a document, any theme fonts, colors, and effects already applied in the document (as well as backgrounds, layouts, and masters in a PowerPoint document) swap to take on the formatting of the new theme.
So, for example, if you apply a color from the Theme Colors palette, the document records the color palette position rather than the particular color. The specific color value that corresponds to that palette position for the active theme is stored in the theme#.xml part within the document. In the following code sample, notice that the XML value for the fill color of an OfficeArt object is the Accent 1 theme color palette position rather than a specific color value.
Note that, because the swapping capability of a theme is based on the user applying specific gallery positions, the user must apply formatting from the galleries for that formatting to swap. For example, if a user manually applies an RGB color value that exactly matches the active theme's Accent 1 RGB value, the color does not change when a new theme is applied. That is because the user has stored the specific color value in the relevant document part rather than the theme color position.
Purpose of a Theme
From one perspective, the benefit of themes is the ability to mix and match formatting options to easily create a custom look from a wide variety of choices.
However, if you are creating themes as part of a 2007 Office release solution for a company, the more likely scenario is that themes are used to apply the company's visual brand identity. (Visual brand identity (or branding) means, essentially, the approved design and appearance parameters for a company's printed and electronically published materials). One click to apply a theme and you get a coherent set of approved colors, fonts, and graphic effects. Then, it is just one more click to switch the document to the branding for a specific product or division. So, with themes, it is actually easier for the typical user to use the company's approved branding than not to use it. This is an extremely important benefit to larger enterprises in particular, where consistent adherence to the company's branding is often a significant marketing problem.
So, before building a theme, it is a good idea to have a clear picture of how you will use it. Then, you can more easily plan your theme and check theme elements as you complete them to ensure the desired user experience. The remaining topics in this section explain how the theme components work to help you create more effective themes.
Cross-Office Components
In Word and Excel, theme colors, theme fonts, and theme effects are accessible on the Page Layout tab. In PowerPoint, these same elements are accessible on the Design tab as well as the Master tabs (Slide Master, Handout Master, and Notes Master).
Although theme fonts, colors, and effects are part of the theme file for a complete theme (the .thmx file, examined later in this article), they are also typically saved as independent files so that they can appear in the galleries for the specific theme element, as shown in Figure 1.
Figure 1: The Themes group as shown on the Page Layout tab in Word 2007.
Providing galleries for specific theme elements enables the user to create their own combinations. These individual galleries are also useful for common corporate document production requirements, such as when the user needs one color scheme for printed documents and another for documents shared on-screen, while the rest of the theme remains the same.
Although the information about theme colors, fonts, and effects in the subheadings that follow may seem very user-oriented, it is essential information for anyone who is going to create a theme. By understanding how the choices you make manifest in Word, Excel, and PowerPoint when a user applies your theme, you can help to ensure a positive user experience with the themes you create.
Theme Colors
Theme colors are a set of 12 colors with specific purposes, as shown in Figure 2. The first ten colors are used to populate the Theme Colors palette, which is accessible anywhere a user can apply color throughout Word, Excel, and PowerPoint. The last two colors are not available in the color palette but are applied automatically as needed, when you add or open a hyperlink.
Figure 2: Theme colors as shown in the Create New Theme Colors dialog box.
The first four colors are used to populate the Background Styles gallery in PowerPoint, as shown later in this article. These colors also determine the font color applied to elements inserted into a PowerPoint presentation. For best practice, Light 1 and Light 2 should be clearly visible on Dark 1 and Dark 2.
The six accent colors are used to format OfficeArt graphics (shapes, SmartArt diagrams, and Excel charts) as well as for table styles in all three programs and WordArt in Excel and PowerPoint. Additionally, the Accent 1 color is the default color for shapes inserted into Excel and PowerPoint as well as for several built-in Word heading styles. For best practice, when possible, all six accent colors should be clearly visible on all Text\Background colors.
The ten colors discussed here populate the Theme Colors palette, shown in Figure 3. The top row of the palette consists of the four text/background colors followed by the six accent colors. The five subsequent rows are populated automatically with tints (for example, lighter variations) and shades (for example, darker variations) of the specified theme colors. These tints and shades are automatic, based on the original color, and cannot be programmatically altered:
For mid-range colors (commonly the accent colors), tints are 80%, 60%, and 40% lighter than the original, and shades are 25% and 50% darker than the original.
Very light colors (typically the light 2 text/background color) use shades of 10%, 25%, 50%, 75%, and 90%.
Very dark colors (typically the dark 2 text/background color) use tints of 90%, 75%, 50%, 25%, and 10%.
White, which is usually used for the Light 1 color position, uses shades of 5%, 15%, 25%, 35%, and 50%.
Black, which is usually used for the Dark 1 color position, uses tints of 50%, 35%, 25%, 15%, and 5%.
Figure 3: The Theme Colors palette
While you technically could set any color you like in any of the 12 theme color positions, remember that specific colors are used for specific purposes, such as populating graphic quick style galleries. A change such as substituting a dark brown for black where you specifically do not want black used anywhere in the theme is likely to work just fine. However, varying from the recommended best practices for visibility discussed earlier could adversely affect the user experience. For example, if you exclude white or black from the theme colors palette, the user will have to take extra steps to apply white or black anywhere in the document.
For best results, check behavior in all locations where a theme is used - such as by inserting a chart on a slide to check its default text color against the slide background or checking the various graphic quick style galleries for visibility of all objects.
Theme Fonts
Each theme includes a pair of theme fonts, comprised of a designated heading font and body font. For example, the body font is available by default to Excel worksheet cells, Word default text formatting, PowerPoint body text placeholders, and most text in charts and SmartArt graphics. Similarly, the designated heading font is automatically applied to PowerPoint title placeholders as well as some Word heading styles. Although you apply the heading font and body font to some types of content automatically, the user can apply either theme font to any content they choose.
Throughout the various galleries and settings where theme font references appear, you may see the theme fonts listed as FontName(Headings) or FontName(Body), or simply as +Headings or +Body, without the active theme's font name even indicated.
If only one editing language is enabled in Microsoft Office, you see only one pair of theme fonts. And, a theme only requires one pair of theme fonts. However, you can have a separate pair of theme fonts for languages using Latin text fonts, East Asian fonts, and complex script fonts. Additionally, you can specify scripts for particular languages.
Theme Effects
Theme effects are the primary theme element that puts a theme into the province of developers, because custom theme effects cannot be created from within Microsoft Office.
Theme effects include the fill, line, and effect formatting applied to OfficeArt graphics. And, although separated in the PowerPoint user interface, theme effects as written in the XML also include the Background Styles gallery settings for PowerPoint.
Theme effects are used to populate the following quick styles galleries:
SmartArt Styles
Chart Styles
Shape Styles (in PowerPoint and Excel only)
Table Styles (in PowerPoint only; top two rows of the gallery only)
When you create custom theme effects, you control what effects are stored in your theme. However, with the exception of the background styles gallery, the specified effects that populate specific gallery choices is intrinsic to Microsoft Office and cannot be altered programmatically. For this reason, it is important to check all applicable galleries after creating your theme effects, to confirm that no undesirable combinations are available to the user. Learn about how to create theme effects and how those effects translate to the galleries later in this article.
PowerPoint-Specific Components
In addition to being powerful formatting functionality you can use across Microsoft Office, themes are also the evolution of PowerPoint design templates. So, when applied in PowerPoint, a theme also includes the slide master, slide layouts, and slide backgrounds for the presentation.
Because slide layouts are customizable in PowerPoint 2007, multiple slide masters are required far less often. This is worth noting because, when your theme is applied to a presentation, every slide master will appear in the Themes gallery and Slide Layouts gallery as a separate theme stored in the file. You can apply different masters to different slides, as in earlier versions of PowerPoint. In PowerPoint 2007, when different masters are applied to specific slides in a presentation or template, the theme fonts, colors, and effects available on those slides are specific to the active slide master's theme.
Considerations for Cross-platform Themes
For those creating themes for use on both the 2007 Office system and Microsoft Office 2008 for Mac, note that themes are cross-platform functionality. That is, you can create a single theme for use on both platforms. When creating themes to use in Office 2008 for Mac, consider the following differences:
The 2007 release of Microsoft Office and Office 2008 for Mac have some differences in available fonts. For your theme to look correct on both platforms, confirm that the theme fonts you intend to include in your theme are available to both your Windows and Mac users.
Some types of shadows manifest differently in the 2007 Office system and Microsoft Office for Mac. To ensure desired results, check the shadows that you include in theme effects, as well as those you apply to objects on slide masters or layouts, on both platforms.
Not all picture file types work equally well on both platforms. However, both PNG and JPG files, which are the recommended image file types for use in themes, do work equally well on both platforms.
In addition to these design considerations, some slight differences in the way theme files are interpreted by the Office programs on the two platforms require checking some elements in the XML when finalizing your theme files. Those checks are explained in the last section of this article.
Understanding .thmx Files
When you explore the ZIP package contents of a .thmx file, as shown in Figure 4, you see the _rels and docProps folders and the [Content_Types].xml file, all of which you know from Open XML Format ZIP packages.
In the second level theme folder, you see the theme1.xml file (which contains the theme color, font, and effect settings for the theme), the themeManager.xml part (which contains just a namespace reference for the theme), the automatically generated thumbnail images for the themes galleries, and a _rels folder.
Figure 4: A .thmx ZIP package
The file themeThumbnail.jpeg is the image that appears in the Themes galleries in Word and Excel; auxiliaryThemeThumbnail.jpeg is the image that appears in the PowerPoint Themes gallery.
You can save a new .thmx file from Word, Excel, or PowerPoint, by using the Save Current Theme option at the bottom of the Themes gallery. When you do this, the set of currently applied theme elements (including your customizations to theme colors, theme fonts, and, if saving your theme from PowerPoint, to the slide master and layouts) is saved as a new theme (a new .thmx file).
The only file in the .thmx ZIP package that requires editing in the XML in order to customize some of its elements is the theme1.xml file.
When you save a new theme from Word or Excel, the slide masters, layouts, and background gallery settings included in the theme are those of the built-in Microsoft Office theme. When creating a complete custom theme, save the theme from PowerPoint to include your customizations to the master and layouts and to generate the thumbnail image for the PowerPoint Themes gallery (which is automatically generated based on the formatting of your theme's Title Slide layout).
Walkthrough: theme1.xml file
The theme1.xml file stores all of the elements of a theme that are applicable across Microsoft Office and the PowerPoint slide background gallery settings. This file contains sections for theme color, font, and effect settings, as shown in the following code sample with the XML markup collapsed for the built-in Paper theme.
Notice that you refer to the theme effects in the XML as the format scheme. In addition to theme effects, the background styles gallery settings are also included in the format scheme XML, and so developers generally consider them to be part of theme effects. However, it is worth noting that the background styles gallery is not treated as part of theme effects within the PowerPoint user interface. That is, if a user applies a different set of theme effects in their presentation but otherwise leaves the active theme intact, the background styles gallery settings do not change.
The following subsections discuss each of the sections of the theme1.xml file. First, however, it's important to mention the Open XML Theme Builder—a free tool created by members of the Microsoft Office product team that provides a user interface for generating all elements of a theme1.xml file.
The Open XML Theme Builder
You can download the Open XML Theme Builder tool from Microsoft Connect. Theme Builder can create a .thmx package, but essentially its purpose is to write the theme1.xml code for you. Using this tool saves you the time of manually writing the theme effects code and enables you to create robust and creative custom themes even if you don't know the XML structure well enough to write the code for the attributes you want to include.
In fact, using the Theme Builder to generate theme effects is an excellent way to learn the Open XML for document themes and much about the Open XML for OfficeArt formatting effects, because you select the attributes you want through the tool and can then read the resulting theme1.xml part that the tool generates from your choices.
Because the options in the Theme Builder map to the theme1.xml file, you will notice that some terminology in this tool differs from the terminology within the Office applications. This is true wherever the terminology in the XML differs from the terminology in the user interface of the Microsoft Office programs. For example, percent transparency for fill and line colors in Word, Excel, and PowerPoint is referred to as the Alpha attribute in the XML. Alpha is the opposite of transparency (i.e., the percent opacity).
Even if you are fluent in Open XML, using the Theme Builder tool is a tremendous timesaver. And, remember that you can always edit the theme1.xml file manually if needed. In fact, a few attributes that you can add to theme effects are not currently available in the tool, such as gradient line color and the miter or beveled line join styles. So, you may want to manually add those in your theme1.xml file after using the Theme Builder. (More information about those attributes is provided later in this article.)
The theme builder does not add a slide master, slide layouts, or thumbnail images to the .thmx package. So, if you start your theme by creating it in the Theme Builder, new presentations based on your theme use the Microsoft Office theme master and layout defaults until you add a slide master and slide layouts. Additionally, a red X appears in place of the thumbnails in the Themes galleries within Word, Excel, and PowerPoint. See Creating a Complete Theme for a recommended best practice process to follow when creating a custom theme from scratch.
Theme Colors
Tags in the theme1.xml markup shown across the next several code samples use the letter a as a prefix, indicating OfficeArt elements.
Looking at the following code sample, notice that the tags for the theme color scheme follow what you see in the Create New Theme Colors dialog box within Word, Excel, and PowerPoint. That is, the tags represent the two pairs of dark and light text\background colors, the six accent colors, and the two hyperlink colors.
>
RGB color values stored in a theme color set are stored as hexidecimal values. To edit color values directly in the theme1.xml part, convert the RGB decimal values to hexadecimal values. There are several ways to do this easily. From within Microsoft Office programs, you can either use the DEC2HEX function in Excel or the hex function in Microsoft Visual Basic for Applications (VBA). When displayed as hex values, the red, green, and blue values for an RGB value are shown in order with no breaks between them.
For example, the color RGB(128,198,100) is expressed in hexadecimal values as 80C664. The hexadecimal value for 128 is 80, the hexadecimal value for 198 is C6, and the hexadecimal value for 100 is 64. Any zero value is expressed as 00 in hexadecimal format, as each hexadecimal value uses two characters.
In the preceding code sample, the dark 1 and light 1 color positions use Windows system colors (the a:sysClr tag instead of the a:srgbClr tag). This is standard for the built-in Office 2007 themes, but it is not a requirement for those color palette positions.
Theme Fonts
Theme fonts must contain one heading and one body font (referred to in the XML markup as major and minor fonts, respectively). The theme font scheme shown in the following code sample is from a US-English installation of Office 2007. For this reason, the font pair identified is for Latin typeface.
If you are creating a theme for users who work in East Asian or complex script languages, add font pairs for those typefaces in the a:ea and a:cs tags. You can include up to three font pairs in your theme fonts but only one pair is required. Note that, even if you add three pairs of fonts, only those font pairs that apply to enabled editing languages appear in Word, Excel, and PowerPoint.
Additionally, you can indicate font scripts to be applied when a user is editing in a specific language, as shown in the following code sample. If a user applies your theme in a language for which you have not specific a font pair or a script, system default fonts are used.
<a:fontScheme <a:majorFont> <a:latin <a:ea <a:cs :majorFont> <a:minorFont> <a:latin <a:ea <a:cs <a:font… … </a:minorFont> </a:fontScheme>
Theme Effects
Theme effects, also referred to as the format scheme (the information within the a:fmtScheme tag, as shown in the fill style code sample that follows), include fill, line, and effect formatting, as well as settings for the Background Styles gallery in PowerPoint.
To create the fill styles, line styles, and effect styles for your theme, specify three sets of options for each, corresponding to subtle, moderate, and intense variations.
Fill Styles
The following code shows the markup for the fill style list in the built-in theme named Paper. In this example, the subtle fill style is a simple solid fill; both the moderate and intense fill styles are image fills (denoted by the a:blipfill tag). You can use images used for fill styles and background styles and are most often used to provide the appearance of a texture.
<a:fmtScheme <a:fillStyleLst> <a:solidFill> <a:schemeClr </a:solidFill> <a:blipFill> <a:blip r: <a:duotone> <a:schemeClr <a:shade <a:tint </a:schemeClr> <a:schemeClr <a:tint <a:satMod </a:schemeClr> </a:duotone> </a:blip> <a:tile </a:blipFill> <a:blipFill> <a:blip r: <a:duotone> <a:schemeClr <a:shade </a:schemeClr> <a:schemeClr <a:tint </a:schemeClr> </a:duotone> </a:blip> <a:tile </a:blipFill> </a:fillStyleLst>
Figure 5 shows an example of the Paper theme effects employed in a SmartArt diagram. Notice that the image fill provides a texture that works across the theme colors. You can see the markup for the fill color in the preceding code sample. Recoloring an image fill is done using duotone recoloring (two variations on the same color that contrast to resolve the detail of the image). Nested inside the a:duotone tags that are shown in the fill style markup, you see the following:
The scheme color value is set to placeholder color (the value phClr). This value appears throughout the fill, line, effect, and background styles and indicates that the settings are applied to the theme color applicable for a given style. This allows the same fill, line, and effect styles to populate across the theme colors that appear in the OfficeArt galleries.
Two settings are required for the duotone recoloring. For each, you can apply tints (lighter variations of a color), shades(darker variations of a color), and alpha (percent opacity), as well as hue, saturation, and luminosity. Example of the markup for tint, shade, and saturation are shown in the preceding code example.
Use the a:tile tag shown in the sample markup to tile an image, so that it repeats as needed throughout the fill of an OfficeArt object.
Notice that the numeric values shown in this markup are percent multiplied by 10,000. So, for example, both the moderate and intense fill styles are tiled at 40% height (the sy attribute) and 40% width (the sx attribute).
Figure 5: A SmartArt diagram in the Paper theme
More common than image fills, however, are gradient fills. The following code sample shows an example of the markup for a gradient fill style. Similar to the image fill styles, gradient fill styles use the placeholder color value in order to enable the theme effects to be applied across all applicable theme colors.
The sample gradient shown is the moderate fill style from a theme named Moonlight, which is available for download from Office Online Templates. This is a three-stop, rectangular gradient. Each gradient stop (a:gs tag) can use the same color modification parameters as shown earlier for the image fills, including tint, shade, alpha, hue, saturation, and luminosity.
<a:gradFill <a:gsLst> <a:gs <a:schemeClr <a:tint <a:satMod </a:schemeClr> </a:gs> <a:gs <a:schemeClr <a:tint <a:satMod </a:schemeClr> </a:gs> <a:gs <a:schemeClr <a:tint <a:satMod </a:schemeClr> </a:gs> </a:gsLst> <a:path <a:fillToRect </a:path> </a:gradFill>
Line Styles
The markup shown in the following code sample is for a typical line style list. Notice that there are three line styles indicated (corresponding to subtle, moderate, and intense), each of which is indicated with the a:ln tag.
The line style tag includes attributes for the cap type (style for the end of the line), the compound type (such as single line, shown here), and the alignment of the line relative to the object border.
Nested within each line style tag is the line's fill style information (solid fill in each of the three styles shown in this example). Line fill can use the same color modification properties noted previously for object fill styles, including tint, shade, alpha, hue, saturation, and luminosity.
The a:prstDash tag indicates the dash type; solid in the three styles shown in this markup.
<a:lnStyleLst> <a:ln <a:solidFill> <a:schemeClr <a:tint <a:satMod </a:schemeClr> </a:solidFill> <a:prstDash </a:ln> <a:ln <a:solidFill> <a:schemeClr <a:tint </a:schemeClr> </a:solidFill> <a:prstDash </a:ln> <a:ln <a:solidFill> <a:schemeClr <a:tint </a:schemeClr> </a:solidFill> <a:prstDash </a:ln> </a:lnStyleLst>
You can customize all of the settings shown in the preceding markup through the Open XML Theme Builder. Two settings not currently available through that tool, as noted earlier, are the line join type and gradient line fills.
The line join type defaults to round, meaning that lines are gently rounded at the corners of objects. To specify miter (square edge) or bevel (flat edge) corners, add the <a:miter /> or <a:bevel /> tag to the line style.
An example of the markup for a gradient line fill is shown in the following code sample. The gradient stops for line fills use the same format as the gradient fills shown earlier. This example is from the Wildflowers theme, available for download from Office Online Templates.
<a:ln <a:gradFill> <a:gsLst> <a:gs <a:schemeClr </a:gs> <a:gs <a:schemeClr <a:lumMod <a:lumOff </a:schemeClr> </a:gs> <a:gs <a:schemeClr <a:lumMod <a:lumOff </a:schemeClr> </a:gs> </a:gsLst> <a:lin </a:gradFill> <a:prstDash </a:ln>
Effect Styles
Effect styles can include inner and outer shadows, reflection, glow, soft edges, bevel, and 3-D rotation. The markup shown in the next code sample includes the following settings:
The subtle effect style includes only a white inner shadow.
The moderate effect style includes a larger white inner shadow as well as a reflection.
The intense effect style includes the same reflection as the moderate style as well as a 3-D bevel with a custom surface finish (translucent powder) and custom lighting.
<a:effectStyleLst> <a:effectStyle> <a:effectLst> <a:innerShdw <a:srgbClr <a:alpha </a:srgbClr> </a:innerShdw> </a:effectLst> </a:effectStyle> <a:effectStyle> <a:effectLst> <a:innerShdw <a:srgbClr <a:alpha </a:srgbClr> </a:innerShdw> <a:reflection </a:effectLst> </a:effectStyle> <a:effectStyle> <a:effectLst> <a:reflection </a:effectLst> <a:scene3d> <a:camera <a:rot </a:camera> <a:lightRig <a:rot </a:lightRig> </a:scene3d> <a:sp3d <a:bevelT </a:sp3d> </a:effectStyle> </a:effectStyleLst>
Understanding Background Styles
Background style options are very similar to the fill style options shown earlier. However, unlike the fill, line, and effect styles for object formatting, the subtle, moderate, and intense background styles you specify do translate exactly to individual entries in the Background Styles gallery.
Each of the three background styles is recolored across the four text\background colors for the theme, creating the twelve background styles gallery positions. The first row of the gallery shows the subtle background style, the second shows the moderate background style, and the third shows the intense background style.
The markup shown in the following code sample is a bit unusual for a background style gallery. As is typical for backgrounds, the subtle style is a simple solid fill and the moderate and intense are gradient fills. However, what is unique here is that some of the gradient stops are specific colors (that is, they will not change for different gallery positions) and some are placeholder colors that are able to change across the given row of the background styles gallery.
Notice that the value phClr is used for placeholder color, but that the accent 5 color (accent5) and the srgbClr color value D8D8D8 (RGB(216,216,216)) are used for some stops. In this theme, the specific colors are used to effect the appearance of sunlight and the placeholder color is used for the balance of the background to provide options across the background styles gallery entries.
If you are designing a complex background gradient, you may want to apply your gradient in PowerPoint, so that you can adjust it and see the results on screen as you do. Then, copy the markup from the PowerPoint slide to which you apply the background and paste it into your theme1.xml file. If you do this, however, be sure to replace gradient stop color values with the phClr value as applicable, to provide options in the background styles gallery.
<a:bgFillStyleLst> <a:solidFill> <a:schemeClr </a:solidFill> <a:gradFill <a:gsLst> <a:gs <a:schemeClr <a:gsLst> <a:gs <a:schemeClr val="accent:bgFillStyleLst>
As with fill styles, background styles can also use image fills, and most often do this to provide texture. The following code sample shows the markup for a typical image-based background style (the moderate background style from the built-in Paper theme) with duotone recoloring applied.
<a:blipFill> <a:blip r: <a:duotone> <a:schemeClr <a:shade <a:alpha </a:schemeClr> <a:schemeClr <a:tint <a:shade <a:satMod <a:alpha </a:schemeClr> </a:duotone> </a:blip> <a:tile </a:blipFill>
Creating a Complete Theme
The following is the best practice process that I recommend when using the PowerPoint user interface along with the Theme Builder to create your custom theme. Note that you may choose to vary this order based on which theme elements most drive the design for your particular theme. For example, if the slide backgrounds are a substantial part of your design, you may want to create the Background Styles gallery settings in the Theme Builder before customizing your slide master.
To create your own custom theme
Start your theme in a new, blank PowerPoint presentation. Create your custom theme fonts and theme colors using the options available from the respective galleries on the Design tab. Then customize the slide master (other than the slide backgrounds, which you can apply after creating the Background Styles gallery settings) and the slide layouts. Once you have the bulk of customizations done for the master and layouts, save the theme (to do this from within PowerPoint, on the Design tab, in the Themes group, click to expand the Themes gallery and then click Save Current Theme).
Why this suggested order?
Font selections affect the size, layout, and formatting of placeholders and other content on the slide master and layouts, because fonts can still differ greatly in size at the same point size. For example, text formatted using Arial 12 point is larger than the same text formatted using Times New Roman 12 point.
The colors you apply affect the appearance of content you add to the masters and layouts, and so you can better ensure that your master is adhering to the intended design.
Placing all global design elements on the slide master has long been a best practice for making PowerPoint documents more efficient to create and to use. Because slide layouts can now be individually customized, using the slide master is even more important for efficient creation and ease of use. Also remember that you can select Hide Background Graphics on the Slide Master tab for any layout that should not show elements from the master. This enables you to use the master for content that will be on most, but not all, layouts.
Having the bulk of the design customization for the master and layouts in place before creating theme effects helps you to test how well your theme effect settings work in as close an environment as possible to what the user encounters.
Open the theme in the Open XML Theme Builder and add the fill, line, effect, and background gallery settings that comprise the format scheme in theme1.xml (that is, the Theme Effects and Background Styles gallery settings). You can also adjust theme colors and theme fonts if needed while the theme is open in Theme Builder.
Then use the toolbox icon on the Theme Builder toolbar to test the theme in PowerPoint. Theme Builder generates a test file that shows you how the Shape Styles gallery will look with your selected theme effects and creates one slide with each layout that is currently available in the theme. Apply the appropriate entry(ies) from the Background Styles gallery to the master or layouts as needed and then review the Shape Styles to confirm desired effects.
Insert a SmartArt graphic, an Excel chart, and a PowerPoint table onto slides in the sample presentation so that you can check their respective Quick Style galleries for appearance and behavior.
After you finish the work you need to do in the Theme Builder, you can open the .thmx ZIP package to make any further customizations needed to the theme1.xml file, such as adding formatting attributes to theme effects that are not available in Theme Builder or copying font scripts from another theme. Do not add theme effect attributes to theme1.xml that are not available in Theme Builder until after you finish using the Theme Builder tool. Otherwise, you may experience an error when trying to save your edited theme in Theme Builder.
Double-click your .thmx file to create a new presentation from your theme. If you manually created any slide backgrounds and then copied them to the gallery, confirm that the background styles attached to your master and layouts are selected from the Background Styles gallery as appropriate. Then, resave the theme from PowerPoint to generate the finalized thumbnail images.
Finalizing your Theme
After you complete and test your .thmx file, you have a few steps remaining to finalize your theme.
Check the theme1.xml markup to ensure consistent naming of the theme elements. This is particularly important when your theme is intended for use in Office 2008 for Mac. The theme elements galleries in the 2007 Office system list theme elements by their file name. However, in Office 2008 for Mac, theme elements are listed in the gallery by the name provided in the XML markup.
When you double-click the theme file to create a new presentation, insert one of each type of slide layout. Then, apply a new theme. If elements are left behind on the master or any layout (other than any custom layouts that don't exist in the newly-applied theme), edit the XML to correct this behavior. Objects may be left behind because of the userDrawn attribute that tells PowerPoint the object was added by the user and should not be removed. This functionality is appropriate in a presentation if, for example, a user inserts a logo on a slide master. However, in themes, it can be problematic if the user needs to switch between themes. To correct the issue, search the XML document part for the slide master and each slide layout to locate and delete any instances of the userDrawn="1". Delete only the text shown here in bold for the userDrawn attribute- not the tag in which the attribute resides.
If you want to have the theme colors, fonts, and effects separately available in each of their respective galleries, create the separate color, font, and effect files, as follows:
Copy the color scheme and font scheme markup into separate XML files to create the theme colors and theme font files. If you are not sure of the structure required, copy an existing theme colors or theme fonts file from one of the built-in themes and paste in the correct markup for your theme. Be sure that the name you indicate in the XML markup matches the file name. Also note that, because these files are named the same and have the same file extension, you must store them in separate folders.
Make a copy of the .thmx file and open its ZIP package. In the top-level theme folder, delete the slideMasters, slideLayouts, and _rels folders. Then, change the file extension to .eftx to create the theme effects file. The reason to delete those folders is simply that the masters and layouts typically contain the bulk of the file size and they are not needed for the .eftx (theme effects) file. The _rels folder at that level contains a .rels file for the slide master, so if you remove the slideMasters folder, you must remove it as well.
When you finished checking the XML, testing the theme in PowerPoint, and creating your theme files, your theme is complete. To save your theme so that it appears in the themes galleries, do one of the following:
For the theme to appear in the custom themes category, save the theme and its respective parts to the set of folders located in one of the following locations:
Windows Vista:C:\Users\[username]\AppData\Roaming\Microsoft\Templates\Document Themes
Windows XP: C:\Documents and Settings\[username]\Application Data\Microsoft\Templates\Document Themes
Mac operating system: The user's My Themes folder.
For the theme to appear in the built-in themes category, save the files to one of the following locations:
Windows Vista or Windows XP: C:\Program Files\Microsoft Office\Document Themes 12
Mac OS: Applications\Microsoft Office 2008\Office\Media\Templates\Office Themes
About the Author
Stephanie Krieger is a professional document consultant, Microsoft Office System MVP, and the author of two books, Advanced Microsoft Office Documents 2007 Edition Inside Out and Microsoft Office Document Designer. Stephanie has extensive experience working with document themes, including building 30 of the themes provided in Office 2008 for Mac and designing and building more than a dozen of the themes available for download from Office Online. Additionally, she wrote the Microsoft Themes SDK, which is available from the Help menu of the Open XML Theme Builder. You can reach Stephanie through her blog, arouet.net.
Additional Resources
For more information, see the following resources:
For Open XML Format basics: | http://msdn.microsoft.com/en-us/library/cc964302.aspx | CC-MAIN-2013-20 | refinedweb | 6,974 | 57.5 |
Aaron Gallagher wrote ..
> I'm getting a slough of bizarre problems on one of my Apache servers,
> and everything is perfect on the other. The version is the same, and
> most of the configuration is the same. Namely, I'm trying to figure
> out why mod_python will sometimes randomly send headers twice.
>
> I'm running mod_python handlers in three different locations, and it
> seems like it'll randomly decide to run out of another location
> rather than where the request is asking for. I mean, the top sys.path
> entry in mod_python should always be the directory of the nearest
> handler, right?
No. It is a known problem with mod_python that the order of directories in
sys.path can be random. As a result, if you use the same module name in
different handler directories, you can get strange things happening, more so if
you are using the worker MPM on UNIX. See:
for a full list of module importer problems.
> The server that doesn't have any URL rewriting done never has any
> problems whatsoever, but the one that does is the one with these
> bizarre problems. I've compared configuration files, and they're both
> almost exactly the same. I can't find any major thing that's
> different between the two other than the rewriting. I'm using
> mod_rewrite to have a dynamic virtual host map. and can post the
> rules and conditions if necessary.
By all means post that part of your configuration which is relevant, but also
state which version of mod_python you are using. Also make it clear whether you
have different parts of the URL namespace with their own PythonHandler
directives and whether you have separated them if possible by tagging them
against different Python interpreter instances using PythonInterpreter
directive or otherwise.
Graham | http://modpython.org/pipermail/mod_python/2006-October/022328.html | CC-MAIN-2017-51 | refinedweb | 300 | 63.7 |
Evaluation¶
To convert overlap among predicted and ground truth bounding boxes into measures of accuracy and precision, the most common approach is to compare the overlap using the intersection-over-union metric (IoU). IoU is the ratio between the area of the overlap between the predicted polygon box and the ground truth polygon box divided by and the area of the combined bounding box region.
Let’s start by getting some sample data and predictions
from deepforest import evaluate from deepforest import main from deepforest import get_data from deepforest import visualize import os import pandas as pd m = main.deepforest() m.use_release() csv_file = get_data("OSBS_029.csv") predictions = m.predict_file(csv_file=csv_file, root_dir=os.path.dirname(csv_file)) predictions.head() xmin ymin xmax ymax label score image_path 0 330.0 342.0 373.0 391.0 Tree 0.802979 OSBS_029.tif 1 216.0 206.0 248.0 242.0 Tree 0.778803 OSBS_029.tif 2 325.0 44.0 363.0 82.0 Tree 0.751573 OSBS_029.tif 3 261.0 238.0 296.0 276.0 Tree 0.748605 OSBS_029.tif 4 173.0 0.0 229.0 33.0 Tree 0.738209 OSBS_029.tif
ground_truth = pd.read_csv(csv_file) ground_truth.head() image_path xmin ymin xmax ymax label 0 OSBS_029.tif 203 67 227 90 Tree 1 OSBS_029.tif 256 99 288 140 Tree 2 OSBS_029.tif 166 253 225 304 Tree 3 OSBS_029.tif 365 2 400 27 Tree 4 OSBS_029.tif 312 13 349 47 Tree
visualize.plot_prediction_dataframe(predictions, ground_truth, root_dir = os.path.dirname(csv_file))
The IoU metric ranges between 0 (no overlap) to 1 (perfect overlap). In the wider computer vision literature, the conventional threshold value for overlap is 0.5, but this value is arbitrary and does not ultimately relate to any particular ecological question. We considered boxes which have an IoU score of greater than 0.4 as true positive, and scores less than 0.4 as false negatives. The 0.4 value was chosen based on visual evaluation of the threshold that indicated a good visual match between the predicted and observed crown. We tested a range of overlap thresholds from 0.3 (less overlap among matching crowns) to 0.6 (more overlap among matching crowns) and found that 0.4 balanced a rigorous cutoff without spuriously removing trees that would be useful for downstream analysis.
After computing the IoU for the ground truth data, we get the resulting dataframe.
result = evaluate.evaluate_image(predictions=predictions, ground_df=ground_truth, show_plot=True, root_dir=os.path.dirname(csv_file), savedir=None) result.head() prediction_id truth_id IoU predicted_label true_label 90 90 0 0.059406 Tree Tree 65 65 1 0.335366 Tree Tree 17 17 2 0.578551 Tree Tree 50 50 3 0.532902 Tree Tree 34 34 4 0.595862 Tree Tree
Where prediction_id is a unique ID to each predicted tree box. truth is a unique ID to each ground truth box. The predicted and true labels are tree in this, case but could generalize to multi-class problems. From here we can calculate precision and recall at a given IoU metric.
result["match"] = result.IoU > 0.4 true_positive = sum(result["match"]) recall = true_positive / result.shape[0] precision = true_positive / predictions.shape[0] recall 0.819672131147541 precision 0.5494505494505495
This can be stated as 81.97% of the ground truth boxes are correctly matched to a predicted box at IoU threshold of 0.4, and 54.94% of predicted boxes match a ground truth box. Optimally we want a model that is both precise and accurate.
The above logic is wrapped into the evaluate.evaluate() function
result = evaluate.evaluate(predictions=predictions, ground_df=ground_truth,root_dir=os.path.dirname(csv_file), savedir=None)
This is a dictionary with keys
result.keys() dict_keys(['results', 'box_precision', 'box_recall', 'class_recall'])
The added class_recall dataframe is mostly relevant for multi-class problems, in which the recall and precision per class is given.
result["class_recall"] label recall precision size 0 Tree 1.0 0.67033 61
One important decision was how to average precision and recall across multiple images. Two reasonable options might be to take all predictions and all ground truth and compute the statistic on the entire dataset. This strategy makes more sense for evaluation data that are relatively homogenous across images. We prefer to take the average of per-image precision and recall. This helps balanace the dataset if some images have many trees, and other have few trees, such as when you are comparing multiple habitat types. Users are welcome to calculate their own statistics directly from the results dataframe.
result["results"].head() prediction_id truth_id IoU ... true_label image_path match 90 90 0 0.059406 ... Tree OSBS_029.tif False 65 65 1 0.335366 ... Tree OSBS_029.tif False 17 17 2 0.578551 ... Tree OSBS_029.tif True 50 50 3 0.532902 ... Tree OSBS_029.tif True 34 34 4 0.595862 ... Tree OSBS_029.tif True
Evaluating tiles¶
The evaluation method uses deepforest.predict_image for each of the paths supplied in the image_path column. This means that the entire image is passed for prediction. This will not work for large images. The deepforest.predict_tile method does a couple things under hood that need to be repeated for evaluation.
psuedo_code:
output_annotations = deepforest.preprocess.split_raster( path_to_raster = <path>, annotations_file = <original_annotation_path>, base_dir = <location to save crops> patch_size = <size of each crop> ) output_annotations.to_csv("new_annotations.csv") results = model.evaluate( csv_file="new_annotations.csv", root_dir=<base_dir from above> ) | https://deepforest.readthedocs.io/en/latest/Evaluation.html | CC-MAIN-2022-33 | refinedweb | 895 | 53.47 |
from __future__ import print_function # For py 2.7 compat
The widget framework is built on top of the Comm framework (short for communication). The Comm framework is a framework that allows you send/receive JSON messages to/from the front-end (as seen below).
To create a custom widget, you need to define the widget both in the back-end and in the front-end.
To get started, you'll create a simple hello world widget. Later you'll build on this foundation to make more complex widgets.
To define a widget, you must inherit from the Widget or DOMWidget base class. If you intend for your widget to be displayed in the IPython notebook, you'll.
Inheriting from the DOMWidget does not tell the widget framework what front-end widget to associate with your back-end widget. Instead, you must tell it yourself by defining a specially named Traitlet,
_view_name (as seen below).
from IPython.html import widgets from traitlets import Unicode class HelloWidget(widgets.DOMWidget): _view_name = Unicode('HelloView', sync=True) front-end. Without
sync=True, the front-end would have no knowledge of
_view_name.
Unicode, used for _view_name, is not the only Traitlet type, there are many more some of which are listed below:
Not all of these traitlets can be synchronized across the network, only the JSON-able traits and Widget instances will be synchronized..
You first need to import the
widget and
manager modules. You will use the manager later to register your view by name (the same name you used in the back-end). To import the modules, use the
require method of require.js (as seen below).
%%javascript require(["widgets/js/widget", "widgets/js/manager"], function(widget, manager){ });
Next define your widget view class. Inherit from the
DOMWidgetView by using the
.extend method. Register the view class with the widget manager by calling
.register_widget_view. The first parameter is the widget view name (
_view_name that you defined earlier in Python) and the second is a handle to the class type.
%%javascript require(["widgets/js/widget", "widgets/js/manager"], function(widget, manager){ // Define the HelloView var HelloView = widget.DOMWidgetView.extend({ }); // Register the HelloView with the widget manager. manager.WidgetManager.register_widget_view('HelloView', HelloView); });
%%javascript require(["widgets/js/widget", "widgets/js/manager"], function(widget, manager){ var HelloView = widget.DOMWidgetView.extend({ // Render the view. render: function(){ this.$el.text('Hello World!'); }, }); manager.WidgetManager.register_widget_view('HelloView', HelloView); });
You should be able to display your widget just like any other widget now.
HelloWidget().
class HelloWidget(widgets.DOMWidget): _view_name = Unicode('HelloView', sync=True) value = Unicode('Hello World!', sync=True)
To access the model associate a
on method which allows you to listen to events triggered by the model (like value changes).
By replacing the string literal with a call to
model.get, the view will now display the value of the back-end upon display. However, it will not update itself to a new value when the value changes.
%%javascript require(["widgets/js/widget", "widgets/js/manager"], function(widget, manager){ var HelloView = widget.DOMWidgetView.extend({ render: function(){ this.$el.text(this.model.get('value')); }, }); manager.WidgetManager.register_widget_view('HelloView', HelloView); });).
%%javascript require(["widgets/js/widget", "widgets/js/manager"], function(widget, manager){ var HelloView = widget.DOMWidgetView.extend({ render: function(){ this.value_changed(); this.model.on('change:value', this.value_changed, this); }, value_changed: function() { this.$el.text(this.model.get('value')); }, }); manager.WidgetManager.register_widget_view('HelloView', HelloView); });
w = HelloWidget() w
w.value = 'test'
The examples above dump the value directly into the DOM. There is no way for you to interact with this dumped data in the front-end. To create an example that accepts input, you will have to do something more than blindly dumping the contents of value into the DOM. In this part of the tutorial, you will use a jQuery spinner to display and accept input in the front-end. IPython currently lacks a spinner implementation so this widget will be unique.
You will need to change the type of the value traitlet to
Int. It also makes sense to change the name of the widget to something more appropriate, like
SpinnerWidget.
from traitlets import CInt class SpinnerWidget(widgets.DOMWidget): _view_name = Unicode('SpinnerView', sync=True) value = CInt(0, sync=True)
The jQuery docs for the spinner control say to use
.spinner to create a spinner in an element. Calling
.spinner on
$el will create a spinner inside
$el. Make sure to update the widget name here too so it's the same as
_view_name in the back-end.
%%javascript require(["widgets/js/widget", "widgets/js/manager"], function(widget, manager){ var SpinnerView = widget.DOMWidgetView.extend({ render: function(){ // jQuery code to create a spinner and append it to $el this.$input = $('<input />'); this.$el.append(this.$input); this.$spinner = this.$input.spinner({ change: function( event, ui ) {} }); this.value_changed(); this.model.on('change:value', this.value_changed, this); }, value_changed: function() { }, }); manager.WidgetManager.register_widget_view('SpinnerView', SpinnerView); });
To set the value of the spinner on update from the back-end, you need to use jQuery's
spinner API.
spinner.spinner('value', new) will set the value of the spinner. Add that code to the
value_changed method to make the spinner update with the value stored in the back-end((. Using jQuery's spinner API, you can add a function to handle the spinner
change event by passing it in when constructing the spinner. Inside the
change event, call
model.set to set the value and then
touch to inform the framework that this view was the view that caused the change to the model. Note: The
var that = this; is a JavaScript trick to pass the current context into closures.**
%%javascript require(["widgets/js/widget", "widgets/js/manager"], function(widget, manager){ var SpinnerView = widget.DOMWidgetView.extend({ render: function(){ var that = this; this.$input = $('<input />'); this.$el.append(this.$input); this.$spinner = this.$input.spinner({ change: function( event, ui ) { that.handle_spin(); }, spin: function( event, ui ) { that.handle_spin(); } }); this.value_changed(); this.model.on('change:value', this.value_changed, this); }, value_changed: function() { this.$spinner.spinner('value', this.model.get('value')); }, handle_spin: function() { this.model.set('value', this.$spinner.spinner('value')); this.touch(); }, }); manager.WidgetManager.register_widget_view('SpinnerView', SpinnerView); });
w = SpinnerWidget(value=5) w
w.value
w.value = 20
Trying to use the spinner with another widget.
from IPython.display import display w1 = SpinnerWidget(value=0) w2 = widgets.IntSlider() display(w1,w2) from traitlets import link mylink = link((w1, 'value'), (w2, 'value')) | http://nbviewer.jupyter.org/github/ipython/ipython/blob/4.0.x/examples/Interactive%20Widgets/Custom%20Widget%20-%20Hello%20World.ipynb | CC-MAIN-2017-51 | refinedweb | 1,056 | 51.24 |
change the priority of a process
#include <sys/sched.h> int sched_setparam( pid_t pid, struct sched_param *param );
The sched_setparam() function changes the priority of process pid (or the calling process if pid is zero) to that of the sched_priority member in the sched_param structure pointed to by param.
The sched_priority member must lie between the minimum and maximum values defined in <sys/sched.h>.
By default, the process priority and scheduling algorithm are inherited from or explicitly set by the parent process. Once running, the child process may change its priority using this function.
The sched_setparam() function returns zero on success. On error, a -1 is returned, and errno is set.
POSIX 1003.4
errno, getprio(), qnx_scheduler(), sched_getparam(), sched_getscheduler(), sched_setscheduler(), sched_yield(), setprio() | https://users.pja.edu.pl/~jms/qnx/help/watcom/clibref/qnx/sched_setparam.html | CC-MAIN-2022-33 | refinedweb | 122 | 56.66 |
Example 6.2
shows a fancier version of our simple applet.
As you can see from
Figure 6.2 ,
we've made the graphical display more interesting. This
applet also does all of its drawing in the paint()
method. It demonstrates the use of Font and
Color objects.
This example also introduces the init() method,
which is used, typically in place of a constructor, to
perform any one-time initialization that is necessary when
the applet is first created. The paint() method may
be invoked many times in the life of an applet, so this
example uses init() to create the Font
object that paint() uses.
import java.applet.*;
import java.awt.*;
public class SecondApplet extends Applet {
static final String message = "Hello World";
private Font font;
// One-time initialization for the applet
// Note: no constructor defined.
public void init() {
font = new Font("Helvetica", Font.BOLD, 48);
}
// Draw the applet whenever necessary. Do some fancy graphics.
public void paint(Graphics g) {
// The pink oval
g.setColor(Color.pink);
g.fillOval(10, 10, 330, 100);
// The red outline. Java doesn't support wide lines, so we
// try to simulate a 4-pixel wide line by drawing four ovals.
g.setColor(Color.red);
g.drawOval(10, 10, 330, 100);
g.drawOval(9, 9, 332, 102);
g.drawOval(8, 8, 334, 104);
g.drawOval(7, 7, 336, 106);
// The text
g.setColor(Color.black);
g.setFont(font);
g.drawString(message, 40, 75);
}
} | https://docstore.mik.ua/orelly/java/javanut/ch06_03.htm | CC-MAIN-2019-26 | refinedweb | 238 | 60.61 |
c++ compile error
I have this class for double linked lists:
template <typename T> class Akeraios { struct node { T data; node* prev; node* next; node(T t, node* p, node* n) : data(t), prev(p), next(n) {} }; node* head; node* tail; public: Akeraios() : head( NULL ), tail ( NULL ) {} template<int N> Akeraios( T (&arr) [N]) : head( NULL ), tail ( NULL ) //meta apo : simainei einai initializer list--arxikopoiisi listas { for( int i(0); i != N; ++i) push_back(arr[i]); } bool empty() const { return ( !head || !tail ); } operator bool() const { return !empty(); } void push_back(T); void push_front(T); T pop_back(); T pop_front(); ~Akeraios() { while(head) { node* temp(head); head=head->next; delete temp; } } };
and somewhere in main
int arr[num1len]; int i=1; Akeraios <int> dlist ( arr );//error line!! for(i=1;i<=num1len;i++){ double digit; int div=10; int j; for(j=1;j<=i;j++)div=div*div; digit=number1/div; int dig=(int) digit;
the error in error line is:
no matching function for call to `Akeraios::Akeraios(int[((unsigned int)((int)num1len))])'
candidates are: Akeraios::Akeraios(const Akeraios&)
note Akeraios::Akeraios() [with T = int]
Answers
This code is perfectly valid and compliant as-is. The only way I can see it messing up is if you had a compiler extension for VLAs and attempted to call the constructor with a variable-length array, which would almost certainly fail. Otherwise, it is perfectly legitimate. Visual Studio accepts without quarrel.
try this:
Akeraios <int>* dlist = new Akeraios( arr );
your compiler thinks you're calling a function doing it the way you do it.
you could also use the implicit constructor
Akeraios<int> dlist = arr;
(not very nice this is)
Since you're saying that num1len is a variable:
Templates are evaluated at compile-time. When you say arr[num1len], you're specifying an array with a variable length (is this C99 or something?). The template expects an array with a size that can be evaluated at compile time (you're saying template<int N>Akeraios( T (&arr) [N]), so there's no way the compiler can match that up.
Just imagine you had a specialization for N=5 or N=10. How would the compiler be able to find the right specialization when compiling the code if the size of the array is not known at that point?
Need Your Help
struct as 208 bits long variable
c struct bit-manipulationI am trying to make a struct that could hold 208 bytes bits. My intentions are using every 3 bits of variables to store 68 values each between 0 and 4.
Want to invoke a base class using a generic with 'this' of child class
c# .net generics inheritance base-classSo my problem is that I want to remove nulls for all my strings in complex objects like POCOs and DTOs. I can do this but the method I am doing it seems like it could be better. So I figured some... | http://unixresources.net/faq/4340250.shtml | CC-MAIN-2019-13 | refinedweb | 490 | 66.47 |
symbols
A collection of
Symbol objects for standard component properties and
methods. These let mixins and a component internally communicate without
exposing these properties and methods in the component's public API. They
also help avoid unintentional name collisions, as a component developer must
specifically import the
symbols module and reference one of its symbols.
To use these
Symbol objects in your own component, include this module and
then create a property or method whose key is the desired Symbol. E.g.,
ShadowTemplateMixin expects a component to define
a property called symbols.template:
import ShadowTemplateMixin from 'elix/src/ShadowTemplateMixin.js'; import * as symbols from 'elix/src/symbols.js'; class MyElement extends ShadowTemplateMixin(HTMLElement) { [symbols.template]() { return `Hello, <em>world</em>.`; } }
The above use of
symbols.
While this project generally uses
Symbol objects to hide component
internals, Elix does make some exceptions for methods or properties that are
very helpful to have handy during debugging. E.g.,
ReactiveMixin exposes its setState
method publicly, even though invoking that method from outside a component is
generally bad practice. The mixin exposes
setState because it's very useful
to have access to that in a debug console.
API
canGoLeft property
Symbol for the
canGoLeft property.
A component can implement this property to indicate that the user is currently able to move to the left.
Type:
boolean
canGoRight property
Symbol for the
canGoRight property.
A component can implement this property to indicate that the user is currently able to move to the right.
Type:
boolean
click() method
Symbol for the
click method.
This method is invoked when an element receives an operation that should
be interpreted as a click. ClickSelectionMixin
invokes this when the element receives a
mousedown event, for example.
contentSlot property.
Type:
HTMLSlotElement
defaultFocus constant
Symbol for the
defaultFocus property.
This is used by the defaultFocus utility to determine the default focus target for an element.
elementsWithTransitions constant
Symbol for the
elementsWithTransitions property.
TransitionEffectMixin inspects this property to determine which element(s) have CSS transitions applied to them for visual effects.
getItemText() method.
Returns:
string the text of the item
goDown() method
Symbol for the
goDown method.
This method is invoked when the user wants to go/navigate down.
goEnd() method
Symbol for the
goEnd method.
This method is invoked when the user wants to go/navigate to the end (e.g., of a list).
goLeft() method
Symbol for the
goLeft method.
This method is invoked when the user wants to go/navigate left. Mixins that make use of this method include KeyboardDirectionMixin and SwipeDirectionMixin.
goRight() method
Symbol for the
goRight method.
This method is invoked when the user wants to go/navigate right. Mixins that make use of this method include KeyboardDirectionMixin and SwipeDirectionMixin.
goStart() method
Symbol for the
goStart method.
This method is invoked when the user wants to go/navigate to the start (e.g., of a list).
goUp() method
Symbol for the
goUp method.
This method is invoked when the user wants to go/navigate up.
hasDynamicTemplate constant
Symbol for the
hasDynamicTemplate property.
If your component class does not always use the same template, define a
static class property getter with this symbol and have it return
true.
This will disable template caching for your component.
keydown() method
Symbol for the
keydown method.
This method is invoked when an element receives a
keydown event.
An implementation of
symbols
symbols.keydown is that the last mixin
applied wins. That is, if an implementation of
symbols.keydown did
handle the event, it can return immediately. If it did not, it should
invoke
super to let implementations further up the prototype chain have
their chance.
This method takes a
KeyboardEvent parameter that contains the event being
processed.
mouseenter() method.
mouseleave() method.
raiseChangeEvents property[symbols.raiseChangeEvents] = true; // Do work here, possibly setting properties, like: this.foo = 'Hello'; this[symbols.raiseChangeEvents] = false; });
Elsewhere, property setters that raise change events should only do so it
this property is
true:
set foo(value) { // Save foo value here, do any other work. if (this[symbols.
Type:
boolean
render() method
Symbol for an internal
render method.
ReactiveMixin has a public render
method that can be invoked to force the component to render. That public
method internally invokes an
symbols.render method, which a component can
implement to actually render itself.
You can implement a
symbols.render method if necessary, but the most
common way for Elix components to render themselves is to use
RenderUpdatesMixin,
ShadowTemplateMixin, and/or
ContentItemsMixin, all of which provide a
symbols.render method.
rendering property
Symbol for the
rendering property.
ReactiveMixin sets this property to true during rendering, at other times it will be false.
Type:
boolean
rightToLeft property
Symbol for the
rightToLeft property.
LanguageDirectionMixin sets this to true if the
if the element is rendered right-to-left (the element has or inherits a
dir attribute with the value
rtl).
This property wraps the internal state member
state.languageDirection,
and is true if that member equals the string "rtl".
Type:
boolean
scrollTarget property
Symbol for the
scrollTarget property.
This property indicates which element in a component's shadow subtree should be scrolled. SelectionInViewMixin can use this property to determine which element should be scrolled to keep the selected item in view.
Type:
Element
startEffect() method
Symbol for the
startEffect method.
A component using TransitionEffectMixin can invoke this method to trigger the application of a named, asynchronous CSS transition effect.
This method takes a single
string parameter giving the name of the effect
to start.
swipeLeft() method
Symbol for the
swipeLeft method.
The swipe mixins TouchSwipeMixin and TrackpadSwipeMixin invoke this method when the user finishes a gesture to swipe left.
swipeRight() method
Symbol for the
swipeLeft method.
The swipe mixins TouchSwipeMixin and TrackpadSwipeMixin invoke this method when the user finishes a gesture to swipe left.
swipeTarget property.
Type:
HTMLElement
template constant
Symbol for the
template method.
ShadowTemplateMixin uses this property to obtain a component's template, which it will clone into a component's shadow root. | https://component.kitchen/elix/symbols | CC-MAIN-2018-30 | refinedweb | 991 | 50.63 |
DEBSOURCES
Skip Quicknav
sources / git / 1:2.20.1-2+deb10u3 / notes
#ifndef NOTES_H
#define NOTES_H
#include "string-list.h"
struct object_id;
struct strbuf;
/*
* Function type for combining two notes annotating the same object.
*
* When adding a new note annotating the same object as an existing note, it is
* up to the caller to decide how to combine the two notes. The decision is
* made by passing in a function of the following form. The function accepts
* two object_ids -- of the existing note and the new note, respectively. The
* function then combines the notes in whatever way it sees fit, and writes the
* resulting oid into the first argument (cur_oid). A non-zero return
* value indicates failure.
*
* The two given object_ids shall both be non-NULL and different from each
* other. Either of them (but not both) may be == null_oid, which indicates an
* empty/non-existent note. If the resulting oid (cur_oid) is == null_oid,
* the note will be removed from the notes tree.
*
* The default combine_notes function (you get this when passing NULL) is
* combine_notes_concatenate(), which appends the contents of the new note to
* the contents of the existing note.
*/
typedef int (*combine_notes_fn)(struct object_id *cur_oid,
const struct object_id *new_oid);
/* Common notes combinators */
int combine_notes_concatenate(struct object_id *cur_oid,
const struct object_id *new_oid);
int combine_notes_overwrite(struct object_id *cur_oid,
const struct object_id *new_oid);
int combine_notes_ignore(struct object_id *cur_oid,
const struct object_id *new_oid);
int combine_notes_cat_sort_uniq(struct object_id *cur_oid,
const struct object_id *new_oid);
/*
* Notes tree object
*
* Encapsulates the internal notes tree structure associated with a notes ref.
* Whenever a struct notes_tree pointer is required below, you may pass NULL in
* order to use the default/internal notes tree. E.g. you only need to pass a
* non-NULL value if you need to refer to several different notes trees
* simultaneously.
*/
extern struct notes_tree {
struct int_node *root;
struct non_note *first_non_note, *prev_non_note;
char *ref;
char *update_ref;
combine_notes_fn combine_notes;
int initialized;
int dirty;
} default_notes_tree;
/*
* Return the default notes ref.
*
* The default notes ref is the notes ref that is used when notes_ref == NULL
* is passed to init_notes().
*
* This the first of the following to be defined:
* 1. The '--ref' option to 'git notes', if given
* 2. The $GIT_NOTES_REF environment variable, if set
* 3. The value of the core.notesRef config variable, if set
* 4. GIT_NOTES_DEFAULT_REF (i.e. "refs/notes/commits")
*/
const char *default_notes_ref(void);
/*
* Flags controlling behaviour of notes tree initialization
*
* Default behaviour is to initialize the notes tree from the tree object
* specified by the given (or default) notes ref.
*/
#define NOTES_INIT_EMPTY 1
/*
* By default, the notes tree is only readable, and the notes ref can be
* any treeish. The notes tree can however be made writable with this flag,
* in which case only strict ref names can be used.
*/
#define NOTES_INIT_WRITABLE 2
/*
* Initialize the given notes_tree with the notes tree structure at the given
* ref. If given ref is NULL, the value of the $GIT_NOTES_REF environment
* variable is used, and if that is missing, the default notes ref is used
* ("refs/notes/commits").
*
* If you need to re-initialize a notes_tree structure (e.g. when switching from
* one notes ref to another), you must first de-initialize the notes_tree
* structure by calling free_notes(struct notes_tree *).
*
* If you pass t == NULL, the default internal notes_tree will be initialized.
*
* The combine_notes function that is passed becomes the default combine_notes
* function for the given notes_tree. If NULL is passed, the default
* combine_notes function is combine_notes_concatenate().
*
* Precondition: The notes_tree structure is zeroed (this can be achieved with
* memset(t, 0, sizeof(struct notes_tree)))
*/
void init_notes(struct notes_tree *t, const char *notes_ref,
combine_notes_fn combine_notes, int flags);
/*
* Add the given note object to the given notes_tree structure
*
* If there already exists a note for the given object_sha1, the given
* combine_notes function is invoked to break the tie. If not given (i.e.
* combine_notes == NULL), the default combine_notes function for the given
* notes_tree is used.
*
* Passing note_sha1 == null_sha1 indicates the addition of an
* empty/non-existent note. This is a (potentially expensive) no-op unless
* there already exists a note for the given object_sha1, AND combining that
* note with the empty note (using the given combine_notes function) results
* in a new/changed note.
*
* Returns zero on success; non-zero means combine_notes failed.
*
* IMPORTANT: The changes made by add_note() to the given notes_tree structure
* are not persistent until a subsequent call to write_notes_tree() returns
* zero.
*/
int add_note(struct notes_tree *t, const struct object_id *object_oid,
const struct object_id *note_oid, combine_notes_fn combine_notes);
/*
* Remove the given note object from the given notes_tree structure
*
* IMPORTANT: The changes made by remove_note() to the given notes_tree
* structure are not persistent until a subsequent call to write_notes_tree()
* returns zero.
*
* Return 0 if a note was removed; 1 if there was no note to remove.
*/
int remove_note(struct notes_tree *t, const unsigned char *object_sha1);
/*
* Get the note object SHA1 containing the note data for the given object
*
* Return NULL if the given object has no notes.
*/
const struct object_id *get_note(struct notes_tree *t,
const struct object_id *object_oid);
/*
* Copy a note from one object to another in the given notes_tree.
*
* Returns 1 if the to_obj already has a note and 'force' is false. Otherwise,
* returns non-zero if 'force' is true, but the given combine_notes function
* failed to combine from_obj's note with to_obj's existing note.
* Returns zero on success.
*
* IMPORTANT: The changes made by copy_note() to the given notes_tree structure
* are not persistent until a subsequent call to write_notes_tree() returns
* zero.
*/
int copy_note(struct notes_tree *t,
const struct object_id *from_obj, const struct object_id *to_obj,
int force, combine_notes_fn combine_notes);
/*
* Flags controlling behaviour of for_each_note()
*
* Default behaviour of for_each_note() is to traverse every single note object
* in the given notes tree, unpacking subtree entries along the way.
* The following flags can be used to alter the default behaviour:
*
* - DONT_UNPACK_SUBTREES causes for_each_note() NOT to unpack and recurse into
* subtree entries while traversing the notes tree. This causes notes within
* those subtrees NOT to be passed to the callback. Use this flag if you
* don't want to traverse _all_ notes, but only want to traverse the parts
* of the notes tree that have already been unpacked (this includes at least
* all notes that have been added/changed).
*
* - YIELD_SUBTREES causes any subtree entries that are encountered to be
* passed to the callback, before recursing into them. Subtree entries are
* not note objects, but represent intermediate directories in the notes
* tree. When passed to the callback, subtree entries will have a trailing
* slash in their path, which the callback may use to differentiate between
* note entries and subtree entries. Note that already-unpacked subtree
* entries are not part of the notes tree, and will therefore not be yielded.
* If this flag is used together with DONT_UNPACK_SUBTREES, for_each_note()
* will yield the subtree entry, but not recurse into it.
*/
#define FOR_EACH_NOTE_DONT_UNPACK_SUBTREES 1
#define FOR_EACH_NOTE_YIELD_SUBTREES 2
/*
* Invoke the specified callback function for each note in the given notes_tree
*
* If the callback returns nonzero, the note walk is aborted, and the return
* value from the callback is returned from for_each_note(). Hence, a zero
* return value from for_each_note() indicates that all notes were walked
* successfully.
*
* IMPORTANT: The callback function is NOT allowed to change the notes tree.
* In other words, the following functions can NOT be invoked (on the current
* notes tree) from within the callback:
* - add_note()
* - remove_note()
* - copy_note()
* - free_notes()
*/
typedef int each_note_fn(const struct object_id *object_oid,
const struct object_id *note_oid, char *note_path,
void *cb_data);
int for_each_note(struct notes_tree *t, int flags, each_note_fn fn,
void *cb_data);
/*
* Write the given notes_tree structure to the object database
*
* Creates a new tree object encapsulating the current state of the given
* notes_tree, and stores its object id into the 'result' argument.
*
* Returns zero on success, non-zero on failure.
*
* IMPORTANT: Changes made to the given notes_tree are not persistent until
* this function has returned zero. Please also remember to create a
* corresponding commit object, and update the appropriate notes ref.
*/
int write_notes_tree(struct notes_tree *t, struct object_id *result);
/* Flags controlling the operation of prune */
#define NOTES_PRUNE_VERBOSE 1
#define NOTES_PRUNE_DRYRUN 2
/*
* Remove all notes annotating non-existing objects from the given notes tree
*
* All notes in the given notes_tree that are associated with objects that no
* longer exist in the database, are removed from the notes tree.
*
* IMPORTANT: The changes made by prune_notes() to the given notes_tree
* structure are not persistent until a subsequent call to write_notes_tree()
* returns zero.
*/
void prune_notes(struct notes_tree *t, int flags);
/*
* Free (and de-initialize) the given notes_tree structure
*
* IMPORTANT: Changes made to the given notes_tree since the last, successful
* call to write_notes_tree() will be lost.
*/
void free_notes(struct notes_tree *t);
struct string_list;
struct display_notes_opt {
int use_default_notes;
struct string_list extra_notes_refs;
};
/*
* Load the notes machinery for displaying several notes trees.
*
* If 'opt' is not NULL, then it specifies additional settings for the
* displaying:
*
* - suppress_default_notes indicates that the notes from
* core.notesRef and notes.displayRef should not be loaded.
*
* - extra_notes_refs may contain a list of globs (in the same style
* as notes.displayRef) where notes should be loaded from.
*/
void init_display_notes(struct display_notes_opt *opt);
/*
* Append notes for the given 'object_sha1' from all trees set up by
* init_display_notes() to 'sb'. The 'flags' are a bitwise
* combination of
*
* - NOTES_SHOW_HEADER: add a 'Notes (refname):' header
*
* - NOTES_INDENT: indent the notes by 4 places
*
* You *must* call init_display_notes() before using this function.
*/
void format_display_notes(const struct object_id *object_oid,
struct strbuf *sb, const char *output_encoding, int raw);
/*
* Load the notes tree from each ref listed in 'refs'. The output is
* an array of notes_tree*, terminated by a NULL.
*/
struct notes_tree **load_notes_trees(struct string_list *refs, int flags);
/*
* Add all refs that match 'glob' to the 'list'.
*/
void string_list_add_refs_by_glob(struct string_list *list, const char *glob);
/*
* Add all refs from a colon-separated glob list 'globs' to the end of
* 'list'. Empty components are ignored. This helper is used to
* parse GIT_NOTES_DISPLAY_REF style environment variables.
*/
void string_list_add_refs_from_colon_sep(struct string_list *list,
const char *globs);
/* Expand inplace a note ref like "foo" or "notes/foo" into "refs/notes/foo" */
void expand_notes_ref(struct strbuf *sb);
/*
* Similar to expand_notes_ref, but will check whether the ref can be located
* via get_sha1 first, and only falls back to expand_notes_ref in the case
* where get_sha1 fails.
*/
void expand_loose_notes_ref(struct strbuf *sb);
#endif | https://sources.debian.org/src/git/1:2.20.1-2+deb10u3/notes.h/ | CC-MAIN-2020-50 | refinedweb | 1,684 | 59.94 |
Webots - MoveIt! Controlling two UR5e Robots
Hi, I want to contrloll two ur5e arms with Moveit over Webots. My goal is to give them an endeffector pose and they go to that position. It works for one! My problem is to controll more than one. I want to have one launch file which starts a move_group node and a webots node for each robot im adding. I tried to follow the Gazebo tutorial and i wanted to use the "<group>" command but then move_group wouldnt subscribe to my webots_joint-publisher. I think its because my Webots node isnt in the same namespace but i couldnt figure out how to change the namespace in my webots-python script.
Seeing as Webots is not a very commonly used simulator with ROS, I would expect you'll have a higher chance of getting a response if you'd use a more appropriate venue, such as the Webots support forum or their issue tracker.
Thanks for your answer! My first attempt was to ask the webots forum but they couldnt help with the problem. Thats why im here. I hoped that someone tried to use Webots with moveIt and knows how to controll multiple robots with it. | https://answers.ros.org/question/345150/webots-moveit-controlling-two-ur5e-robots/ | CC-MAIN-2020-16 | refinedweb | 203 | 71.55 |
This is your resource to discuss support topics with your peers, and learn from each other.
11-25-2012 04:27 PM
Hi,
I'm new to Cascaded with previous experience in MeeGo Qt/QML development. Currently I'm trying to port few apps to BlackBerry 10 platform with is great, but having lots of difficulties due to the fact that Cascades uses modified version of QML. Would it be possible to keep this thread for all of MeeGo developers who struggle as me with simple things in Cascades? Thank you in advance.
My first question is very simple, how do I pragmatically scroll to an item in ListView? I did read the documentation, and also used google, but got no answer. I know there is a method scrollToItem, but I cannot figure it out what should I pass to indexPath argument. Tried using simple index (int value that specifies the index of the item in the list) but without any success. Here is the code that misses arguments for scrollToItem method:
import bb.cascades 1.0 Container { layout: StackLayout {} ListView { id: valueSelector; verticalAlignment: VerticalAlignment.Fill; horizontalAlignment: HorizontalAlignment.Fill; dataModel: ArrayDataModel { id: arrayModel; } } onCreationCompleted: { for (var i=0; i<100; i++) arrayModel.append (i); valueSelector.scrollToItem (); } }
Thank you in advance for your help
12-18-2012 02:52 AM
let me connect this thread :
this could be adapted w/ meego components , what do you think ?
12-18-2012 04:34 AM
rzr, thank you for your reply. I already used Symbian components on PlayBook and they work perfectly (at least those I used). My problem was Cascades that are not very similar to QML/QML components at all, despite the fact that both use the same engine. On MeeGo/Symbian we use QML components that are designed for corresponding platform and standard QML objects like ListView. What would be beneficial for MeeGo/Symbian Qt developers is to have some sort of mapping scheme from "standard" QML elements to Cascades.
I know that one can use standard Qt/QML on BB10 but then we loose the beauty of the platform and its capabilities, since QtGui (that is used by standard QML viewer) and Cascades cannot be mixed in one project
12-18-2012 12:45 PM
12-19-2012 06:27 AM
afaik indexpath is just array (variant list)
you can try
ScrollToItem([0, n], ScrollAnimation.Default); // for scroll to item header 1 and item index nth
12-19-2012 07:27 AM
we use <your model name here>.scrollToItem(<your index path here>)
12-19-2012 08:11 AM
Model? Oh, I'll try this method.
Thank you all for your helpful replies
12-19-2012 08:16 AM
Sorry, I wrote model but meant list view
12-19-2012 08:24 AM
I see
12-20-2012 07:22 PM
any feedback on :-
As suggested : | http://supportforums.blackberry.com/t5/Native-Development/Cascades-for-MeeGo-developers/m-p/2046807 | CC-MAIN-2015-27 | refinedweb | 476 | 62.68 |
Aspose.Newsletter: Load Plain Text (TXT) Files into Aspose.Words (0 messages)
Aspose publishes December 2008 Newsletter for .NET & Java programmers by highlighting the newly supported features by Aspose.Spell, Aspose.Pdf for Reporting Services, Aspose.Cells for Reporting Services, Aspose.BarCode, Aspose.Words, Aspose.Pdf, Aspose.Slides for Reporting Services, Aspose.Pdf.Kit, Aspose.Cells, Aspose.Network and Aspose.BarCode for Reporting Services. We will also provide information about migrating your code for MS Office Automation to Aspose using Aspose.Words. You will learn about the latest news from Aspose along with the monthly Tech-Tip, which demonstrates how to load plain text files into Aspose.Words and an introduction to our featured technical article which shows you how to create PDF/A-1 with Aspose.Pdf. In addition to this, we will introduce the latest tutorial video from Aspose, which shows you how to generate barcodes in WPF windows applications using Aspose.BarCode for WPF framework. Product Spotlight. Take the time to download the free evaluation version today to see how Aspose.Spell can work for you. Inline HTML and Bookmarks supported by Aspose.Pdf for Reporting Services The latest version 1.4.0.0 of Aspose.Pdf for Reporting Services now supports bookmarks and inline HTML with Textbox. In this release the positioning algorithm has been optimized, which reduces the nested level of table and improves the performance of rendering. The rendering engine has also been modified to improve rendering speed. Numerous other bug fixes and improvements are also included in this version. For more information you can view the official release page and the relevant blog post. The latest version of Aspose.Pdf for Reporting Services can be downloaded from here. Integrate Aspose.Cells for Reporting Services with Report Viewer in Local Mode Aspose.Cells for Reporting Services version 1.3.0.0 has been released. The new release allows developers to integrate Aspose.Cells for Reporting Services with Report Viewer control in local mode. We have also enhanced standard RDL support. Now Aspose.Cells for Reporting Services can render RDL reports just as the built-in Excel renderer does and also supports additional RDL elements like nested tables. In addition to improved support for 64bit OS, this release also includes numerous other bug fixes. For detailed information you are requested to view the official release page and accompanying blog post. The latest version of Aspose.Cells for Reporting Services can be downloaded from here. Aspose.BarCode for WPF Released The latest release of Aspose.BarCode for .NET version 2.9.0.0 introduces a new barcode control, Aspose.BarCode for WPF (Windows Presentation Foundation). Aspose.BarCode for WPF is a .NET component which generates high quality vector-based barcode images for WPF applications. Aspose.BarCode for WPF supports most of the popular barcode standards (Linear (1D), Postal & 2D barcode) and is fully compatible with Microsoft Visual Studio 2008, providing rich design-time support. In addition to this, there are numerous other bug fixes and improvements included in this release. For more information, please consult the official release page and the relevant blog post. The latest version of Aspose.BarCode for .NET can be downloaded from here. Load Microsoft Office 2007 Open XML (DOCX) documents with Aspose.Words for Java Aspose.Words for Java version 2.6.0.0 has been released. One of the earlier releases introduced the ability to save documents in the Microsoft Word 2007 DOCX format. This release makes it possible to load DOCX files. Now you can open, generate, save and convert DOCX documents. This makes Aspose.Words for Java the first document processing Java library on the market that provides such capabilities. For more information, you are requested to view the official release page and the accompanying blog post. The latest version of Aspose.Words for Java can be downloaded from here. PDF/A fully supported by Aspose.Pdf for .NET The latest version 3.9.0.0 of Aspose.Pdf for .NET offers complete support for PDF/A which includes both PDF/A-1a and PDF/A-1b. This release also includes support for Widows/Orphans control. Users can easily allow/disallow Widows/Orphans by turning on/off Widows/Orphans control. In addition to this, the macro #$UNICODE() is also supported which can be used in both Heading and Text. We have included support for Direct-to-stream mode as well. Also in this release, it is possible to adjust fonts automatically. Now the proper font is automatically selected according to the contents of the Segment paragraph. There are numerous other bug fixes and improvements incorporated into this release. For more details, please consult the official release page and the relevant blog post. The latest version of Aspose.Pdf for .NET can be downloaded from here. Improvements in Aspose.Slides for Reporting Services Aspose.Slides for Reporting Services version 2.1.1.0 has been released. In this release the latest stable version of Aspose.Slides for .NET has been merged. There are numerous bug fixes which include the proper rendering of Bold, Italic and Underlined fonts, more accurate rendering of table and matrix cells and borders, as well as the size of a slide is now equal to the page size in a report. For more details please consult the official release page and the accompanying blog post. The latest version of Aspose.Slides for Reporting Services can be downloaded from here. Improved Headers and Footers with Aspose.Pdf for Java The latest version 2.4.0.0 of Aspose.Pdf for Java has been released. In this release, a lot of important features about Section, Text, Table and Image have been improved to enable developers to use them more conveniently and effectively. HeaderFooter class has been rewritten to give developers more flexibility and control, while at the same time promoting conformance to the .NET Framework. The new release also supports various page, table, header and footer borders, allows getting the width and height of images, and supports most replaceable symbols in Text. Also included in this release are numerous bug fixes and enhancements. For more information please consult the official release page and the relevant blog post. The latest version of Aspose.Pdf for Java can be downloaded from here. Replacing and Deleting Images from PDF Document with Aspose.Pdf.Kit for .NET Aspose.Pdf.Kit for .NET version 3.3.0.0 has been released. This release supports the new features of replacing and deleting images from a PDF document. You also have the option of editing comments (annotations), removing digital signature, supporting multi-line text in both AcroForm and XfaForm. In addition to this, some new features have been added to enhance editing capabilities. The performance of PdfFileEditor and PdfConverter has been optimized and the Exception Handling mechanism has been improved for better usability. Many other improvements and bug fixes have also been incorporated into this release. For more details please consult the official release page and the accompanying blog post. The latest version of Aspose.Pdf.Kit for .NET can be downloaded from here. Enhanced support for Excel 2007 in Aspose.Cells for Java The latest version 2.0.0.0 of Aspose.Cells for Java now offers enhanced support for Excel 2007 file format. You can now easily read and write Excel2007 XLSM, XLTX, XLTM files, manipulate charts in Excel97-2003 template files and process drawing objects such as Shapes, Charts, etc. in Excel2007 format. In addition to this, you can now set outline border for a range, read OleObject from template file, insert AVI file as OleObject and copy Macros when copying Workbook. Images in xls2pdf and new Excel formula functions (MROUND, FDIST, and NEGBINOMDIST) have also been supported in this release. You will also find many other enhancements and bug fixes incorporated into this release. For more information please consult the official release page and the relevant blog post. The latest version of Aspose.Cells for Java can be downloaded from here. Aspose.iCalendar for .NET merged with Aspose.Network for .NET Aspose.Network for .NET version 4.3.0.0 has been released. The product Aspose.iCalendar has been merged into Aspose.Network from this release. All of the classes of Aspose.iCalendar are placed under the same namespace without changes. The existing Aspose.iCalendar customers do not need to change legacy code for this change; they only need to add reference to the new Aspose.Network.dll. For more details about the merge please consult our policy page. This release also allows you to set the MessageFlags for Outlook Message files, decode S/MIME Outlook Message files and offers enhanced FtpClient performance by using asynchronous socket programming technology. The FileDrop Control has also been merged into Aspose.Network.dll. In addition to this, numerous other enhancements and bug fixes have been incorporated into this release. For more details please consult the official release page and the accompanying blog post. The latest version of Aspose.Network for .NET can be downloaded from here. Application Identifiers (AI) for EAN128 supported by Aspose.BarCode for Reporting Services The latest version 1.7.0.0 of Aspose.BarCode for Reporting Services now supports International Standard of Application Identifiers (AI) for EAN128. This release also allows rendering barcode images to report header. The support for SQL Server 2000 Reporting Services has been enhanced and the configuration tool to support SQL Server 2000 Reporting Services configuration has been upgraded. For more details please consult the official release page and the accompanying blog post. The latest version of Aspose.BarCode for Reporting Services can be downloaded from here. Migration from Microsoft Office Automation to Aspose – Aspose.Words In this month's newsletter we include information for migrating to Aspose.Words your Microsoft Office Automation code to change page setup (e.g. paper size, orientation, margins etc) in an existing document. You can find the detailed article with complete code here. Technical Article – How to create PDF/A-1 with Aspose.Pdf The PDF/A formats specified in the ISO 19005 standard strive to provide a consistent and robust subset of PDF, which can safely be archived for a long period of time, or it can be used for reliable data exchange in enterprise and government environments. This article demonstrates how you can create PDF/A-1 with Aspose.Pdf. Tutorial Video – Generating barcodes in WPF Applications This video tutorial demonstrates how to generate barcodes in WPF windows applications using Aspose.BarCode for WPF framework. After viewing this tutorial, you will be able to add a reference to Aspose.BarCode dll for WPF, add the BarCode control to the toolbox, use the control properties to set the CodeText and Symbology Type to generate the BarCode and change the properties using code. Technical Tip – Load Plain Text (TXT) Files into Aspose.Words Currently Aspose.Words (Aspose.Words for .NET 3.5.0.0 and Aspose.Words for Java 2.5.0.0) supports saving documents as plain text files, but does not directly support loading them. This technical tip shows you how to write your own code to load plain text files into Aspose.Words. 02 2008 09:29 EST | http://www.theserverside.com/discussions/thread.tss?thread_id=52082 | CC-MAIN-2015-11 | refinedweb | 1,862 | 52.26 |
[
]
Markus Wiederkehr commented on MIME4J-72:
-----------------------------------------
@Bernd:
dispose() should free any resources that cannot be reclaimed by the garbage collector. This
implies that dispose() essentially destroys the object and it can no longer be used afterwards.
So idempotency cannot be an issue here. It is perfectly okay for an object to behave unpredictably
once disposed. You would not expect an InputStream to work as it did before once you have
closed it, would you?
The intention is to dispose an object and leave it to the garbage collector. If you continue
to use it your are doing something wrong.
As for the pollution of the framework, this is a valid point. But the disposed flag is entirely
optional and can be removed. I will provide a patch for that shortly.
Your third concern was "all files failing deletion are visited (again (and again))". I don't
see where this happens. There is no dispose call inside a finally block (the super.dispose()
in TempFileBinaryBody only sets the parent to null, there is no recursion, loop or anything).
Considering your proposal of a ResourceManager on TempFile*Body.. TempFileTextBody and TempFileBinaryBody
aren't even public classes.. And the use case is to simply dispose a message and free all
temp files held by it or its parts. With my approach you simply call message.dispose() and
be done with it. With your approach you would first have to traverse the message hierarchy
down to the TempFile*Bodys, obtain the ResouceManager and then free the resources - seems
like a lot of work to.patch, mime4j-dispose-no-clutter | http://mail-archives.us.apache.org/mod_mbox/james-server-dev/200810.mbox/%3C656965781.1223461427309.JavaMail.jira@brutus%3E | CC-MAIN-2019-18 | refinedweb | 265 | 67.04 |
Jeff Brown: An Introduction To Building Groovy Web Applications With Grails
Groovy may be the one.
I'll try to live blog today's St. Louis JUG meeting. I have done this for the OCI internal Java and C++ lunches in the past. Since the auditorium at One City Place, where the JUG meets, has excellent WIFI, I thought I'll try to do the live blog here.
The JUG usually starts with a Q&A session:
Q: What's new in Java?
Kyle Cordes: We are on the other side of the adoption curve. There are enormous amount of money to be made. Scripting languages is a playground where you can learn some of the new constructs, like closures. These constructs are coming to a future version of Java.
Jay Meyer: The scripting support in Java 6 allows me to setup an enterprise ready server where you can deploy your applications written in a scripting language, such as Groovy, or JavaScript. Now you have transactions, you have security, etc.
Q: What is a good Java job?
Kyle Cordes: Software product work is more prestigious than IT work. There are good jobs in both categories here in St. Louis.
Jeff Brown is on stage to give today's Grails presentation. First person is Jeff now.
Ruby on Rails is new and fun. A lot of Java developer looked into Ruby on Rails and asked if it is possible to duplicate it in the Java platform. Grails meets that challenge.
Groovy is not a perfect programming language. But there are a lot of things in groovy that's cool.
(Jeff starts Eclipse.) Let me warn you that the Groovy plugin for Eclipse is flaky on a good day.
Groovy
In groovy, everything is an object. The number 5 is an object, you can call times on it:
class GroovyTest { static void main(args) { 5.times { println it } } }
In Groovy strings are surrounded in single quotes. Groovy also has GStrings. They are surrounded by double quotes. You can do variable substitution within GStrings.
Groovy support named parameter lists:
class GroovyTest { String firstName String lastName Integer age static void main(args) { def gt = new Groovytest(firstName: 'Jeff', lastName: 'Brown') println gt.firstName } }
All the places where your IDE will generate getter and setter code for you are suspicious. In Groovy you don't need the boilerplate code. When you declare a field, a getter and a setter is written for you.
I can still write a getter, but only if I want to do something different.
There are no package level members in groovy.
No semi-colon is required.
There is a really easy way to generate markups.
Grails
All right, on to the meat of the presentation. What is Grails? It's a MVC web framework for web apps. It exploits the awesome power of Groovy. It leverages proven staples: Hibernate, Spring, and Sitemesh. It is excellent for those apps in the sweet spot. And it is Fun, Fun, Fun
The user mailing list is very active. They are not hostile to Rails at all. The communities are awesome.
In the spirit of fun, I'm going to give away
an early access copy of a book that has not yet been written—Grails In Action, by Graeme Rocher, the main developer of Grails, to be published by Manning in January 2007. Four early access chapters are available already. [I completely messed up the details here. See Jeff Brown's comment at the end of this post for the correct information. My apologies to Jeff and Craeme. –Weiqi]
Famous people loves grails.
John Lennen:
"Imagine no config files
It's easy if you try
No action mappings
Man, that Grails is going to be fly."
(Jeff runs a command "grails create-app" and things flow on the command shell. Jeff then runs "grails create-domain-class" and entered "Person" and a class is generated.)
Apparently Rails does something that makes it difficult to create your own domain classes.
(Jeff runs the "grails create-controller" and entered "PersonControler".)
One of the things that is created is Eclipse project files. (Jeff then imports the whole thing into Eclipse.)
I'm going to add some attributes to Person. (Jeff adds firstName, lastName and age.) I'm going to add an attribute called scaffold
def scaffold = true
This tells grails to generate our controller at runtime.
(Starting Jetty web server, surfing to localhost:8080/javasigdemo, and things appear.) Just like JSPs, the pages in Grails are written in GSPs, Groovy Server Pages. They also need to be compiled the first time they are executed, just like JSPs.
(Mario Aquino: Jeff, are you using a database?) I'm using HSQL DB. I'll get to it in a moment.
(Jeff adds several persons in the web app.)
(Audience Member: What about the mixture of statically and dynamically typed variables? Jeff Grigg: Static types makes the code run faster.)
Famous people loves grails.
Batman and Robin:
"Holy productivity Batman! What are we going to do with the free time."
The scaffolding in Grails is interesting. The one we have been using all happens at runtime and are just like magic. I can also tell Grails to generate all, in which case it will generate all the code beforehand.
Looking at the controller: All the code blocks are mapped to actions:
def list = { [personList: Person.list(params) ] }
These code blocks are closures.
The "M"
The "M" in MVC are the domain classes.
In your domain class, you can stick with POGOs (plain old Groovy objects. You want your domain class to be free of view stuff. However you may want validation logic in your domain classes.
(Audience Member: When you change the code, what changes can be automatically picked up by the application?) Grails will dynamically pick up a lot of changes in your application. But not everything is picked up. Domain model changes are not picked up.
(Jeff shows validation at work. Invalid fields are highlighted.)
The "C"
The "C" (controller) is the traffic cop. It defines actions and navigates to the views.
We don't see anything in the list code block that tells us where to go. By convention, we go to list.gsp. If you don't want the automatic thing to happen, you can call redirect. (Jeff shows the URL associated with the delete button, something like)
(Kyle Cordes: Doing a GET on your delete URL deletes stuff. Doesn't that make you go eeeeh?)
The "V"
The "V" is GSP—Groovy Server Page.
In GSP you can easily define custom tags. You just define a closure. And the tag can be used in your GSP pages. No taglib XML files.
Sitemesh is at play here. Grails uses Sitemesh to layout the pages.
There are a lot of tags built into Grails. Logical, iterative, Ajax, form, etc.
Famous people loves grails.
Mr. T:
"I pity the fool who has to maintain all of those TLD files."
Hey Dude, Where Is My Data?
Grails generates configuration files *DataSource.groovy where * are: Development, Production, Test
Grail uses HSQL DB's in memory relational database as the default database. This can be easily changed.
You can use a ApplicationBootStrap.groovy class to to populate the database with sample data.
Grails hooks your domain objects with Hibernate, which in turn hooks up with the actual database. You don't have to write your Hibernate config files.
(Jeff writes an ApplicationBootStrap class.) This class is picked up when the application starts. It populates the database.
GORM is Groovy Object Relational Mapping. Currently it is Hibernate based. JPA support slated for 0.4.
Questions And Other Tidbits
(I asked about production or public websites running Grails.) Every 7 minutes somebody asks this question on the mailing list. It doesn't really make sense. If what you need is in there, you can use it. If not, not.
Grails 0.3 will be out in a month or so. It will have Sprint 2.0 integration.
(Kyle Cordes: How do you measure the relative merits of Grails vs. JRuby on Rails?) Groovy runs on the JVM, you can access all the Java core classes, leverage to use all the java classes you have written. JRuby is a tool that allows Ruby to be run on the JVM. Having alternatives is good.
(Jeff Grigg: There is a mismatch between Ruby and the JVM. The JRuby guys have to do a lot of tricky things to support Ruby language features such as adding methods to classes at run time.)
Just this week, at Sun days, according to one source, Sun announced that Groovy is going to be a module in Java 7.
Jeff wrapped up by giving away four ebooks on Grails. First person is Weiqi now.
What To Think
I think Jeff's talk is excellent. The audience participation makes it that much more interesting and lively.
I'm a little bit surprised by me own reaction. I came into the meeting thinking Grails is nothing but a knock-off of Ruby on Rails, and my reaction to Ruby on Rails hasn't been all that positive ("Rails is full of magic that I don't understand, will fall down somehow, etc.")
However, after the talk, I feel that Grail is a reasonable web framework that learned a lot from Ruby on Rails yet remained true to the Java platform. It makes use of the best ORM and other frameworks that the Java platform has to offer. And has a reasonable chance of picking up mind share among the rank and file Java developers. And it has a reasonable chance at succeeding with what it attempts to do.
To be sure, Groovy is not the cleanestly designed language. However it does mesh well with Java. And it does offer features that makes Grail possible. And most importantly, someone did something nice with Groovy. | http://www.weiqigao.com/blog/2006/09/14/jeff_brown_an_introduction_to_building_groovy_web_applications_with_grails.html | crawl-002 | refinedweb | 1,651 | 77.64 |
Hi All, One of the things I've been working on lately is some ASN.1 stuff.One of the first things I wrote in Haskell was an ASN.1 parser. It only worked for a subset, and I'm revisiting it to make it handle a larger subset. One of the things that gets messy is that in lots of places you can put either a thing or a reference to a thing (i.e. the name of a thing defined elsewhere). For example, consider the production: NamedNumber ::= identifier "(" SignedNumber ")" | identifier "(" DefinedValue ")" If we ignore the second alternative, the natural translation into a Parsec parser would look like: namedNumber = do name <- identifier val <- parens signedNumber return (name, val) Now to handle the second alternative is easy enough: namedNumber = do name <- identifier val <- parens (fmap Left signedNumber <|> fmap Right definedValue) return (name, val) however because names can be used before they are defined the result typegoes from being type NamedNumber = (Name,Integer) to type NamedNumber = (Name,Either Integer Name) Nothing too terrible so far. The messiness comes in when you considerthe number of places that you have to replace a type 't' with (Either t Name). I'd really like to avoid having to do this. If I were using Prolog, I could finesse the problem by introducing afree variable and filling it in when I come across the definition[*]. Logic variable backpatching. :-) So one possibility would be to return a closure: ... return $ \bindings -> (name,resolve val bindings) resolve :: (Either t Name) -> Map Name t -> t or something like that. Then when you get to the end, you apply the bindings and voila, out pops the simple type. I'm not sure this will work quite as well as it sounds. This sounds like a common problem type. Is there a well known solution to this sort of problem? cheers, Tom [*] And then at the end use var/1 to look for undefined names. Urk. Actually, if I were using Prolog in the way most Prolog programmers use it, I wouldn't be thinking about the types. -- Dr Thomas Conway drtomc at gmail.com Silence is the perfectest herald of joy: I were but little happy, if I could say how much. | http://www.haskell.org/pipermail/haskell-cafe/2007-August/029787.html | CC-MAIN-2014-35 | refinedweb | 372 | 70.23 |
Spring and Spring MVC is one of the most popular Java framework and most of new Java projects uses Spring these days. Java programmer often ask questions like which books is good to learn Spring MVC or What is the best book to learn Spring framework etc. Actually, there are many books to learn Spring and Spring MVC but only certain books can be considered good because of there content, examples or the way they explained concept involved in Spring framework. Similar to Top 5 books on Java programming we will some good books on Spring in this article, which not only help beginners to start with Spring but also teaches some best practices. In order to learn a new technology or a new framework, probably best way is to start looking documentation provided and Spring Framework is no short on this. Spring provides great, detailed documentation to use various features of Spring framework but despite of that nothing can replace a good book. Luckily both Spring and Spring MVC got couple of good titles which not only explains concepts like Dependency Injection and Inversion of Control which is core to spring framework but also gives coverage to other important aspect of Spring. Following are some of the good books available on Spring and Spring MVC which can help you to learn Spring.
Top 5 Books on Spring Framework and Spring MVCHere is my list of top 5 books to learn Spring MVC and Spring framework. Let me know if you come across any other great book on Spring, which is worth adding into this list.
Expert Spring MVC and Web Flow
Expert Spring MVC and Web Flow by Seth Ladd, Darren Davison, Steven Devijver, Colin Yates is one of my favorite book on Spring MVC and arguably one of the best book in Spring MVC. It covers both Spring MVC and web flow in depth and explains each concept with simple explanation. I highly recommend this book to any beginner which is learning Spring MVC framework. There chapter on Spring fundamentals is also one of the best way to learn dependency injection and inversion of control in Spring and I myself learned DI and IOC from that chapter. This is the Spring book I recommend to any Java web developer who is familiar with Java web technology or any MVC framework like Struts. Only missing point is that this book only covers Spring MVC and web flow and does not cover whole Spring framework. Also, in my opinion there chapter on Spring Fundamentals is one of the best way to start with Spring framework.
Spring Recipes – A problem solution approach
This is another good book on Spring Framework which I like most. This book is collection of Spring recipes or How to do in Spring Framework. In every Spring recipes you learn some new concept and it also helps to learn Spring fundamental e.g. there recipes help me to learn when to use ApplicationContext and BeanFactory and Constructor vs Setter Injection. Key highlight of this book is, It’s problem solution approach. Since it’s teaching style is different than any conventional book, it’s a good supplement along with Spring documentation. This books also provide excellent coverage of many spring technologies e.g. Spring Security, Spring JDBC, Spring and EJB, JMX, Email and have a chapter on scripting as well. If you like books on problem solution approach than you will enjoy reading Spring Recipes, not the best book on Spring but still a good one and will definitely made to any list of top 10 books on Spring framework.
Professional Java Development with the Spring Framework
Main highlight of this book is that one of it’s author is Rod Johnson, who is also created Spring framework. So you get his view on Spring and How spring should be used used, what are best practices to follow on Spring e.g. When to use Setter Injection and Constructor Injection. This book provide good coverage of Spring framework including Spring core, Spring MVC, Spring ORM support etc. Also examples in this book is easy to understand and it also focus on Unit tests which is good practice. Though I don’t rate this book too high, like if your focus is Spring MVC than Expert Spring MVC and Web flow is the best Spring book to follow. If you are looking an overview on Spring features, than Spring Documentation is best book to read. As I said positive point of this book is knowing Spring from author Rod Johnson himself. Once you have basic knowledge of Spring framework, you can read this book to get authors view.
Pro Spring 3.0
Pro Spring is one of the best book to learn Spring Framework from start. This book is massive and tries to cover most of the Spring concept e.g. Spring fundamentals, JDBC Support, Transaction support, Spring AOP, Spring Web MVC, Spring Testing etc. Good point about this book is that it’s conventional and easy to read, it explains concept, followed with good example, which is good way to learn. What is worrying is sheer size, I haven’t completed this book till date and only refer with some topic. Good point is that this book covers Spring 3.1 which is the latest stable version. As I said this is one of the most comprehensive book on Spring framework and any one who wants to learn Spring framework by following just one book, Pro Spring 3.0 is a good choice.
Spring framework documentation is located on Springsource website, here
is the link for Spring documentation for Spring framework 3.1 in HTML format. Though this is not a book, Spring tutorials and Spring documentation are
another two source of learning Spring framework, which I highly recommend. Main
reason for that is they are free and highly comprehensive and has lot of
examples to support various concept and feature. Also one of the best part
of reference documentation is that they are updated with the latest Spring
release available. Updating books with every new version of Spring is
rather difficult than updating documentation. Spring documentation combine with
any Spring book is best way to learn Spring framework. For learning Spring MVC,
you can combine Spring documentation with earlier spring book, Expert Spring
MVC and Web Flow.
Spring Documentation
Spring in ActionLots of my readers suggested Spring in Action from manning, as one of the best book to learn Spring. Seems like a worth reading book. I have seen it's content briefly and it does cover both Spring and Spring MVC. So if you are looking for common book for complete Spring framework, Spring in Action is another one.
These are some of the best books to learn Spring framework and Spring MVC. Spring documentation is special because of update and new releases of Spring Framework. Given popularity of Spring Framework for new Java development work, every Java developer should make effort to learn Spring framework.
12 comments :
How about Spring in Action?
Hi Javin,
Thanks a lot for sharing useful books information, but I would like to share for quick rap up , please see the following url..
where i can find the books list i am unable to see
Spring in Action is also good.
Can you suggest a spring book which covers concepts in-depth rather than syntax.
i.e. I want to know how namespaces work/ the concept behind namespaces, best practices for authenticating users etc.
I thought Spring in Action will take 1st place!!!
How about "Spring in Action" by Manning?
Hi,
Great article about Spring.
I think one more book "Spring in Action" can be added to this perfect list.
Regards,
Chirag
Thanks for your comments guys, As I can see, lot of you have suggested Spring in Action, another great book to add into this list.
I think Expert Spring MVC and Web Flow is a fantastic book. I learnt a lot about Java, the Spring Framework and development in general.
Best book in Spring is it's documentation. It contains accurate, updated and comprehensive information about everything on Spring framework. Most of the book only cover either few topics or few modules but documentation covers everything.
I didn't find Spring in Action pretty much fascinating since I am a beginner. This book covers more of a theortical approach. | http://javarevisited.blogspot.com/2013/03/5-good-books-to-learn-spring-framework-mvc-java-programmer.html?showComment=1380521703581 | CC-MAIN-2015-22 | refinedweb | 1,401 | 70.23 |
You can't get far in creating C programs without using functions. The good news is that in C functions are simple and efficient and there is no reason not to use them. In this chapter we look at functions, parameters, pass-by-value, return values, prototypes, local and global variables.
Compiling C – Preprocessor, Compiler, Linker Extract Compilation & Preprocessor
Also see the companion volume: Applying C
<ASIN:1871962609>
<ASIN:1871962463>
<ASIN:1871962617>
<ASIN:1871962455>
C is a very small language in the sense that it has very few pre-defined keywords. Many of the things that you use in C are provided by libraries of functions. For example, C doesn't have a print command it makes use of the printf function provided by the stdio library. As we will discover functions can be added and existing functions modified and this makes C a more powerful language.
Now we need to discover what a function is exactly and how to create one.
A function is just a collection of C instructions that you can execute by simply using the functions name. For example, printf is a function and it is comprised of quite a few lines of C statements. You can call up those lines of C by simply typing printf. In this sense you have already been using functions since your first C program.
A function is a block of C code that you give a name. We already know how to create a block of C code you simply write it between curly brackets - a compound statement. A function assigns a name to this block of code using the syntax:
functionName(){ block of code}
For example, if you start a new C99 project and following main enter:
hello(){ printf("Hello Function World");}
This defines a function called "hello" which simply prints to the console the message.
You can use the function by typing its name followed by parentheses:
hello();
You can think of this as transferring control to the start of the function which then executes each instruction to the last instruction when the part of the program that called the function is resumed.
The entire program is:
int main(int argc, char** argv) { hello(); return (EXIT_SUCCESS);}
If you run this you will see the message displayed in the console.
Notice that you have to place the hello function before the main program because functions have to be defined before they are used.
You can see that this is a powerful idea. You have effectively added a new command to C - the hello command.
This idea of extending the language by writing functions is a basic approach to creating larger programs.
In top down programming you write functions that do big things by calling other functions that do smaller things by calling other functions that do even smaller things - until the program is complete.
In bottom up programming you write small functions that might be useful and then use them to build functions that do bigger things by using them and so on up to the final program.
Most programmers thing that top down is the right way to go because it is easier to see what you need at each level.
Of course you don't need functions. You can write your program as a single block of basic C instructions. However trying to work out what this monolithic bock of code does when you come back to it after even a few hours can be very difficult. Splitting a program up into small functions makes it much easier to understand and this is called modular programming. Your program shouldn't be one huge chunk of code it should be made of modules each one doing a clear and understandable job. In C functions are your modules.
Of course there is always the efficiency objection.
Using a function is slower than just writing the instructions because the flow of control has to transfer to the function and then back again to the program that called the function. There is an overhead in calling a function but it is small enough to be ignored in most situations. Of course there are time when developing programs on small devices that you need every drop of performance. Even in this situation it is still worth using functions unless you are forced not to.
Thinking in functions should be your default that you only give up when efficiency forces you to.
You might have been wondering what the parentheses are for in the definition of a function? The answer is that you can include parameters that the calling code and use to tell the function what to do. For example:
hello(int times) { for (int i = 0; i < times; i++) { printf("Hello Function World \n"); }}
You can see the intent here. The function has an integer parameter, times which is used in the for loop to repeat the message that number of times. The \n at the end is the symbol for a newline and this separates our messages onto separate lines.
To use the function in its new form you would write:
hello(3);
to display the message three times.
What happens is as if a new variable has been created and set to 3 within the function i.e. as if:
int times=3;
was the first instruction in the function.
This is a completely general mechanism and you can pass in multiple parameters to a function each one separated by a comma.
For example
add(int a, int b) { int c = a + b; printf("%d", c);}
This adds the two specified parameters together and prints the result. You call the function using:
add(1,2);
which displays 3 on the console.
Parameters are ways of getting values into functions. There is also a way of getting a result out of a function - its return value. If you write
return value;
in a function it terminates and the value specified is returned.
What does "returned" mean?
A function that has a return value can be used in an expression and assigned to a variable.
So for example is you change the add function to:
add(int a, int b) { int c = a + b; return c;}
then it now returns the sum of a and b i.e. the value stored in variable c.
You can now use the add function and the value it returns:
int ans = add(1, 2);printf("%d",ans);
which prints the value 3.
It is as if add was a variable that had its value determined by the return value of the function.
Notice that while you can send multiple inputs into a function i.e. use multiple parameters, there can only be a single return value. This can cause problems but it is easy enough to over come this limitation.
There is a small complication. Notice that we have to specify the type of the parameters but the return type isn't specified at all. In fact if you don't specify a return type then the compiler (in C99) assumes that the value is an int. In general you should always specify the type of the return value by prefixing the function name with a type.
So the add function should be more properly defined as:
int add(int a, int b) { int c = a + b; return c;}
Now we have a function that accepts two ints and returns an int and it is used exactly as it was before. The advantage of typing the parameters and the return value is that the compiler can check that you are working with the right type of data and flag an error if you try to do something silly.
As long as a function returns a value of the correct type it can be used within an expression as if it was a variable of that type.
For example:
int ans=add(1,2)*2;
will store 6 in ans. | https://www.i-programmer.info/programming/cc/11644-fundamental-c-functions.html | CC-MAIN-2022-40 | refinedweb | 1,326 | 68.81 |
.
x + y
For example, Cents(4) + 6 would call operator+(Cents, int), and 6 + Cents(4) would call operator+(int, Cents). Consequently, whenever we overload binary operators for operands of different types, we actually need to write two functions -- one for each case. Here is an example of that:
Cents(4) + 6
6 + Cents(4).
2/5
3/8
6/40
4/5
6/8
6/24
Hi Alex,
Happy New Year!
I understand that, when you overload an operator like in the example that you have given:
you must return by value, as the result goes out of scope. On the other hand, you often preach that passing or returning large objects by value is not performant.
I am tempted to write a class representing matrices. These surely can become large. What would be the proper way to overload the arithmic operators in such a case?
And by the way: I was looking for an answer to that question in the comments. I appreciate your patience in answering the people here.
Thanks in advance
Hi Benjamin, Happy New Year!
Your compiler will usually optimize return values to get rid of this problem.
In Chapter 15 (Move semantics and smart pointers) you’ll learn more about efficiently handling large objects.
Alex might be able to elaborate return value optimization.
I suggest returning it by value. The alternatives (return by reference/address or an out parameter) both have more serious downsides or fragility issues.
However, there are two things that can work in our favor here, both of which Nascardriver has already identifier:
1) A good optimizing compiler may be able to elide the copy, preventing an unnecessary copy from being made. I talk more about copy elision later in this chapter. Rather than re-explain it here, just keep reading. 🙂
2) If your class uses dynamically allocated memory, it would probably benefit from move semantics. This would allow the class data to be transfered rather than cloned, which is a lot less expensive (basically copying a pointer rather than the entire data). I talk about move semantics in chapter 15.
Is it acceptable to initialize the reduction protocol in the constructor?
e.g.
//codecodecode
Fraction(int num, int den) : m_num{ num/gcd(num, den) }, m_den{ den/gcd(num, den) }
{
assert(m_den != 0 && "denom was zero");
}
It’s syntactically legal. But I don’t think I’d recommend doing so for two reasons:
1) It’s hard to read.
2) It calls gcd() twice when it could be called once otherwise.
Hi Alex,
Why do we need to write the name of the class after "return" while overloading the operator?
Also, why did u not do the same while calling the function having parameters of different types?
MinMax operator+(int value, const MinMax &m)
Good questions.
1) It’s better to be explicit than implicit when doing a conversion. Using Cents(c1.m_cents + c2.m_cents); makes it clear we’re intending to return a Cents object. Returning just c1.m_cents + c2.m_cents relies on an implicit conversion from int to Cents and leaves more room for interpretation or compiler errors.
2) There’s no conversion in this case. All we’re doing is calling the function above it (which returns a MinMax). Since this function returns a MinMax as well, we don’t need to specify that we want a MinMax (that’s redundant).
Why do you use parentheses in the second case instead of just
return m + value;
They’re extraneous, and I’ve removed them.
Hallo Alex,
I tried the solution the last quiz question without making the gcd function static. Here’s how I changed it:-
int gcd(int a, int b)
{
return (b == 0) ? (a > 0 ? a : -a) : gcd(b, a % b);
}
void reduce()
{
int gd = gcd(m_numerator, m_denominator);
m_numerator /= gd;
m_denominator /= gd;
}
And it worked. I have the following questions:-
1. Can member functions call other member functions without the object. Like reduce called gcd?
2. I also tried a variant where gcd was static, but I called it from reduce as follows:-
static int gcd(int a, int b)
{
return (b == 0) ? (a > 0 ? a : -a) : gcd(b, a % b);
}
I didn’t need to scope resolve it as Fraction::gcd(m_numerator, m_denominator). Why did it work?
3. Why are we making gcd static? There is no need for it to be static? What was the motivation to make gcd static?
I’d appreciate the answers to my questions and thanks again for great tutorials!
1) No. When (non-static) member functions call other (non-static) member functions, the object is implicitly passed (via the hidden this parameter).
2) Functions inside the class can see other functions inside the class, so the scoping qualifier isn’t necessary.
3) We made it static so you can call Fraction::GCD without instantiating a Fraction object. e.g.
Hello,
I don’t understand two things of the first part of the lesson:
1- Why you declare overload operators Cents instead of int? and then you create a r-value which is more expensive, isn’t it?
2- Why you copy initialize the class doing
instead of doing direct initialization
Many thanks!.
1) Because in the example, we’re showing how to add two Cents objects together. Later on, we show how to add a Cents and an int (in either order). Where do I create an r-value? Not sure what that part is in reference to.
2) Stylistic choice. Either works, and the compiler will likely treat them the same.
Ok. Thank you. Regarding to point 2), I was asking because in earlier chapters I think you said something like "try to avoid copy initialization and use direct initialization". But maybe it was in a different context.
Thanks.
Generally it _is_ better to use direct initialization, as copy initialization can cause issues in certain cases (most often when the initializer and initialized are different types). In this case, it should be the same, but that’s not _always_ the case, hence the recommendation.
Hi, under the section "Friend functions can be defined inside the class", you say you do not recommend doing this for "non-trivial member function definitions". This is confusing, as a friend function is not a member function, I would recommend you re-write that.
Thanks for the suggestion. Fixed!
Experienced programmers may laugh at me but this function blew my mind. Never saw the conditional operator nested like that. The recursive function is the cherry on top. I hope I will someday envision equally clever scripts.
“Clever” is something that is usually best avoided in programming. 🙂 In this case, it’s marginally acceptable because the nested conditional is trivial (it’s just the absolute value of variable a).
[#include <iostream>
using namespace std;
class Fraction
{
private:
int num;
int den;
public:
Fraction(int m_num=0, int m_den=1)
{
num=m_num;
den=m_den;
}
friend Fraction operator*(Fraction &m1 , Fraction &m2);
friend Fraction operator*(Fraction &m , int m2);
friend Fraction operator*( int m1 , Fraction &m);
void print()
{
cout<<num<<"/"<<den<<endl;
}
};
Fraction operator*(Fraction &m1 , Fraction &m2)
{
return Fraction ((m1.num*m2.num),(m1.den*m2.den));
}
Fraction operator*(Fraction &m , int m2)
{
return Fraction ((m.num*m2),(m.den));
}
Fraction operator*( int m1 , Fraction &m)
{
return Fraction ((m1*m.num),(m.den));
}
int main()
{
Fraction f1(2, 5);
f1.print();
Fraction f2(3, 8);
f2.print();
Fraction f3 = f1 * f2;
f3.print();
Fraction f4 = f1 * 2;
f4.print();
Fraction f5 = 2 * f2;
f5.print();
Fraction f6 = Fraction(1, 2) * Fraction(2, 3) * Fraction(3, 4);
f6.print();
return 0;
}
]
i’m getting an error "invalid operands to binary epression" for f6… why so ?
When Fraction(1,2) is multiplied by Fraction(2,3), the result is a new Fraction that is an r-value. This r-value gets multiplied by Fraction(3,4).
Your overloaded multiplication operator is using a non-const reference parameter. Non-const references can’t bind to l-rvalues. If you make your parameters const references, then they will be able to bind to r-values and you should be good to go.
Hello Alex,
I really liked your chapter on operator overloading -- especially compared to other introductions that I read before it’s starting more than slow enough. I agreed, the "friend method" is more readable as the reader can directly see the origins of input and output in the code. It’s so much easier to understand at the beginning if you don’t have to remind yourself that the other operand is accessed directly via the calling object… though I’ll be interested to see the benefits of that syntax soon 😉
However, I think the solution of quiz 1c) has an issue and some weird behavior:
causes
to crash, that might be the right place for an assert():
Try
and you’ll see that the constructor may change the sign of both numerator and denominator. The reason is "operator%()":
In the above case, we have the calls
Both numerator and denominator are divided by -1 and change signs! You can solve this issue if you force gcd() to return the absolute value:
-----------
P.S.: In maths they do exactly the same thing -- all operators used can have different meanings depending on the fields/spaces/… where they are defined. E.g. on the real numbers, "+" simply adds two numbers, whereas on finite real vector spaces, "+" is defined to add the vectors’ components. As the components are real numbers, vector addition is well defined and reuses the "+" for real numbers.
From a programmers point of view, in maths all those fields/spaces/… which reuse (arithmetic) operators are really just classes that overload those (arithmetic) operators…
Sorry for the long post, I just realized that similarity between maths and programming and think it’s amazing just how similar the underlying concepts really are!
Yes, you’ll note that many of the examples don’t have proper error checking -- this is just to keep them simple. In this case, the Fraction constructor definitely should assert that m_denominator is not 0.
Thanks for the updated gcd() function. I’ve updated the example.
hello alex…
how can i make operator + function friend of two different class???i want to add two different objects of different class..
class A
{
int data_A;
public:
A(int x)
:data_A(x){}
int get_A()
{
return data_A;
}
};
class B
{
int data_B;
public:
B(int x)
:data_B(x){}
int get_B()
{
return data_B;
}
};
int main()
{
A a(5);
B b(7);
A sum=a+b; //is it possible?
B result =a+b; //is it possible?
}
Just add the function prototype as a friend inside each class and it will be friends to both.
First of all thanks for making this great tutorial. It has been very helpful in learning C++. On a side note, in the section “Overloading operators for operands of different types”
An inline function has been defined as:
int GetCents() { return m_cents; }
Shouldn’t it be getCents()? It has been called as getCents() from main().
Yep. Fixed. Thanks for pointing that out.
With only the friend function with two Cents parameters, my code still compiles and gives the correct result for the main function.
Can you tell me why this still works? I tried to debug and see what’s going on and seems like the integer(3) successfully converted to Cents type. Does this have to do with implicit conversion?
Yes. The Cents constructor is being used to implicitly convert integer 3 into a Cents(3), which can then be used as an operand for your overloaded operator+.
Dear Alex, as far as i can se the code i made is the same as the one given as the solution, save for the fact that it wont compile. More precisely the line in main where i state what f6 should be, gives me an error saying that ‘*’ cant act on arguments type Fraction Fraction (I’m using Xcode IDE, using GNU14++). So as far as i can understand this means that it doesn’t recognise my overloaded variant of ‘*’ operator. If i delete the last line in main, it executes just fine. Could you give me some insight as to what is happening?
Surprisingly, this compiles on Visual Studio.
The issue here is that you’re multiplying three anonymous fractions (which are r-values), but your overloaded operator* that multiplies fraction is taking non-const references (which can only bind to l-values). This should not be allowed.
You should change your operator* reference parameters to be const.
thank you for this explanation.
thank you for the great tutorial!!!
In the section "Another example" line 46, you should write "// call operator+(MinMax, int)".
Best regards!
Updated, thanks for the suggestion.
Can you please explain me why it s not allowed to return by reference ?
friend Test& operator+(const Test &obj1, const Test &obj2)
{
return Test(3);
}
You can only have a reference to an l-value. Test(3) is an r-value.
Beyond that, you should never return a reference to a locally defined variable, as the variable will be destroyed when the function ends and you will be left with a reference to garbage.
Thanks Alex 🙂
Typo in exercise 1b: "Hint: To multiply two fractions, fist multiply…"
Unless you mean to pound those fractions into submission. 😉
Hah! I do mean you should pound those fractions into submission. But I’ve fixed the typo regardless.
Take that, fractions!
hello Alex when i am trying compiling above code first one using friend function am getting an error like
{<Error 1 error C2661: ‘Cents::Cents’ : no overloaded function takes 2 arguments c:usersmanikanthdocumentsvisual studio 2013projectsthis1this1prct.cpp 20 1 this1
>
<]
[#include <iostream>
class Cents
{
private:
int m_cents;
public:
Cents(int cents) { m_cents = cents; }
// add Cents + Cents using a friend function
friend Cents operator+(const Cents &c1, const Cents &c2);
int getCents() const { return m_cents; }
};
// note: this function is not a member function!
Cents operator+(const Cents &c1, const Cents &c2)
{
// use the Cents constructor and operator+(int, int)
// we can access m_cents directly because this is a friend function
return Cents(c1.m_cents + c2.m_cents);
}
int main()
{
Cents cents1(6);
Cents cents2(8);
Cents centsSum = cents1 + cents2;
std::cout << "I have " << centsSum.getCents() << " cents." << std::endl;
return 0;
}>]
The error message is complaining that there is no Cents constructor that takes two arguments. However, nowhere in your program is a Cents constructed with two arguments. Looks at the specific line the compiler is complaining about and see if you notice anything weird related to that.
[code]
static int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
[code]
This is a static member function.From article 8.12,we know that static member functions can only access static member variables.But here, it is working with local variables. So, i guess that static member functions can work on auto variables also.
Yes, static member functions can only access static member variables of the class they are associated with. But they can also access any other variables that are in scope, which could include function parameters, local variables, or global variables.
Hello, amazing tutorial, thank you! i have one question, when you put this line:
return Cents(c1.m_cents + c2.m_cents);
you are using the constructor again, but in 8.5 - Constructors, you put "They can not be explicity called" and to me seems like thats whats happend here. Can you help me please? i hope is not a dumm question .
This is actually a great question. Although it looks like we’re calling the Cents constructor directly, we’re actually not (it just looks like it). What we’re doing is creating an anonymous Cents object, which has the side-effect of calling the constructor. See lesson 8.14 -- Anonymous objects for more info on anonymous objects.
aaaa i get it now, thank you!!
Hello, Alex.
This may be a stupid question, but if I put the gcd function prototype inside the class:
and then outside the class I do this:
Visual Studio complains about "a storage class may not be specified here".
Also if I leave it without the Fraction::, the prototype complains and says it doesn’t find the function declaration. Could you explain this behavior? I find it confusing.
(The code works leaving static only in the prototype, and the declaration with Fraction::)
Thanks! 🙂
I’m can’t find any particular reason why C++ disallows you from redeclaring that the member function is static when you define the function outside the class.
One theory is that you only need to define the elements of the function prototype that are used to determine whether the function is overloaded. Static is not one of those things, since you can’t have a static and non-static version of a function that is otherwise identical.
Uhm, ok, thanks!
Why are we passing the arguments as const and by reference in the following:
MinMax operator+(const MinMax &m1, const MinMax &m2)
You should always pass objects that are classes by reference, to avoid making a copy. Const references allow you to pass in const objects, as well as anonymous objects (and literals, if that’s relevant).
public:
Fraction(int numerator, int denominator=1):
m_numerator(numerator), m_denominator(denominator)
{
// We put reduce() in the constructor to ensure any fractions we make get reduced!
// Since all of the overloaded operators create new Fractions, we can guarantee this will get called here
reduce();
}
// We’ll make gcd static so that it can be part of class Fraction without requiring an object of type Fraction to use
static int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
void reduce()
{
int gcd = Fraction::gcd(m_numerator, m_denominator);
m_numerator /= gcd;
m_denominator /= gcd;
}
in the snippet above from solution 1c , constructor is able to make a successful function call to reduce() even without knowing it’s prototype.
i wonder how’s the function call possible when the caller(constructor in this case) is unaware of the prototype of the function to be called as reduce() has not been forward declared here and defined below the calling constructor’s definition.
Classes work differently than global functions, in that the members of a class can be declared in any order. It’s one area where C++ definitely made tangible improvements.
Hi Alex, I have a doubt in the example of Overloading operators for operands of different types.
In the definition of second operator+(), shouldn’t it be
instead of
?
Both of these overloaded operators are calling the Cents(int) constructor, not calling overloaded operator+. It doesn’t matter whether you add value+c1.m_cents, or c1.m_cents+value -- either way you get an integer result that’s sent as the argument to the Cents constructor.
class Fraction
{
private:
int m_numerator = 0; --->why not invalid ?????????
int m_denominator = 1; --->why not invalid ?????????
public:
Fraction(int numerator, int denominator=1):
m_numerator(numerator), m_denominator(denominator)
{
}
void print()
{
std::cout << m_numerator << "/" << m_denominator << "\n";
}
};
initializing a class member in class template suppose to be invalid but its not i don’t get it ??????????
See lesson 8.5b -- Non-static member initialization. This ability was added in C++11.
I don’t know why, but every time I try to declare/define classes in separate header/source files and then use the functions in main(), it says "undefined reference to Class::Function()", even though I included the header files needed to use said classes/functions.
Are you instantiating class objects or trying to call the function directly via Class::Function? Only static functions can be called directly via Class::Function. Non-static functions have to be called through an instantiated object (e.g. Class x; x.function(); ).
Name (required)
Website | http://www.learncpp.com/cpp-tutorial/92-overloading-the-arithmetic-operators-using-friend-functions/ | CC-MAIN-2018-05 | refinedweb | 3,289 | 56.25 |
I'm not really to sure with using python and its object oriented features as Im better with java.
Im not sure whether to put the functions inside the classes as i can't really seeing this making a difference. I will apply my code and any changes or guidence would be great (just to be told if im on the right path etc)
def main(): user = menu(username) class Film(object): def __init__(self, year, fans): self.year = year self.fans = fans class Drama(Film): def __init__(self, film, director, actor): Film.__init__(self, year, fans) self.film = film self.director = director self.actor = actor self.year = year self.fans = fans class Documentary(Film): def __init__(self, narrator, subject, year, fans): Film.__init__(self, year, fans) self.narrator = narrator self.subject = subject def menu(userName) print "Hello, welcome." userName = raw_input("What is your name?: ") while exit = 0 print "Please select an option. 1. Add a Film 2. List Films 3. Find film by release date" inputCommand = input("Enter here: ") if inputCommand == 1 filmType = input("Press 1 for Drama . Press 2 for Documentary: ") if filmType == 1 addDrama(film, director, actor, year) else addDoc(narrator, subject, year) elif inputCommand == 2 listFilms(film, director, actor, year) elif inputCommand == 3 releaseDate(year) elif inputCommand == 8 exit = 1 def addDrama(film, director, actor, year): film = raw_input("Enter name of film: ") director = raw_input("Enter name of director: ") actor = raw_input("Enter name of actor: ") year = input("Enter year of film: ") filedata file = open("database.txt", "w") dram = Drama(film, director, actor, year) file.write(film, director, actor, year) file.close() def addDoc(narrator, subject, year): narrator = raw_input("Enter name of narrator: ") subject = raw_input("Enter subject of documentary: ") year = input("Enter year of film: ") filedata file = open("database.txt", "w") doc = Documentary(narrator, subject, year) file.write(narrator, subject, year) file.close() | https://www.daniweb.com/programming/software-development/threads/191358/python-object-orienated | CC-MAIN-2017-22 | refinedweb | 305 | 52.66 |
Moving NameNode Roles
This section describes two procedures for moving NameNode roles. Both procedures require cluster downtime. If highly availability is enabled for the NameNode, you can use a Cloudera Manager wizard to automate the migration process. Otherwise you must manually delete and add the NameNode role to a new host.
After moving a NameNode, if you have a Hive or Impala service, perform the steps in NameNode Post-Migration Steps.
Moving Highly Available NameNode, Failover Controller, and JournalNode Roles Using the Migrate Roles Wizard
Minimum Required Role: Cluster Administrator (also provided by Full Administrator)
The Migrate Roles wizard allows you to move roles of a highly available HDFS service from one host to another. You can use it to move NameNode, JournalNode, and Failover Controller roles.
Requirements and Limitations
- Nameservice federation (multiple namespaces) is not supported.
- This procedure requires cluster downtime, not a shutdown. The services discussed in this list must be running for the migration to complete.
- The configuration of HDFS and services that depend on it must be valid.
- The destination host must be commissioned and healthy.
- The NameNode must be highly available using quorum-based storage.
- HDFS automatic failover must be enabled, and the cluster must have a running ZooKeeper service.
- If a Hue service is present in the cluster, its HDFS Web Interface Role property must refer to an HttpFS role, not to a NameNode role.
- A majority of configured JournalNode roles must be running.
- The Failover Controller role that is not located on the source host must be running.
Before You BeginDo the following before you run the wizard:
- On hosts running active and standby NameNodes, back up the data directories.
- On hosts running JournalNodes, back up the JournalNode edits directory.
- If the source host is not functioning properly, or is not reliably reachable, decommission the host.
- If CDH and HDFS metadata was recently upgraded, and the metadata upgrade was not finalized, finalize the metadata upgrade.
Running the Migrate Roles Wizard
- If the host to which you want to move the NameNode is not in the cluster, follow the instructions in Adding a Host to the Cluster to add the host.
- Go to the HDFS service.
- Click the Instances tab.
- Click the Migrate Roles button.
- Click the Source Host text field and specify the host running the roles to migrate. In the Search field optionally enter hostnames to filter the list of hosts and click Search.The following shortcuts for specifying hostname patterns are supported:Select the checkboxes next to the desired host. The list of available roles to migrate displays. Clear any roles you do not want to migrate. When migrating a NameNode, the co-located Failover Controller must be migrated as well.
- Range of hostnames (without the domain portion)
- IP addresses
- Rack name
- Click the Destination Host text field and specify the host to which the roles will be migrated. On destination hosts, indicate whether to delete data in the NameNode data directories and JournalNode edits directory. If you choose not to delete data and such role data exists, the Migrate Roles command will not complete successfully.
- Acknowledge that the migration process incurs service unavailability by selecting the Yes, I am ready to restart the cluster now checkbox.
- Click Continue. The Command Progress screen displays listing each step in the migration process.
- When the migration completes, click Finish.
Moving a NameNode to a Different Host Using Cloudera Manager
Minimum Required Role: Cluster Administrator (also provided by Full Administrator)
- If the host to which you want to move the NameNode is not in the cluster, follow the instructions in Adding a Host to the Cluster to add the host.
- Stop all cluster services.
- Make a backup of the dfs.name.dir directories on the existing NameNode host. Make sure you back up the fsimage and edits files. They should be the same across all of the directories specified by the dfs.name.dir property.
- Copy the files you backed up from dfs.name.dir directories.dir directories where you copied the data on the new host, and then click Accept Changes.
- Start cluster services. After the HDFS service has started, Cloudera Manager distributes the new configuration files to the DataNodes, which will be configured with the IP address of the new NameNode host.
NameNode Post-Migration Steps
- Go to the Hive service.
- Stop the Hive service.
- If you have an Impala service, restart the Impala service or run an INVALIDATE METADATA query. | https://docs.cloudera.com/documentation/enterprise/5-13-x/topics/admin_nn_migrate_roles.html | CC-MAIN-2021-21 | refinedweb | 739 | 56.76 |
22 July 2011 23:59 [Source: ICIS news]
LONDON (ICIS)--European July bisphenol-A freely negotiated contracts settled €160/tonne down at €1,700–1,800/tonne FD (free delivered) NWE (north-west Europe) because of declining feedstock costs, slowing demand and increasing imports from Asia and Russia, sources said on Friday.
Market players said this is because conditions have improved a lot since the start of the year, when the market was very tight.
"Before April the market was extremely tight, whereas now conditions have improved a lot and there are no constraints on the market," said a market player.
The events at INEOS Phenol, which last week declared force majeure to its phenol customers, dominated talks. Many fear market conditions may deteriorate again if the force majeure continues until September, when demand is expected to pick up.
INEOS Phenol will also carry out planned maintenance in September for four weeks, for which it would normally stock up now, but is prevented from doing so by the cumene supply problems.
A number of producers fear that if the force majeure lasts until the planned maintenance it could cause supply shortages on the market.
"The news about INEOS Phenol has made a lot of people uncertain about the future, especially producers, who fear they will not be able to buy enough phenol on the market," said a BPA producer.
Buyers, on the other hand, said there is plenty of product coming in from Asia and ?xml:namespace>
Formula-related July BPA contracts are at €1,500–1,750/tonne FD NWE because of declining feedstock costs.
However, because benzene and phenol is set to increase in August, formula-related BPA contracts are likely to follow. On Wednesday, August benzene spot prices were around $1,240–1,245/tonne CIF ARA, which is €126-130/tonne above the July contract price which settled at €754/tonne CIF (cost, insurance and freight)ARA (Amsterdam-Rotterdam-Antwerp).
BPA spot prices are at €1,650–1,800/tonne FD NWE. One buyer and a producer reported spot at €1,500–1,590, but this is not representative of the market.
Supply is healthy, with increased imports | http://www.icis.com/Articles/2011/07/22/9479478/bpa-july-contract-settles-at-1700-1800tonne-fd-nwe.html | CC-MAIN-2015-18 | refinedweb | 362 | 57.71 |
When I first installed Reporting Services I had read something about embedded code, and my head had filled with visions of grandeur. I pictured hooking events for customization and deriving new classes to override virtual functions. I expected an ASP.NET experience complete with code behind and a reporting engine under the hood. So before we continue, let’s be clear – you won’t be doing any of the above with embedded code in Reporting Services for SQL Server 2000.
There are, however, lots of extensibility points in Reporting Services. You can write rendering, delivery, security, and data processing extensions to meet special needs, such as forms authentication – but the focus of this article will be on embedded code. The ability to embed code into a report will let you accomplish many tasks once you understand the purpose of the feature and the limitations you are working under. Let’s look at some of the details of code in Reporting Services.
Why Embed Code?
Reporting Services gives you a number of functions to use in a report. For instance, there are functions to sum and average numbers, and functions to count values. Visual Basic functions such as InStr and DateAdd are present, as are Iif and Switch. However, the product designers could not predict your every need, and embedded code allows you to implement functions with custom code.
Custom code comes in two forms. You can write a custom assembly and reference the assembly from a report. This is a good approach to use when you need to share code across a number of reports, or to decouple calculations and rules from a report into a class library and possibly share the class library with other applications. A custom assembly is also a good choice when you need additional security permissions, which we will revisit later.
The second form of custom code is code embedded directly into a report. We will address some of the difficulties in this approach, but first, a code example. Let’s say we want to sprinkle some color into a report. Depending on the value of a field, we will want to adjust the color from a plain black to a bright red. With a report in the designer we will go to the Report menu and select Report Properties. In the dialog box (shown below), we can enter code into the text area.
To use the code, we can select a textbox (or any control with a Color property that we want to set programmatically) and open the properties toolbox window. In this case, we will set the Font Color property for a Textbox control in a report table. W can enter the following expression, which assumes we have a query returning a Quantity column:
=Code.SetColor(Fields!Quantity.Value)
One of the nice features of Reporting Services is the ability to use an expression instead of a hard value on any property. When the report renders, this expression will change the colors of the font depending on the value in each row. Again, you can use expressions on any property to control layout, colors, and styles.
So where does the code live? Inside the RDL file. Right click the RDL file in Solution Explorer and take a look at the XML markup. Inside you'll see:
<Report > ... <Code>Public Shared Function SetColor(ByVal Value As Integer) As String SetColor = "Red" If Value < 10 Then SetColor = "Black" ElseIf Value < 15 Then SetColor = "Maroon" ElseIf Value < 20 Then SetColor = "Orange" End If End Function </Code> . . . </Report>
Take A Step Back
Now we have seen how and where we can use custom code, let’s talk about some restrictions (remember this article is written for Reporting Services 2000, future versions may change).
First, you must write the embedded code in the Visual Basic .NET language (although a custom assembly could use any .NET language). There is no intellisense in the code window, and you will not learn of any compilation errors until you do a report preview. You must write the code inside a public, shared function. You can embed more than a single function, but I would discourage anyone from overcrowding a report with code. A custom assembly, with all of the proper support from Visual Studio, should prove more manageable in the end.
You need to pass values from the report into your function to perform calculations. In other words, you cannot reach out from custom code and grab field values, nor can you obtain references to Dataset objects. There has been some discussion about future versions exposing the Dataset objects, which would allow the building of custom aggregators using custom code.
While shared methods are recommended, shared fields are definitely not. For instance, the following code will have problems.
Public Shared Function AddToCount(ByVal Value As Integer) As String Count = Count + value End Function Shared Count As Integer = 0
First, we have no control over the lifetime of the variable Count. Secondly, if multiple users are executing the report with this code at the same time, both reports will be changing the same Count field (that is why it is a shared field). You don’t want to debug these sorts of interactions – stick to shared functions using only local variables (variables passed ByVal or declared in the function body).
Finally, you can use types from the Microsoft.VisualBasic, System.Convert, and System.Math namespaces without namespace qualifiers. You can also use types from other namespaces, but you’ll need to specify the full namespace, for example:
Dim a as system.Collections.ArrayList
However, there are some types you will not be able to use for security reasons.
Embedded Code and Security
Code Access Security is in effect in Reporting Services. Since end-users can upload reports with embedded code, it makes perfect sense to protect the server and network from malicious report code. Embedded code executes with the built-in Execute permission by default, which does not allow for much beyond string and math operations on the Reporting Services object model. You would not, for instance, be able to use file or network IO.
If you need additional permissions for your code, you can change the default permission for embedded code but it is not a step to take without very careful thought. Modifying the permissions for embedded code will allow the code in any report to execute with the same permissions. This is another scenario where I would strongly advise using a custom assembly. For more information on code access security in Reporting Services, take a look at Understanding Code Access Security In Reporting Services.
Conclusion
Reporting Services is a platform to create, manage, and deliver reports. Having the ability to embed custom code inside of these reports allows flexibility in what you can achieve. Hopefully, future versions will allow access to more of the internal events and objects of the engine.
Additional Resources
Read more Reporting Services articles at OdeToCode.
-- by K. Scott Allen | http://odetocode.com/Articles/130.aspx | CC-MAIN-2014-52 | refinedweb | 1,164 | 62.68 |
Dealing with dates
Dates are tricky little things in ways that aren't apparent when you first look at them. As I burrowed into the requirements around generating an Atom feed for this site I wandered into the thorny wastelands of ISO-8601 dates. For example, look at this simple Atom feed:
<?xml version="1.0" encoding="utf-8"?> <feed xmlns=""> <title>Coffee and Code Feed</title> <link href=""/> <updated>2017-11-10T08:15:26+0000</updated> <author> <name>Tony Bedford</name> </author> <id>urn:uuid:B2F5F303-9B73-4D58-B4DF-32EC8F74136F</id> <!-- Entries go here --> <entry> <title>Creating an Atom feed</title> <link href=""/> <id>urn:uuid:2E4A626F-FF02-47F0-9538-254F76F5C7EF</id> <updated>2017-11-10T11:07:29+0000</updated> <summary>This is a summary of the article.</summary> </entry> </feed>
You'll notice if you look at an Atom feed dates in a format similar to
2017-11-10T11:07:29+0000. This is an ISO-8601 format date. It has various forms. This one is in a format where the time difference to UTC is shown, in this case the difference is zero.
The other common ISO-8601 format you might come across is
2011-08-27T23:22:37Z. This format is converted to UTC, in other words the local date-time has been adjusted to be a UTC date-time.
This can be clarified by example, while showing you how you can generate ISO-8601 dates on the command line (in Mac OS X, Linux, or Cygwin).
To obtain a UTC referenced date on the command line you can issue the following command:
date -u +"%Y-%m-%dT%H:%M:%SZ"
This will give you an ISO-8601 format date corrected to UTC - the
-u option tells
date you want the date-time automagically converted from your local time to UTC. Example output from the command would be:
2011-08-27T23:22:37Z
If you've not come across UTC before you can think of it as approximately GMT. GMT is based on astronomical time, but UTC is based on fancy-pants atomic time as dictated by super accurate atomic clocks. This atomic time is called International Atomic Time (TAI).
One of the problems with astronomical time is it's based on, well, astronomical bodies, and their spinning and motion tends to speed up and slow down depending on tides, the moon, the sun, and which way the wind is blowing.
So astronomical time and TAI get out of synch, so there's this "fiddle factor" called the leap second they have to apply now and then and that's when Linux crashes and all hell breaks loose. This TAI with the fiddle factor is called Universal Coordinated Time (UTC).
The reasons the acronyms don't quite match is the acronyms were based on the original French names for these standards.
Anyway, I digress...
I realized the best approach with regards dates for my website would be to standardize on a date reference and two date formats.
First, the date reference point for all dates associated with this site is UTC. It does not matter whether or not I am on summer time, or what time zone you are in, dates are UTC - period. I will say that again - dates on this site are always UTC.
Generally when you are looking at ISO-8601 dates they always have the format YYYY-MM-DD. This avoids the confusing situation where some countries put the month before the day and so on.
I also use two date-time string formats:
I have a human readable (at least more human readable) format which I use in the article source at the bottom of each article. This is of the format
2017-10-01 12:21:36 UTC. Note the UTC on the end which is my way of clarifying this is a UTC date-time. It's quick and clean and because it's more or less ISO-8601 (but not quite) it should be unambiguous. This is basically used for
publishedand
updateddate-times.
The second string format I use is one you have already seen - it is an ISO-8601 format date corrected to UTC. This is only used within the generated Atom feed for the site, so you generally won't see it. This format is a little 'busy' to be used as a human readable format, but feed readers love it!
I have some Python code that will convert from format 1 to format 2. So the idea is the date-time can be read from a blog post / article, and converted to the ISO-8601 format. Here's the code snippet:
import re def convert_date (s): m = re.search (r'(\d\d\d\d-\d\d-\d\d)', s) date = m.group(1) m = re.search (r'(\d\d:\d\d:\d\d)', s) time = m.group(1) iso_date = date + "T" + time + "Z" return iso_date
The code is fairly simple - I could have used a single regex, with multiple capture groups, which would have been faster and use less code, but it seemed easier to read split over two regexes.
OK so I second guessed myself and did a slightly more succinct version for you, and then added some error checking too, since we really need to be explicit about specifying UTC date-times:
def convert_date (s): m = re.search (r'(\d\d\d\d-\d\d-\d\d) (\d\d:\d\d:\d\d) (\w\w\w)', s) if m.group(3) != "UTC": print("ERROR: Only UTC format should be specified!") exit(-1) return m.group(1) + "T" + m.group(2) + "Z"
As an aside, if you type the command
date in the terminal normally you will get a date-time in this format
Fri 10 Nov 2017 14:03:59 GMT. In summer this would probably show a BST on the end I would guess - that's one reason why I avoid this format, you'd have to start dealing with setting clocks backwards and forwards and all that malarkey. By sticking with UTC I never have to worry about that.
You can do
date -u to get a date-time adjusted to UTC and formatted like this:
Tue 14 Nov 2017 13:21:21 UTC. I have considered this date format too as it is very human readable. I have not quite decided whether to use this format or not, but the code to convert it to ISO-8601 is as follows:
def convert_date2 (s): months = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12} m = re.search (r'(\w\w\w) (\d\d) (\w\w\w) (\d\d\d\d) (\d\d:\d\d:\d\d) (\w\w\w)', s) if m.group(6) != "UTC": print("Only UTC format should be specified!") exit(-1) YYYY = m.group(4) MM = str(months[m.group(3)]) DD = m.group(2) time = m.group(5) return YYYY + '-' + MM + '-' + DD + 'T' + time + 'Z'
Again, this could probably be made a little more succinct but it's good enough for this application.
I hope you've found this article useful. Feel free to contact me or borrow any of my code if you think it might be useful.
References: | https://tonys-notebook.com/articles/dealing-with-dates.html | CC-MAIN-2022-05 | refinedweb | 1,218 | 71.44 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
sale agent field is empty in invoice
In OpenERp v7
A sale order is created with the customer having sale agent. After confirming the sale , I created the invoice. The Agent field in the created invoice is empty.
The agent is not populated from sale order to invoice.
Is there any change to be done in the latest version of the sale commission module downloaded from launchpad.
Hello !
If you want to transfer anything from Sales Order to invoice, then you have to override this method in your module which is written in Sale module in sale.py file.
If you are aware about OpenERP architecture and having python knowledge then you can do that.
def _prepare_invoice() | https://www.odoo.com/forum/help-1/question/sale-agent-field-is-empty-in-invoice-30196 | CC-MAIN-2017-09 | refinedweb | 146 | 64 |
You can use S3's Object Lifecycle feature, specifically Object Expiration,
to delete all objects under a given prefix and over a given age. It's not
instantaneous, but it beats have to make myriad individual requests. To
delete everything, just make the age small.
[email protected] needs to have write permission for your
LogBucket as described here:
By default, objects on S3 are "private" -- they are only accessible if you
prove to "own" those objects by providing some credentials in the query
string.
To make the objects publicly accessible (ie, without having to sign the
requests), you need to attach a policy to the bucket.
To add that permission, go to S3 on the AWS Management Console, click on
your bucket, select Properties, and there you will see "Permissions". Try
that.
var s3bucket = new AWS.S3({params: {Bucket: 'test_bucket/sub_bucket'}});
will create an extra file. Take out the params in the parentheses. I found
out that Amazon's quick start guide example creates an extra file. This way
is the correct way to do it.
// Create a bucket using bound parameters and put something in it.
var s3bucket = new AWS.S3();
s3bucket.createBucket(function() {
var params = {Bucket: 'bucket/sub-bucket', Key: 'file_name1', Body:
'Hello!'};
s3bucket.putObject(params, function(err, data) {
if (err) {
console.log("Error uploading data: ", err);
} else {
res.writeHead(200, {'Content-Type':'text/plain'});
res.write("Successfully uploaded data to bucket/sub-bucket/");
res.end()
}
});
});
Go to your eclipse folder, open eclipse.ini and add the lines
-vm
C:Program FilesJavajdk1.6.0_29jreinserverjvm.dll
Replace jdk1.6.0_29 with the version code of your jdk. These lines should
be added above
-vmargs
{
:::yourbucketname"],
"Condition":{"StringEquals":{"s3:prefix":["","yourfoldername/"],"s3:delimiter":["/"]}}
},
{
"Sid": "AllowListingOfUserFolder",
"Action": ["s3:ListBucket"],
"Effect": "Allow",
"Resource": ["arn:aws:s3:::yourbucketname"],
"Condition":{"StringLike":{"s3:prefix":["yourfoldername/*"]}}
},
{
"Sid": "AllowAllS3ActionsInUserFolder",
"Effect": "Allow",
You can do this with pre-signed query string authentication:
I assume, because you mention passing a URL to Dropbox, that you're using
the Saver? If so, you can tell the Saver what file name to use, so give it
the authorized URL and specify a filename so there's a file extension.
E.g.:
<a href="..." class="dropbox-saver"
data-</a>
or, in JavaScript:
Dropbox.save('...', 'myfile.txt');
When you say that "because the file then doesn't end in an extension
Dropbox recognizes so it again fails to work," what do you mean, exactly?
What goes wrong when the file doesn't have an extension?.
I don't believe you can log the activities to the event log, but what you
can do is use the -xml parameter to output the changes in XML format. You
could then use this to log to the event log via a Powershell script, for
example.
I performed the following tasks:
Created a bucket in Amazon S3 named images.my-domain.com
Uploaded a file into the bucket
Created a Record Set in Amazon Route 53 (A record, Alias = Yes, Alias
Target = s3-website-ap-southeast-2.amazonaws.com -- yes, I'm in Sydney too)
Test 1 - Direct access: Clicking the object link in Amazon S3
(s3-ap-southeast-2.amazonaws.com/images.my-domain.com/picture.jpg) returned
AccessDenied as expected, since there are no permissions on the object.
Test 2 - Direct Pre-Signed URL: Using a Pre-Signed URL (created via
BucketExplorer) on the object in S3 (using the normal S3 URL) successfully
provided access to the object. This is to be expected.
Test 3 - Alias access: Accessing the object link in Amazon S3, but changing
it to use the domain name directly (images
This answer can help you: Notification of new S3 objects
The summary is that, at this moment, there is no notification of new
objects except for s3:ReducedRedundancyLostObject event. The official
documentation is here:
The solution is to implement the logic in your code or poll the bucket..
Had this very same problem a while ago.
For your debug process to run with full Admin access, you'd have to open
Visual Studio with full admin access.
In production, have your process "Run As Administrator".
If you do not do any of the above, you will have to implement
impersonation.
When creating your MVC application, one option is to create an "Intranet"
application. This will turn on "Windows" authentication by default inside
Web.config.
When publishing such a project to IIS, you need to enable Windows
authentication for your application in the IIS Management Console. You may
also have to disable Anonymous authentication.
Ok so i got the solution.
I need to discard the Pramaeterized plugin but now is using the Build flow
Plugin []
The benefit is it is giving me the log to be placed in the parent job
without any modification in the child project.
the usage is as follows:
def today = new Date()
out.println '----------------- Build Started At '+ today+
'----------------------------'
b=build("<BaseBuild>",ParentWorkSpace:build.properties["workspace"],Param:"Value")
today=new Date()
out.println '-------- Build Log -------------- '
out.println b.log
out.println '----------------- Build Ended At '+ today+
'----------------------------'
This way i have full control and when i attach the log then i am attaching
the original log in m have to have folders created first. But you can't call file.mkdirs() -
you need to call file.getParentFile().mkdirs() - otherwise, you will
create a folder with the name of the file (which will then prevent you from
creating a file with the same name).
I'll also mention that you should check the result code of mkdirs(), just
in case it fails.
And though you didn't ask for it, I'll still mention that you don't need to
call createNewFile() (your FileWriter will create it).
and, just for thoroughness, be sure to put your file.close() in a finally
block, and throw your exception (don't just print it) - here you go:
void writeToFile(String input) throws IOException{
File file = new File("C:\WeatherExports\export.txt");
if (!file.getParentFile().mkdirs())
IE's XMLHttpRequest object (which WinJS.xhr uses) doesn't support ftp
protocol so that's why you get an error.
Try using BackgroundDownloader class which supports ftp downloads.
You don't need to use prefix to refer to the resource for the context of
Object operations. I'd also recommend restricting the S3 actions. Here is
a recommend policy, based on the one from an article on an S3 Personal File
Store. Feel free to remove the ListBucket if it doesn't make sense for you
app.
{"Statement":
[
{"Effect":"Allow",
"Action":["s3:PutObject","s3:GetObject","s3:DeleteObject"],
"Resource":"arn:aws:s3:::my-bucket-test/66-*",
},
{"Effect":"Allow",
"Action":"s3:ListBucket",
"Resource":"arn:aws:s3:::my-bucket-test",
"Condition":{
"StringLike":{
"s3:prefix":"66-*"
}
}
},
{"Effect":"Deny","Action":"sdb:*","Resource":["arn:aws:sdb:u
Sounds like a cross-domain-request issue.
You are unable to use getJSON() to fetch data from another site due to
browser policies.
The only possible reason I can think of is you are not really the WoopyCat
user, here is the correct way to get the path based of the currently
running user.
var roamingFolder =
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
//This equals the AppDataRoaming folder for the current user
Directory.Move(Path.Combine(roamingFolder, ".minecraft"),
Path.Combine(roamingFolder,currentUser));
Try with a more recent version:
Set http = CreateObject("Msxml2.XMLHttp.6.0")
It could also be an issue with your Internet security settings (see here).
Open the Internet Options applet in the Control Panel, select the zone for
the website (probably "Trusted sites") in the Security tab and click Custom
level….
In the section Miscellaneous set Access data sources across domains to
Enabled.
You could use the Console.ReadLine method which will return the value
entered by the user and you could store it in the corresponding variable:
namespace Password
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter password:");
string password = Console.ReadLine();
bool passWordMatch;
passWordMatch = password == "Test";
if (passWordMatch)
{
Console.WriteLine(" Password Match. Access Granted");
}
else
{
Console.WriteLine("Password doesn't match! Access
denied.");
}
}
}
}
The doctrine relation annotations were wrong:
/**
* @ORMManyToMany(targetEntity="Role", inversedBy="users")
*/
private $roles;
/**
* @ORMManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
The following generates two arrays: $values contains the values, and $out
contains keys in the form type1:3. The variable $max determines the maximum
number of sets:
$arr['type1'] = array(1, 2, 3, 4, 5);
$arr['type2'] = array(6, 7, 8, 9);
$arr['type3'] = array(10, 11, 12, 13, 14, 15);
$arr['type4'] = array(16, 17, 18, 19);
$arr['type5'] = array(20, 21, 22, 23, 24);
$max = 5;
$out = array();
$values = array();
$i = 0;
foreach ($arr as $key1 => $type){
foreach ($type as $key2 => $item){
$out[$i%$max][] = $key1.':'.$key2;
$values[$i%$max][] = $item;
$i++;
}
}
var_dump($values);
[0] => array(1, 6, 11, 16, 21)
[1] => array(2, 7, 12, 17, 22)
[2] => array(3, 8, 13, 18, 23)
[3] => array(4, 9, 14, 19, 24)
[4] => array(5, 10, 15, 20)
Or you ca
Twitter released the next version of API (1.1). And tweetstream doesn't
support it yet. See relevant issue on tweetstream project issue tracker.
I am not JAVA user but isn't it 32 vs. 64 bit issue ?
on 64 bit Windows error code 5 usually means that executable is not 64 bit
compatible
sometimes this is the case even when executable need to access only some
(older win) system directory which does not exist anymore
To prove this try to use your executable in command line. if you can manage
to get it work there than it is different issue. If not find executable for
your OS.
Another possibility is that the file has to be physically present on some
drive.
you wrote that you has it as temporary.
not shore what it means for JAVA
if it only copy it to some file and delete after use than its OK
but if it is only in memory somewhere than that could be problem if
executable need access to itself
To prove this just copy the file to some
I realized this has to do with the new AWS Identity and Access Management
(IAM). I had created a new IAM user, but I hadn't given that user the
correct privileges. In the past, there was only one user, and that user
had admin privileges. Now you have to create a user, give that user the
correct privileges, and use that user's credentials. I hope this helps
someone.
You are running on a sandbox and you don't have the permission to perform
the classLoading require by the ObjectMessage. Try relaxing the settings of
your JVM's security sandbox, or sign the jar. Anyways it's not really a
HornetQ issue. it's more a JVM security configuration thing.
Its because it seems like you are trying to open and read a directory here.
Your file as you say it, doesn't have any extension specified so java takes
it as a directory. use isFile() method to check for a file before opening.
You can use listFiles() method to obtain files of the directory.
check if the folder is read only (in windows) if it is, just clear the read
only flag.
if it isn't read only, make sure that the admin user has full rights on
that folder. You can check this by right clicking on the folder -->
properties --> security
check out this link for more information on how to set it programatically:
C# - Set Directory Permissions for All Users in Windows 7
Is there a config file on the NAS where to put allowances for clients? E.g.
in debian based OS the config file is "/etc/exports" and you would put
there "/volume2/Asterisk_Recordings 192.168.1.1(rw,sync)" and activate this
with "exportfs -a" (your NAS may do this automatically if you update the
config via a web interface, I guess.) Check also Mounting NFS results in
access denied by server.
The account that is being used for the worker process of the web site has
no (write)access to the file.
Configure the file (or folder) so that the ASP.NET process has access.
Another thing to look at is whether or not the path as stated in the code
is the actual path on the server.
I'm not exactly sure if this is how XDR works, but it works like this on my
server for some reason, but it looked like 'open' triggered the ajax
response from my .Net back-end, and blocked the send from getting through
(It doesn't sound right, but that's is how it looked in Fiddler). So no
form data was being posted, which caused all the weirdness to happen.
To fix this, I changed the post to a get, and added a clause to my .Net
Ajax Controller that said if Request.Form.AllKeys.Length = 0, get the query
string instead.
Unless you have a specific need to use the ANSI version of LogonUser, you
should use LogonUser instead of LogonUserA in your declaration, i.e.
Declare Function LogonUser Lib "advapi32.dll"
You should also verify that the user being impersonated has interactive
logon rights on the local machine. | http://www.w3hello.com/questions/Just-created-S3-bucket-getting-a-bunch-of-access-denied-logs | CC-MAIN-2018-17 | refinedweb | 2,195 | 55.74 |
convert expression to QuadraticField
I tried (in the Sage shell)
K = QuadraticField(-3) a = K(sqrt(-3))
But that fails with a TypeError exception. What is the problem?
I know that I can get the generator by
K.gen() but I want to be able to convert expressions to
K.
I don't know that it will be so easy to coerce from the symbolic ring to here in general, but more power to you if someone can... I do find the following behavior a little disturbing - try `sage: K.gen()`, which yields `a`, which no one ever asked for... this *is* documented in `QuadraticField?` but only as the default variable name, which of course isn't injected into the global namespace. | https://ask.sagemath.org/question/10126/convert-expression-to-quadraticfield/ | CC-MAIN-2021-04 | refinedweb | 122 | 75.4 |
@andrewsantarin/extended-flexlayout-react v0.4.0-alpha.2
FlexLayout Extended
This fork extends the existing
flexlayout-react library with additional features.
Notes from the Contributor
Hello, there. You might be wondering, "What the fork? What's going on?"
Terrible joke, I know.
To put it simply: It's a version of
FlexLayout (a.k.a.
flexlayout-react on NPM) which is still very much a work in progress. Currenly, I'm developing a feature which will support docking & undocking of tabs.
See my Imgur upload () for a rough prototype idea of what this extension intends to do.
Premise and Objective
If you're in dire need of a React.js library that supports tabsets which can both be separated on the grid and float freely one the screen, then this extended library is most likely for you.
Where to start? / Installation / Usage
For the installation & usage, check the original docs below. I've made some additional details based on what I've contributed so far.
This fork contains additional features not included in the original. It is currently being pitched as a proof of concept at. To use this specific fork in your projects, follow these commands:
npm install react --save npm install react-dom --save npm install react-rnd --save # This dependency is needed for the free-floating tabs npm install @andrewsantarin/extended-flexlayout-react --save
Then, follow the rest of the docs as usual.
If you want to see this library's tie-in examples, then do this:
git clone cd FlexLayout git checkout -b branch origin/wip/<the-wip-branch-name> npm install npm start
Replace the
wip/<the-wip-branch-name> with any particular development branch I'm working on. If you want to see what's in store for this library, don't look at the
master branch. Instead, refer to one of these three groups:
develop- merge of all
featurecommits
feature- polished up commits
wip- totally new stuff, very unstable
Once you run
npm start, wait for the
webpack bundler to finish, then open on your local browser.
Normal docs continue below!
FlexLayout
FlexLayout is a layout manager that arranges React components in multiple tab sets, these can be resized and moved.
Try it now using JSFiddle
Screenshot of Caplin Liberator Explorer using FlexLayout
FlexLayout's only dependency is React.
Features:
- splitters
- tabs
- tab dragging and ordering
- tabset dragging (move all the tabs in a tabset in one operation)
- dock to tabset or edge of frame or (NEW!) free-floating space
- maximize tabset (double click tabset header or use icon)
- tab overflow (show menu when tabs overflow)
- border tabsets
- floating tabsets (NEW!)
- submodels, allow layouts inside layouts
- tab renaming (double click tab text to rename)
- theming - light and dark
- touch events - works on mobile devices (iPad, Android)
- add tabs using drag, indirect drag, add to active tabset, add to tabset by id
- preferred pixel size tabsets
- tabset with headers
- tab and tabset attributes: enableHeader, enableTabStrip, enableDock, enableDrop...
- customizable tabs and tabset header rendering
[esc]key to cancel drag
- typescript type declarations
- supports overriding css class names via the classNameMapper prop, for use in css modules
Installation
FlexLayout is in the npm repository. Simply install React and FlexLayout from npm:
npm install react --save npm install react-dom --save npm install flexlayout-react --save
Import React and FlexLayout in your modules:
import React from "react"; import ReactDOM from "react-dom"; import FlexLayout from "flexlayout-react";
Include the light or dark style in your html:
Light
<link rel="stylesheet" href="node_modules/flexlayout-react/style/light.css" />
Dark:
<link rel="stylesheet" href="node_modules/flexlayout-react/style/dark.css" />
Usage
The
<Layout> component renders the tabsets and splitters, it takes the following props:
The model is tree of Node objects that define the structure of the layout.
The factory is a function that takes a Node object and returns a React component that should be hosted by a tab in the layout.
The model can be created using the Model.fromJson(jsonObject) static method, and can be saved using the model.toJson() method.
this.state = {model: FlexLayout.Model.fromJson(json)}; render() { <Layout model={this.state.model} factory={factory}/> }
Example Configuration
Consider this typical use case and its implementation code below:
- You want a main layout that has two groups of tabs, split evenly in the middle.
- You also want another tab to float freely over the main layout, which can be moved around at the user's discretion.
- You also want yet another set of panels which contain docked tabs on all four sides of your main layout.
const json = { global: {}, layout: { // Required type: "row", // Also required. weight: 100, // Also required. children: [ // Optional children elements. // If you'd rather not have any elements on this layer, leave the "children" array empty. { type: "tabset", weight: 50, // Not in pixels, but rather, a relative ratio between the children of the same parent. selected: 0, children: [ { type: "tab", name: "FX", component: "grid", } ], }, { type: "tabset", weight: 50, // Not in pixels, but rather, a relative ratio between the children of the same parent. selected: 0, children: [ { "type": "tab", "name": "FI", "component": "grid", }, ], }, ], }, floating: { // Required type: "floating", // Also required. children: [ // Also required. // Optional children elements. // If you'd rather not have any elements on this layer, leave the "children" array empty. // You may only nest tabsets up to 1 level from the floating element. { type: "tabset", // Use the following on the tabset instead of "weight". x: 125, // From the topmost pixel of the layout root element. y: 250, // From the leftmost pixel of the layout root element. width: 600, // Initial pixel width of the child element. height: 480, // Initial pixel height of the child element. // ------------ // selected: 0, children: [ { type: "tab", name: "FX", component: "grid", }, ], }, ], }, "borders": [ // Optional // You can specify up to 4 borders in total across 4 sides. // 1 border = 1 side { "type": "border", "location": "top", "children": [ { "type": "tab", "enableClose": false, "name": "Navigation", "component": "grid" } ] }, { "type": "border", "location": "left", "children": [ { "type": "tab", "enableClose": false, "name": "Views", "component": "grid" } ] }, { "type": "border", "location": "right", "children": [ { "type": "tab", "enableClose": false, "name": "Options", "component": "grid" } ] }, { "type": "border", "location": "bottom", "children": [ { "type": "tab", "enableClose": false, "name": "Activity Blotter", "component": "grid" }, { "type": "tab", "enableClose": false, "name": "Execution Blotter", "component": "grid" } ] } ] };
Example Code
import React from "react"; import ReactDOM from "react-dom"; import FlexLayout from "flexlayout-react"; // Let's assume that the example configuration above is what we want. import MAIN_LAYOUT_JSON from "./main.layout.json"; class Main extends React.Component { constructor(props) { super(props); this.state = { model: FlexLayout.Model.fromJson(MAIN_LAYOUT_JSON), }; } factory = (node) => { const component = node.getComponent(); if (component === "button") { return <button>{node.getName()}</button>; } } render() { return ( <FlexLayout.Layout model={this.state.model} factory={this.factory}/> ) } } ReactDOM.render(<Main/>, document.getElementById("container"));
The above code would render two tabsets horizontally each containing a single tab that hosts a button component. The tabs could be moved and resized by dragging and dropping. Additional grids could be added to the layout by sending actions to the model.
If you're looking for more advanced implementations to exert additional control over your layout, see our examples.
Try it now using JSFiddle
Core Concept
The model revolves around 4 types of "node":
row
Rows contain a list of tabsets and child rows. The top level row will render horizontally, while child "rows" will render in the opposite orientation to their parent.
Note: Rows can't be nested in on
floatingand
border.
tabset
Tabsets contain a list of tabs and the index of the selected tab.
tab
Tabs specify the name of the component that they should host (that will be loaded via the factory) and the text of the actual tab.
border
Borders contain a list of tabs and the index of the selected tab; they can only be used in the border's top level element.
The main layout is defined with rows within rows that contain tabsets that themselves contain tabs.
The model json contains 4 top level elements:
global
where global options are defined.
layout
where the grid-separated
row -> tabset -> tabslayout hierarchy is defined.
floating
where the free-floating
tabset -> tabshierarchy is defined.
(optional)
borders
where up to 4 borders are defined (i.e. the
"top",
"bottom",
"left",
"right"sides), one border for each side.
Weights on rows and tabsets specify the relative weight of these nodes within the parent row. The actual pixel values do not matter; their relative values will be calculated instead (i.e. two tabsets of weights
30,
70 relative their parent element would render the same if they had weights of
3,
7).
To control where nodes can be dropped, you can add a callback function to the model:
model.setOnAllowDrop(this.allowDrop);
Example:
class Main extends Component { allowDrop = (dragNode, dropInfo) => { let dropNode = dropInfo.node; // prevent non-border tabs dropping into borders if (dropNode.getType() == "border" && (dragNode.getParent() == null || dragNode.getParent().getType() != "border")) { return false; } // prevent border tabs dropping into main layout if (dropNode.getType() != "border" && (dragNode.getParent() != null && dragNode.getParent().getType() == "border")) { return false; } return true; } }
By changing global or node attributes you can change the layout appearance and behavior.
For example, setting
tabSetEnableTabStrip to
false in the global options would change the layout into a multi-splitter (without
tabs or drag and drop).
{ "global": { "tabSetEnableTabStrip": false } }
Global Config attributes
Attributes allowed in the
global element
Row Attributes
Attributes allowed in nodes of type
"row".
Tab Attributes
Attributes allowed in nodes of type
"tab".
Inherited defaults will take their value from the associated global attributes (see above).
Tab nodes have a
getExtraData() method that initially returns an empty object. This is the place to
add extra data to a tab node that will not be saved.
TabSet Attributes
Attributes allowed in nodes of type
"tabset".
Inherited defaults will take their value from the associated global attributes (see above).
Note: tabsets can be dynamically created as tabs are moved and deleted when all their tabs are removed (unless
enableDeleteWhenEmpty is
false).
Tab set nodes will use certain positioning, size and relative split variables depending on where it has been nested:
weightwhen nested inside
layout
width,
height,
x,
ywhen nested inside
floating
Border Attributes
Attributes allowed in nodes of type
"border".
Inherited defaults will take their value from the associated global attributes (see above).
Model Actions
All changes to the model are applied through actions. You can intercept actions resulting from GUI changes before they are applied by implementing the
onAction callback property of the
<Layout> component. You can also apply actions directly using the
Model.doAction() method.
Example
model.doAction(Actions.updateModelAttributes({ splitterSize: 40, tabSetHeaderHeight: 40, tabSetTabStripHeight: 40 }));
The above example would increase the size of the splitters, tabset headers and tabs. This could be used to make adjusting the layout easier on a small device.
Example:
model.doAction(Actions.addNode( { // Your new tab. type: "tab", component: "grid", name: "a grid", id: "5" }, "1", DropLocation.CENTER, 0 ));
This code would add a new grid component to the center of tabset with id "1" and at the
0'th tab position (use value
-1 to add to the end of the tabs).
Note: You can get the
id of a node using the method
node.getId(). If an
id wasn't assigned when the node was created, then one will be created for you of the form #\<next_available_id> (e.g. #1, #2 ...).
Layout Component Methods to Create New Tabs
Methods on the Layout Component for adding tabs. The tabs are specified by their layout configuration in json.
Example:
this.refs.layout.addTabToTabSet( "NAVIGATION", { // Your new tab. type: "tab", component: "grid", name: "a grid" } );
This would add a new grid component to the tabset with id "NAVIGATION".
Tab Node Events
You can handle events on nodes by adding a listener. This would typically be done in the class component's
constructor() method.
Example:
class Main extends Component { constructor(props) { super(props); let config = this.props.node.getConfig(); // save state in flexlayout node tree this.props.node.setEventListener("save", function (p) { config.subject = this.subject; }.bind(this)); } }
Building the Project
To compile the project just run webpack in the top level directory, this will compile and bundle flexlayout and the examples into the bundles dir. Once compiled the examples can be run by opening their index.html files.
To build the npm distribution run 'npm run build', this will create the artifacts in the dist dir. | https://npm.io/package/@andrewsantarin/extended-flexlayout-react | CC-MAIN-2022-40 | refinedweb | 2,048 | 55.64 |
* Serge E. Hallyn <[email protected]> wrote:> Quoting James Morris ([email protected]):> > On Tue, 9 Dec 2008, Ingo Molnar wrote:> > > > > > They're already published in my tree. Do you want me to revert them?> > > > > > I've also got it published :-/ If it's at the tail of your commits, can > > > you reset it?> > > > There have been commits since, and people are using the tree in any case.> > Yikes. Maybe it's best (henceforth) to keep user namespaces patches in > their own tree toward the end of linux-next? There certainly are > security implications with all of them, but other things (filesystem, > sched) will be impacted as well...i'm fine with having this in James's tree - i didnt realize that you had another commit that created dependencies.(if such situations ever cause real damage then we can always create a separate branch to track it cleanly. That's not needed now.) Ingo | https://lkml.org/lkml/2008/12/12/125 | CC-MAIN-2017-09 | refinedweb | 155 | 74.19 |
30 March 2009 11:00 [Source: ICIS news]
SINGAPORE (ICIS news)--Here is Monday’s end of day Asian oil and chemical market summary from ICIS pricing.
CRUDE: May WTI $50.53/bbl down $1.85 May BRENT $50.42/bbl down $1.56
Crude futures fell sharply on Monday in ?xml:namespace>
NAPHTHA: Asian naphtha prices closed softer Monday. First half May price indications were pegged at $459.00-460.00/tonne CFR (cost and freight) Japan, second half May at $453.00-454.00/tonne CFR Japan and first half June at $447.50-448.50/tonne CFR Japan.
BENZENE: Prices were stable-to-weak at $580-585/tonne FOB(free on board)
TOLUENE: Prices were notionally kept unchanged at $575. | http://www.icis.com/Articles/2009/03/30/9204111/evening+snapshot+-+asia+markets+summary.html | CC-MAIN-2013-20 | refinedweb | 123 | 80.28 |
HTML and CSS Reference
In-Depth Information
chapter 9
n n n
Dealing with Local Files Using
the File API
It's a well-known fact that for the sake of security and privacy, browsers don't allow web applications to
tamper with the local file system. Local files are used in a web application only when the user decides to
upload them to the server using the HTML <input> element of type file. The title of this chapter may
surprise you at first, because the term File API gives the impression of being a full-blown file-system
manipulation object model like the System.IO namespace of .NET Framework. Obviously, the people
behind HTML5 are aware of the security issues such an object model can create. So, the File API is
essentially a cut-down version of a file-handling system in which files can only be read and can't be
modified or deleted. Additionally, the File API can't read any random file on the machine. File(s) to be read
must be explicitly supplied by the user. Thus, the File API is a safe way to read and optionally upload local
files with user consent.
This chapter examines what the File API can do for you and how it can be used in ASP.NET web
applications. Specifically, you learn the following:
• Classes available as a part of the File API
• Techniques of selecting iles to be used with the File API
• Using HTML5 native drag-and-drop
• Reading iles with the File API
• Uploading iles to the server
Understanding the File API
The HTML5 File API consists of a set of three objects (see Table 9-1) that allow you to read files residing on
the client computer. The files to be read must be explicitly selected by the user using one of the supported
techniques discussed in later sections. Once selected, you can read the files using JavaScript code.
Search WWH ::
Custom Search | http://what-when-how.com/Tutorial/topic-524phdg/HTML5-Programming-for-ASPNET-Developers-227.html | CC-MAIN-2017-47 | refinedweb | 329 | 58.72 |
Post your Comment
on line exam
on line exam how we can upload the data on the server from any site
AJAX Line
AJAX Line
AJAX Community with a blog, forum and tutorials
Read full Description
objective c read file line by line
objective c read file line by line Please explain how to read files in Objective C line by line?
How to Read a file line by line using BufferedReader? Hello Java... to Read a file line by line using BufferedReader, efficiently and using less memory...
java.io.BufferedReader
in your program and use the class for reading the file line
Command line arguments
Command line arguments Please explain me what is the use of "command line arguments" and why we need to use
Line From code
Line From code document.getElementById("demo").innerHTML=Date();
Please explain each and every word in this line
Line Breaks in PHP
Line Breaks in PHP Hi,
I am beginner in PHP language. How to do the line-break in PHP? Does somebody help me in this regard.
Thanks
sorting Line in c
sorting Line in c Hi I need help with sorting line in programming c
asking user to enter 1-10 characters and then sort them in lower case, alphabetical and ascending order. Any help will be appreciated! please help!
void
divide the line in to two
divide the line in to two In| this |example |we| are| creating |an |string| object| .We| initialize| this| string |object| as| "Rajesh Kumar"|.| We| are| taking| sub| string |
In above mentioned line based on the tag i want
Line Number Reader Example
Line Number Reader Example
...; readLine()
method is used to read the data line by line. LineNumberReader class
is provide getLineNumber() method to get the number of line. We
Line Drawing - Swing AWT
Line Drawing How to Draw Line using Java Swings in Graph chart,by giving x & Y axis values Hi friend,
i am sending code of draw line...) {
System.out.println("Line draw example using java Swing");
JFrame frame = new
COMMAND LINE ARGUMENTS
COMMAND LINE ARGUMENTS JAVA PROGRAM TO ACCEPT 5 COMMAND LINE ARGUMENTS AND FIND THE SUM OF THAT FIVE.ALSO FIND OUT LARGEST AMONG THAT 5
Hi Friend,
Try the following code:
import java.util.*;
class
JBoss Unix and Line Separator
JBoss Unix and Line Separator Hi, I am trying to solve an critical problem. I have an application which write a batch file using the method println from the PrintWriter class from java api, this method uses the default line
Compiling package in command line
Compiling package in command line Hi friends,
i am totally new to java programming, i am basic learner in java.
My query is, How to compile java package using command line.
For Eg: When i compile following command,
c:>set
Java Read File Line by Line - Java Tutorial
Java Read File Line by Line - Example code of
reading the text file in Java one line at a time
... to
write java program to read file line by line. We will use the DataInputStream
Post your Comment | http://www.roseindia.net/discussion/32299-AJAX-Line.html | CC-MAIN-2014-15 | refinedweb | 514 | 66.37 |
One of the ways I use Jupyter notebooks is to write stream-of-consciousness code.
Whilst the code doesn’t include formal tests (I never got into the swing of test-driven development, partly because I’m forever changing my mind about what I need a particular function to do!) the notebooks do contain a lot of implicit testing as I tried to build up a function (see Programming in Jupyter Notebooks, via the Heavy Metal Umlaut for an example of some of the ways I use notebooks to iterate the development of code either across several cells or within a single cell).
The resulting notebooks tend to be messy in a way that makes it hard to reuse code contained in them easily. In particular, there are lots of parameter setting cells and code fragment cells where I test specific things out, and then there are cells containing functions that pull together separate pieces to perform a particular task.
So for example, in the fragment below, there is a cell where I’m trying something out, a cell where I put that thing into a function, and a cell where I test the function:
My notebooks also tend to include lots of markdown cells where I try to explain what I want to achieve, or things I still need to do. Some of these usefully document completed functions, others are more note form that relate to the development of an idea or act as notes-to-self.
As the notebooks get more cluttered, it gets harder to use them to perform a particular task. I can’t load the notebook into another notebook as a module because as well as loading the functions in, all the directly run code cells will be loaded in and then executed.
Jupytext comes partly to the rescue here. As described in Exploring Jupytext – Creating Simple Python Modules Via a Notebook UI, we can add
active-ipynb tags to a cell that instruct Jupytext where code cells should be executable:
In the case of the
active-ipynb tag, if we generate a Python file from a notebook using Jupytext, the
active-ipynb tagged code cells will be commented out. But that can still make for a quite a messy Python file.
Via Marc Wouts comes this alternative solution for using an
nbconvert template to strip out code cells that are tagged
active-ipynb; I’ve also tweaked the template to omit cell count numbers and only include markdown cells that are tagged
docs.
echo """{%- extends 'python.tpl' -%} {% block in_prompt %} {% endblock in_prompt %} {% block markdowncell scoped %} {%- if \"docs\" in cell.metadata.tags -%} {{ super() }} {%- else -%} {%- endif -%} {% endblock markdowncell %} {% block input_group -%} {%- if \"active-ipynb\" in cell.metadata.tags -%} {%- else -%} {{ super() }} {%- endif -%} {% endblock input_group %}""" > clean_py_file.tpl
Running
nbconvert using this template over a notebook:
jupyter nbconvert "My Messy Notebook.ipynb" --to script --template clean_py_file.tpl
generates a
My Messy Notebook.py file that includes code from cells not tagged as
active-ipynb, along with commented out markdown from
docs tagged markdown cells, that provides a much cleaner python module file.
With this workflow, I can revisit my old messy notebooks, tag the cells appropriately, and recover useful module code from them.
If I only ever generate (and never edit by hand) the module/Python files, then I can maintain the code from the messy notebook as long as I remember to generate the Python file from the notebook via the
clean_py_file.tpl template. Ideally, this would be done via a Jupyter content manager hook so that whenever the notebook was saved, as per Jupytext paired files, the clean Python / module file would be automatically generated from it.
Just by the by, we can load in Python files that contain spaces in the filename as modules into another Python file or notebook using the formulation:
tsl = __import__('TSL Timing Screen Screenshot and Data Grabber')
and then call functions via
tsl.myFunction() in the normal way. If running in a Jupyter notebook setting (which may be a notebook UI loaded from a
.py file under Jupytext) where the notebook includes the magics:
%load_ext autoreload %autoreload 2
then whenever a function from a loaded module file is called, the module (and any changes to it since it was last loaded) are reloaded.
PS thinks… it’d be quite handy to have a simple script that would autotag all notebook cells as
active-ipynb; or perhaps just have another template that ignores all code cells not tagged with something like
active-py or
module-py. That would probably make tag gardening in old notebooks a bit easier… | https://blog.ouseful.info/tag/jupytext/ | CC-MAIN-2019-51 | refinedweb | 764 | 63.63 |
Subsets and Splits