Re: Lies in education [was Re: The "loop and a half"]
Grant Edwards : > I like [const qualifiers] in C because it allows the linker to place > them in ROM with the code. It also _sometimes_ provides useful > diagnostics when you pass a pointer to something which shouldn't be > modified to something that is going to try to modify it. Unfortunately, "const" is so tacky in practice that the language and the standard libraries have rendered it useless. One example is the surprising fact that string literals in C are "char *" and not "const char *". Additionally, you can launder any constant string into a nonconstant string with strstr(3): const char *cs = "hello"; char *s = strstr(cs, ""); s[0] = 'y'; Also, you'd expect execve(2) to take in: const char *const argv[] Instead, it wants: char *const argv[] which makes little semantic sense. The reason for all of this weirdness is that the proper use of "const" in C is very painful to do: you have to sprinkle your code with explicit casts. Tons of legacy code would be riddled with compiler error messages. The solution was to pay lip service to "const." It would have been better not to import "const" into the language. (C++ has its own special issue with "const," which forced C++ to introduce the ugly concept of const_cast<>().) Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Marko Rauhamaa wrote: Grant Edwards : I like [const qualifiers] in C because it allows the linker to place them in ROM with the code. It also _sometimes_ provides useful diagnostics when you pass a pointer to something which shouldn't be modified to something that is going to try to modify it. Unfortunately, "const" is so tacky in practice that the language and the standard libraries have rendered it useless. One example is the surprising fact that string literals in C are "char *" and not "const char *". If not, you couldn't pass a string literal to a function having prototype void f(char *s); Of course, if f tries to modify *s, there will be a run time error as character string literals are stored in a "special place", and are not mutable. This improves performance. -- https://mail.python.org/mailman/listinfo/python-list
Want to write a python code for sending and receiving frames over wifi/wlan0 using python
Hello all, I want to send some frames defined by me{Example, [0x45,0x43,0x32]} to the raspberry pi from any macine(Desktop/Laptop/other raspberry pi). But I want to send those frames over wifi or use wlan0 using python Any suggestions? -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On Thu, Oct 12, 2017 at 6:22 PM, Marko Rauhamaa wrote: > Grant Edwards : > >> I like [const qualifiers] in C because it allows the linker to place >> them in ROM with the code. It also _sometimes_ provides useful >> diagnostics when you pass a pointer to something which shouldn't be >> modified to something that is going to try to modify it. > > Unfortunately, "const" is so tacky in practice that the language and the > standard libraries have rendered it useless. > > One example is the surprising fact that string literals in C are "char > *" and not "const char *". Additionally, you can launder any constant > string into a nonconstant string with strstr(3): > > const char *cs = "hello"; > char *s = strstr(cs, ""); > s[0] = 'y'; Well hey, if you want that, you can just cast the pointer. C is not about preventing you from doing things. The 'const' keyword is a useful protection (and one that would be more useful if string literals were const), but it's not meant to be a straitjacket. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Want to write a python code for sending and receiving frames over wifi/wlan0 using python
On 12/10/2017 09:08, T Obulesu wrote: Hello all, I want to send some frames defined by me{Example, [0x45,0x43,0x32]} to the raspberry pi from any macine(Desktop/Laptop/other raspberry pi). But I want to send those frames over wifi or use wlan0 using python Any suggestions? Are you talking about literal network frames? https://en.wikipedia.org/wiki/Frame_(networking) Or merely data which represents some kind of "frame" in your application? ie are you looking for low-level control of the network device? Or merely a way to transmit data across a network generally? TJG -- https://mail.python.org/mailman/listinfo/python-list
Re: Want to write a python code for sending and receiving frames over wifi/wlan0 using python
On Thu, Oct 12, 2017 at 7:08 PM, T Obulesu wrote: > Hello all, I want to send some frames defined by me{Example, > [0x45,0x43,0x32]} to the raspberry pi from any macine(Desktop/Laptop/other > raspberry pi). But I want to send those frames over wifi or use wlan0 using > python Any suggestions? > -- Since you use the word "frame", I'm thinking you possibly mean at a very low level, and not packaged up into UDP/IP packets. I'm curious as to why you'd need that; for most purposes, the easiest way would be either TCP or UDP. But sending raw packets is entirely possible in Python - though you have to bear in mind that many OSes restrict this capability to administrative programs. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Am 12.10.17 um 01:15 schrieb Stefan Ram: Define a function »g« with a parameter »x« of type »int«, so that this function »g« returns a pointer to another function. This other function has a parameter of type »char« and returns a double value. Ok /Without/ a typedef. And WHY would you do that? Typedefs do not cost money. Try this: typedef double (*countdown_rate_func) (char letter); countdown_rate_func select_rate_func(int level); // I've substituted 'x' by 'level' // and 'g' by 'select_rate_func' for clarity I claim that the above is quite clear, it declares a function in a Countdown game engine, which, depending on the level, returns a different function to rate the weight of the individual letters. Your exercise results in the line noise double (*g(int x))(char) (thanks to Ben for doing the exercise), which is not extremely bad, but still does tell nothing about the intent of that line. Writing the typedef is easy for humans, stick * in front of the function name for a regular declaration and add (). The compiler can then figure out the complete type on its own, it's its job, not mine. Christian -- https://mail.python.org/mailman/listinfo/python-list
Re: Logging from files doesn't work
Andrew Z wrote: > Hello, > > apparently my reading comprehension is nose diving these days. After > reading python cookbook and a few other tutorials i still can't get a > simple logging from a few files to work. > I suspected my file organization - all files are in the same directory, > causing problem. But it appears it is not. > > Anyway, in the example below, only logging from main.py works. I also want > to have login from "test1/test.py" to write into the same common log file. > > And how can i accomplish the same if test.py is in the same directory as > main.py? > > dir structure: > src/ > |- main.py > |-test/ Shouldn't that be |-test1/ ? > |-test.py > > code: > test.py: > > import logging > # neither of below produce any results > > log = logging.getLogger("test1.test") > # log = logging.getLogger(__name__) > > def fun(): >print("DADADA") >log.debug(" DADADADA " ) > > > main.py: > > from test1.test import fun > > def main(): > >log = logging.getLogger(__name__) >log.setLevel(logging.DEBUG) > >fh = logging.FileHandler("nja_" + > datetime.now().strftime("%Y_%b_%d_%H_%M_%S") +".log") >formatter = logging.Formatter('%(levelname)s - %(asctime)s - > %(funcName)10s() %(lineno)s - %(message)s') >fh.setFormatter(formatter) >log.addHandler(fh) > >log.debug("Yes, this line is in the log file") > >fun() > >log.debug("And this one is too") You have already worked out why the names are what they are. You can avoid the problem if you attach the handler to the root logger, e. g. def main(): root_log = logging.getLogger() root_log.setLevel(logging.DEBUG) fh = logging.FileHandler( "nja_" + datetime.now().strftime("%Y_%b_%d_%H_%M_%S") +".log" ) formatter = logging.Formatter( '%(levelname)s - %(asctime)s - %(funcName)10s()' '%(lineno)s - %(message)s' ) fh.setFormatter(formatter) root_log.addHandler(fh) log = logging.getLogger(__name__) log.debug("Yes, this line is in the log file") fun() log.debug("And this one is too") "And this one is too") That way you can capture messages from the whole hierarchy regardless of its actual layout. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12 01:32, Christopher Reimer wrote: > On Oct 11, 2017, at 9:07 AM, Bill wrote: >> >> Grant Edwards wrote: >>> On 2017-10-11, Bill wrote: >>> >>> [...] I'm not here to "cast stones", I like Python. I just think that you shouldn't cast stones at C/C++. >>> Not while PHP exists. There aren't enough stones in the world... >>> >> >> PHP seems (seemed?) popular for laying out web pages. Are their vastly >> superior options? I'm a little naive in this matter, thus my question. >> -- >> https://mail.python.org/mailman/listinfo/python-list > > AFAIK, JavaScript frameworks has largely replaced PHP. I personally use > Pelican to generate static web pages and use JavaScript sparingly. "Remember Ruby on Rails?" -- Thomas Jollans -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: MPC-HC project ending? [Re: Lies in education [was Re: The "loop and a half"]]
On 2017-10-12 02:51, Chris Angelico wrote: > If it wants new life, it's probably going to need a Linux version, > because that's where a lot of developers hang out. The reality is that > open source developers are much more likely to develop on Linux than > on Windows; you can maintain a Windows port of a Linux program with > fewer Windows experts than maintaining the entire program on Windows. > > The other option, though, would be for the useful parts to become > feature suggestions for VLC. It's the year of the Linux desktop! (No, actually, that was a few years ago, but nobody noticed at the time) -- Thomas Jollans -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Bill : > Marko Rauhamaa wrote: >> One example is the surprising fact that string literals in C are >> "char *" and not "const char *". > > If not, you couldn't pass a string literal to a function having > prototype void f(char *s); That *ought* to be prevented. That's the whole point. Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12 01:33, Chris Angelico wrote: > Have you seen a city that grew one house at a time, and had > streets added to service those houses? Not good. Actually, that's more or less how most cities grew historically. Nowadays these organically grown city centres tend to be much more people-friendly than "modern" cities (mis-)designed around the road and the motorcar. Of course they've had centuries to mature. They've seen constant maintenance and refactoring (fortifying the city, digging canals, moving fortifications to accommodate growth, building railway lines, replacing key canals with roads, ...) to adapt to changing demands and challenges of the environment. Yes, yes, there are plenty of examples of cities with more recent histories of ad hoc growth that don't function as well as London, Budapest or Jerusalem - yet. No, the comparison is not relevant. For starters, people tend to care more about their home than about their PHP code. -- Thomas Jollans -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Chris Angelico : > On Thu, Oct 12, 2017 at 6:22 PM, Marko Rauhamaa wrote: >> Additionally, you can launder any constant string into a nonconstant >> string with strstr(3): >> >> const char *cs = "hello"; >> char *s = strstr(cs, ""); >> s[0] = 'y'; > > Well hey, if you want that, you can just cast the pointer. Point is, there is no legitimate way to implement the strstr(3) prototype. Somebody must be lying through their teeth. The idea of "const" (and other type declaration paraphernalia) is to prevent accidental bugs at compile time. The noble idea of "const" has been undermined by its sloppy use by the standard libraries and the language itself. BTW, C++ tries to be a bit stricter about "const". It declares two separate prototypes: const char *strstr(const char *, const char *); char *strstr(char *, const char *); http://www.cplusplus.com/reference/cstring/strstr/> Also, in C++, string literals are "const char *". Marko -- https://mail.python.org/mailman/listinfo/python-list
how to replace maltipal char from string and substitute new char
Hi Team, How to replace multipal char from string and substitute with new char with one line code Ex: str = "9.0(3)X7(2) " ===> 9.0.3.X7.2 need to replace occurrence of '(',')' with dot(.) chars output: 9.0.3.X7.2 Thanks, -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 12/10/2017 09:23, Christian Gollwitzer wrote: Am 12.10.17 um 01:15 schrieb Stefan Ram: Define a function »g« with a parameter »x« of type »int«, so that this function »g« returns a pointer to another function. This other function has a parameter of type »char« and returns a double value. Ok /Without/ a typedef. And WHY would you do that? Typedefs do not cost money. They cost extra effort in devising them, writing them, and having to trace them when someone else is reading the code. Try this: typedef double (*countdown_rate_func) (char letter); countdown_rate_func select_rate_func(int level); // I've substituted 'x' by 'level' // and 'g' by 'select_rate_func' for clarity Those substitutions don't help, as I'm trying to see how well it matches the original spec. If I change them back (not easy to tell which bit is whic): typedef double (*F) (char); F g(int x); No, sorry, it doesn't really cut it. It is still cryptic. It doesn't help that C doesn't use a keyword to introduce a function (like, say, 'function'). You still need to know that double (*F) is a pointer to a function returning double, and that double *F is a function returning a pointer to a double. It also introduces this arbitrary name 'F', which if you encounter it in source, means you know have to search for this typedef. (And the requirement was a definition not a declaration.) I claim that the above is quite clear, it declares a function in a Countdown game engine, which, depending on the level, returns a different function to rate the weight of the individual letters. Renaming 'g' and 'x' to be more meaningful, and introducing a parameter name that is not needed, is a different subject. And actually I found your 'countdown_rate_func' and 'select_rate_func' names confusing (the two are actually of different rank, but both end in _func). Your exercise results in the line noise double (*g(int x))(char) (thanks to Ben for doing the exercise), which is not extremely bad, but still does tell nothing about the intent of that line. Using any sane syntax for type (AND function) declarations, writing Stefan's function is straightforward. For example**: function g(int x) => ref function(char)real = return nil end Just transcribed exactly as written (I could have used 'x:int' maybe). If I translate this to C, then it gives me: static double (*g(int32 x)) (char) { return 0; } It's a piece of cake. It shows how important the right syntax can be; you write what you have to write, then get on with the rest of the coding. Oh, and it's also very easy to read. It's a mystery to me actually; there is zero cost to devising, implementing and using the most helpful syntax, and actually there are real benefits. So why use something so bizarre? (**This is my actual language but as someone guessed, this part is derived from Algol68.) -- bartc -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 12/10/2017 06:39, Grant Edwards wrote: On 2017-10-11, Gregory Ewing wrote: Neil Cerutti wrote: I dig const qualifiers, even though I'm comletely fine with their absence from Python. Out of curiosity, do you have any insights into why you like them in C++, if you don't miss them in Python? I like them in C because it allows the linker to place them in ROM with the code. It also _sometimes_ provides useful diagnostics when you pass a pointer to something which shouldn't be modified to something that is going to try to modify it. It's one of these features that on paper sound good. In practice, it's just useless extra clutter. It's used to: (1) Define named constants; except (in C) they can't be used like constant expressions, you can take their addresses, and accidentally or maliciously change their values. (2) Declare data to be put into read-only memory as you say. That's fine with a 'const int * p', but what about a 'int * const p'? (Or is it the other way around? Whatever...). Or any other hybrid type where some elements are const and some aren't. (3) Pass data that is supposed to be read-only, but with any even slightly complex type, it won't work (the head of a linked list for example, where the node elements need to be writeable). It gives a false sense of security. -- bartc -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12 07:31, Chris Angelico wrote: > On Thu, Oct 12, 2017 at 12:19 PM, Ben Bacarisse wrote: >> Provided some early part of the URL is handled by PHP, the rest of the >> URL path is provided to PHP in $_SERVER["PATH_INFO"]. > > Is it possible to do that without having ".php" visible in the path? Just like with Python-based frameworks, this requires a few lines of web server configuration. On Apache, you might use mod_wsgi to tell the server how to run the code in one case, and a combination of mod_php and mod_rewrite in the other. If you're using FastCGI with nginx or lighttpd, I believe the configuration would look pretty similar in both cases. Then again, I don't do much web programming any more and generally stay away from PHP, so I may be misremembering. -- Thomas Jollans -- https://mail.python.org/mailman/listinfo/python-list
FW: Printing to a file and a terminal at the same time
It wouldn't be too difficult to write a file object wrapper that emulates tee, for instance (untested): class tee(object): def __init__(self, file_objs, autoflush=True): self._files = file_objs self._autoflush = autoflush def write(self, buf): for f in self._files: f.write(buf) if self._autoflush: self.flush() def flush(self): for f in self._files: f.flush() use like so: sys.stdout = tee([sys.stdout, open("myfile.txt", "a")]) Another approach is by bsandrow (https://github.com/bsandrow/pytee), which uses fork and os.pipe(), this more closely resembles what the actual tee command are actually doing. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Chris Angelico writes: > On Thu, Oct 12, 2017 at 12:19 PM, Ben Bacarisse wrote: >> Chris Angelico writes: >> >>> On Thu, Oct 12, 2017 at 11:55 AM, Ben Bacarisse >>> wrote: Chris Angelico writes: > it binds your URLs to > the concrete file system. That may not seem like too much of a > problem, but it's a pretty big limitation; you can't have URLs like > "https://en.wikipedia.org/wiki/Foo"; without some help from the web > server, eg Apache's mod_rewrite. I don't follow this. Your "can't" and "big limitation" suggests something inevitable, but I don't see it as an intrinsic problem with the language. I'm sure PHP is not as flexible as the frameworks you mention, but you are not tied to URLs mapping to files. Maybe you meant that this is what often happens, or what most people do, with PHP. >>> >>> How would you, with PHP itself, handle database-provided URLs? The >>> only way I've ever seen it done is at an external level - such as >>> mod_rewrite - which means that someone else, *not* the PHP script, is >>> managing your URLs. They're pushed to some external config file >>> somewhere. That's okay for just one URL pattern, but it doesn't scale >>> well, which is why (for example) Wikipedia's editing pages are >>> "/w/index.php?" instead of, say, "/wiki/Foo/edit" or >>> "/wiki/edit/Foo". >>> >>> Unless you know something I don't? >> >> Provided some early part of the URL is handled by PHP, the rest of the >> URL path is provided to PHP in $_SERVER["PATH_INFO"]. > > Is it possible to do that without having ".php" visible in the path? Yes, though because that will depend on how the server is configured I should perhaps say "usually yes"! -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Why the CLI hang using pyjwt ?
Not sure why the CLI command "pyjwt decode --no-verify ..." will hang at sys.stdin.read() even though I provided all the input. Any ideas on how to work around the problem? $ pyjwt -v pyjwt 1.5.3 $ pyjwt decode --no-verify eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg ^CTraceback (most recent call last): File "/usr/local/bin/pyjwt", line 11, in sys.exit(main()) File "/usr/local/lib/python2.7/dist-packages/jwt/main.py", line 157, in main output = arguments.func(arguments) File "/usr/local/lib/python2.7/dist-packages/jwt/main.py", line 58, in decode_payload token = sys.stdin.read() $ pyjwt decode --no-verify eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg ^CTraceback (most recent call last): File "/Users/v612996/anaconda/bin/pyjwt", line 11, in sys.exit(main()) File "/Users/v612996/anaconda/lib/python3.6/site-packages/jwt/main.py", line 157, in main output = arguments.func(arguments) File "/Users/v612996/anaconda/lib/python3.6/site-packages/jwt/main.py", line 58, in decode_payload token = sys.stdin.read() KeyboardInterrupt $ python --version Python 3.6.0 :: Anaconda custom (x86_64) But the same token decoded perfectly under python 2.6 interpreter: jwt.decode(encoded,verify=False) {u'some': u'payload'} What is the work around of "pyjwt decode --no-verify" hang in the CLI? -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On Thu, Oct 12, 2017 at 7:32 PM, Thomas Jollans wrote: > On 2017-10-12 07:31, Chris Angelico wrote: >> On Thu, Oct 12, 2017 at 12:19 PM, Ben Bacarisse wrote: >>> Provided some early part of the URL is handled by PHP, the rest of the >>> URL path is provided to PHP in $_SERVER["PATH_INFO"]. >> >> Is it possible to do that without having ".php" visible in the path? > > Just like with Python-based frameworks, this requires a few lines of web > server configuration. > > On Apache, you might use mod_wsgi to tell the server how to run the code > in one case, and a combination of mod_php and mod_rewrite in the other. > If you're using FastCGI with nginx or lighttpd, I believe the > configuration would look pretty similar in both cases. > > Then again, I don't do much web programming any more and generally stay > away from PHP, so I may be misremembering. Normally, with a Python-based framework, you don't need _any_ web server configuration. You simply define your URL routing within the Python code. The only thing the web server needs to know is where to find the web app, and that's sufficiently standard that it can be done off-the-shelf; for instance, you push your code to Heroku, and they set everything up to pass requests to your app. Not possible with PHP, since you need *custom* web server config to manage your rewrite rules. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On Thu, Oct 12, 2017 at 8:20 PM, Marko Rauhamaa wrote: > Chris Angelico : > >> On Thu, Oct 12, 2017 at 6:22 PM, Marko Rauhamaa wrote: >>> Additionally, you can launder any constant string into a nonconstant >>> string with strstr(3): >>> >>> const char *cs = "hello"; >>> char *s = strstr(cs, ""); >>> s[0] = 'y'; >> >> Well hey, if you want that, you can just cast the pointer. > > Point is, there is no legitimate way to implement the strstr(3) > prototype. Somebody must be lying through their teeth. > > The idea of "const" (and other type declaration paraphernalia) is to > prevent accidental bugs at compile time. The noble idea of "const" has > been undermined by its sloppy use by the standard libraries and the > language itself. > > BTW, C++ tries to be a bit stricter about "const". It declares two > separate prototypes: > >const char *strstr(const char *, const char *); >char *strstr(char *, const char *); > > http://www.cplusplus.com/reference/cstring/strstr/> > > Also, in C++, string literals are "const char *". So basically, C++ fixed some problems in C, in the same way that Python 3 fixed some problems in Python 2. Yet for some reason Python 3 is killing Python, but C++ isn't killing C. Not sure how that works. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: MPC-HC project ending? [Re: Lies in education [was Re: The "loop and a half"]]
On Thu, Oct 12, 2017 at 8:12 PM, Thomas Jollans wrote: > On 2017-10-12 02:51, Chris Angelico wrote: >> If it wants new life, it's probably going to need a Linux version, >> because that's where a lot of developers hang out. The reality is that >> open source developers are much more likely to develop on Linux than >> on Windows; you can maintain a Windows port of a Linux program with >> fewer Windows experts than maintaining the entire program on Windows. >> >> The other option, though, would be for the useful parts to become >> feature suggestions for VLC. > > > It's the year of the Linux desktop! > > (No, actually, that was a few years ago, but nobody noticed at the time) I'm typing this up from my primary Linux system. Beside me, my laptop also runs Linux. I use these computers for basically everything - coding, testing, work, gaming, the lot. Just finished playing an episode of The Walking Dead, streamed to Twitch.tv; yes, that game wasn't released for Linux, but thanks to Wine, I can run the Windows version, and it's flawless. It's the year of the Linux desktop alright. Has been for some time, gonna still be for a while yet. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 12/10/2017 11:39, Stefan Ram wrote: bartc writes: (1) Define named constants; except (in C) they can't be used like constant expressions, you can take their addresses, and accidentally or maliciously change their values. When I think of »const«, I do not think of ROM. »const« makes code more readable, because it conveys the intentions of the author and simplifies the mental variable model of the reader. »const« helps to find inadvertend modifications. void f( const int i ){ if( i = 4 )putchar( 'x' ); } That's two undesirable language features: (1) Having to use 'const' in front of every simple parameter, so that 'const' now dominates every program; (2) Mixing up '=' and '=='. You're saying it's OK to use both as they sort of cancel each other out! (Other languages solve the =/== problem by either not allowing assignment within an expression, or by using a symbol for it that isn't so easily mistaken for equality.) -- bartc -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On Thu, 12 Oct 2017 04:41 pm, Grant Edwards wrote: >> Even two >> different C compilers could return different values. > > Nope. If sizeof char is not 1, then it's not C. Today I Learned. Thank you to everyone who corrected me, even the person who said I was not educated. -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: how to replace maltipal char from string and substitute new char
On Thursday, October 12, 2017 at 10:46:03 AM UTC+1, Iranna Mathapati wrote: > Hi Team, > > > How to replace multipal char from string and substitute with new char with > one line code > > Ex: > > str = "9.0(3)X7(2) " ===> 9.0.3.X7.2 > > need to replace occurrence of '(',')' with dot(.) chars > > output: > > 9.0.3.X7.2 > > > Thanks, >>> help(str.replace) replace(...) S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. Hence:- >>> '9.0(3)X7(2)'.replace('(','.').replace(')', '.') '9.0.3.X7.2.' -- Kindest regards. Mark Lawrence. -- https://mail.python.org/mailman/listinfo/python-list
Re: Want to write a python code for sending and receiving frames over wifi/wlan0 using python
On Thursday, 12 October 2017 13:38:55 UTC+5:30, T Obulesu wrote: > Hello all, I want to send some frames defined by me{Example, > [0x45,0x43,0x32]} to the raspberry pi from any macine(Desktop/Laptop/other > raspberry pi). But I want to send those frames over wifi or use wlan0 using > python Any suggestions? Yes.. Actully we are sending and receiving ZigBee frames through the serial port. But I want to do the same thing through the Ethernet port/ Wlan0 port rather serial port. My Zigbee Frame Format looks like this: 0x7EA88X00S8899800131A2000 My setup is as follows: My raspberry pi and my laptop both are connected to the same WiFi and ports are wlan0. And it can be directly connected to the laptop using Ethernet cable. If this is the case, I wnat to change the port to the eth0 and send the packets -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: MPC-HC project ending? [Re: Lies in education [was Re: The "loop and a half"]]
On Thursday, October 12, 2017 at 12:33:09 PM UTC+1, Chris Angelico wrote: > On Thu, Oct 12, 2017 at 8:12 PM, Thomas Jollans wrote: > > On 2017-10-12 02:51, Chris Angelico wrote: > >> If it wants new life, it's probably going to need a Linux version, > >> because that's where a lot of developers hang out. The reality is that > >> open source developers are much more likely to develop on Linux than > >> on Windows; you can maintain a Windows port of a Linux program with > >> fewer Windows experts than maintaining the entire program on Windows. > >> > >> The other option, though, would be for the useful parts to become > >> feature suggestions for VLC. > > > > > > It's the year of the Linux desktop! > > > > (No, actually, that was a few years ago, but nobody noticed at the time) > > I'm typing this up from my primary Linux system. Beside me, my laptop > also runs Linux. I use these computers for basically everything - > coding, testing, work, gaming, the lot. Just finished playing an > episode of The Walking Dead, streamed to Twitch.tv; yes, that game > wasn't released for Linux, but thanks to Wine, I can run the Windows > version, and it's flawless. > > It's the year of the Linux desktop alright. Has been for some time, > gonna still be for a while yet. > > ChrisA I have to agree as I've now moved to Linux, Ubuntu as it happens. I wish I'd done it years ago as it feels as if I've had a major hardware upgrade as it's so much more responsive. The most noticeable thing is that when watching videos from YouTube the sound and picture always stay in sync. Not a chance of that with Windows 10. -- Kindest regards. Mark Lawrence. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Chris Angelico : > On Thu, Oct 12, 2017 at 8:20 PM, Marko Rauhamaa wrote: >> BTW, C++ tries to be a bit stricter about "const". It declares two >> separate prototypes: >> >>const char *strstr(const char *, const char *); >>char *strstr(char *, const char *); >> >> http://www.cplusplus.com/reference/cstring/strstr/> >> >> Also, in C++, string literals are "const char *". > > So basically, C++ fixed some problems in C, in the same way that > Python 3 fixed some problems in Python 2. Yet for some reason Python 3 > is killing Python, but C++ isn't killing C. Not sure how that works. I have bitten the bullet and do my Python development in Python3. There's no going back. As far as C++ goes, though, it didn't succeed in becoming the "fulfillment" of C programming. In fact, it started a whole new religion. C and C++ share the same Old Testament but have completely different virtues and tenets. I'm not convinced by the tenets of C++. Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Gregory Ewing writes: > Ben Bacarisse wrote: >> That's a different type. I think you mean that a human writing C >> (rather than bartc's code generator) would probably design the code to >> use tokenrec ** then I agree, but the latter is not just a different way >> to write the former. > > Yes, I was translating his English description of the type > into C, using C's meaning of the word "array". It seems that > arrays in the original language (Algol? One of Bart's > inventions?) are somewhat richer things. Probably, but you can have pointers to array types in C which is what the posted type used. Humans pass arrays in C by passing a pointer to the first element. Pointers to arrays therefore crop up when passing 2D (or higher) arrays, even when the code is hand written by a person. -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Re: how to replace multiple char from string and substitute new char
On Thu, Oct 12, 2017, Iranna Mathapati wrote: > >Hi Team, > > >How to replace multipal char from string and substitute with new char with >one line code > >Ex: > >str = "9.0(3)X7(2) " ===> 9.0.3.X7.2 > >need to replace occurrence of '(',')' with dot(.) chars > >output: > > 9.0.3.X7.\ My first gut response was to key on the words "replace" and "string" and think there is a very handy method already existing that can help with that. It would be one line of code, if you don't mind having wo function calls in that one line of code. If you want only one function call and you want to do even more substitutions than just those below, there is another handy functionin the string object that can do so very nicely. What did you try? Roger Christman Pennsylvania State University -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-11, Gregory Ewing wrote: > Neil Cerutti wrote: >> I dig const qualifiers, even though I'm comletely fine with >> their absence from Python. > > Out of curiosity, do you have any insights into why you like > them in C++, if you don't miss them in Python? I can tell at a glance if a parameter is expected to be modifiable just by looking at the function signature. Also using reference types feels more comfortable when it's easy to know it won't be changed. This isn't technical, but it feels somehow satifying the way const propogates seemlessly through a well-designed interface. When programming Python, the only constants I care about are magic numbers and lookup tables defined at the top of a program or outside the program. If there are enough of them I'll put them in a module or class/namespace. They don't exist in interfaces, so I don't think about them in that sense. -- Neil Cerutti -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12, Marko Rauhamaa wrote: > Bill : > >> Marko Rauhamaa wrote: >>> One example is the surprising fact that string literals in C >>> are "char *" and not "const char *". >> >> If not, you couldn't pass a string literal to a function >> having prototype void f(char *s); > > That *ought* to be prevented. That's the whole point. I'm far less experienced in C, but I threw up my hands and stopped bothering with const qualifiers in C due to such headaches. When in Rome, program without const qualifiers in C. -- Neil Cerutti -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12 14:01, Stefan Ram wrote: > Many of the quotations are from the previous decade. Thanks Stefan, that was fun. > I must say that C++ has improved in this decade (the 2010s), > and there also is a rennaisance of C and C++ (compared to > "coffee languages") usage because single-thread processor > speeds do not grow anymore ("the free lunch is over") and so > in the 2010s C and C++ are more valued as efficiency > languages (also saving energy in the data centers). This is precisely the motivation of languages like Rust, Go and (in a way) Julia: "C++ is horrid, but C is a slog. Python is too slow for [insert specific use case]. There has to be a better way!" -- Thomas Jollans -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Chris Angelico writes: > On Thu, Oct 12, 2017 at 7:32 PM, Thomas Jollans wrote: >> On 2017-10-12 07:31, Chris Angelico wrote: >>> On Thu, Oct 12, 2017 at 12:19 PM, Ben Bacarisse >>> wrote: Provided some early part of the URL is handled by PHP, the rest of the URL path is provided to PHP in $_SERVER["PATH_INFO"]. >>> >>> Is it possible to do that without having ".php" visible in the path? >> >> Just like with Python-based frameworks, this requires a few lines of web >> server configuration. >> >> On Apache, you might use mod_wsgi to tell the server how to run the code >> in one case, and a combination of mod_php and mod_rewrite in the other. >> If you're using FastCGI with nginx or lighttpd, I believe the >> configuration would look pretty similar in both cases. >> >> Then again, I don't do much web programming any more and generally stay >> away from PHP, so I may be misremembering. > > Normally, with a Python-based framework, you don't need _any_ web > server configuration. You simply define your URL routing within the > Python code. The only thing the web server needs to know is where to > find the web app, and that's sufficiently standard that it can be done > off-the-shelf; for instance, you push your code to Heroku, and they > set everything up to pass requests to your app. Not possible with PHP, > since you need *custom* web server config to manage your rewrite > rules. That's at odds with what I've read online which admittedly may be all junk. I wanted to try Flask so I installed the Ubuntu packages but then got stuck on a huge document that suggested I needed to install things called Nginx and Gunicorn. You've now mentioned another: Heroku. I'm sure the complex instructions I found are not really required -- it was probably just the usual "this is what I did so this is how it's done" document, but I'm having trouble finding the simpler way to do it. Since no web server configuration is needed (I have a working Apache installation that mirrors, as closely as possible, what my hosting provider uses) it should be relatively easy. Can you tell me, or can you point me to a resource that tells me, where to put the app? I don't yet know what "push your code to Heroku" means. -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On Thu, 12 Oct 2017 11:01 pm, Stefan Ram quoted: > Basically I got sick of every single > aspect of C++ being designed around higher performance > instead of my productivity. Unlike C, where every single aspect of the language is designed around higher performance instead of the developer's productivity. > [...] If I had to write a > high performance application these days I would reach > for C. -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12, Ben Bacarisse wrote: > Chris Angelico writes: >> Normally, with a Python-based framework, you don't need _any_ web >> server configuration. You simply define your URL routing within the >> Python code. The only thing the web server needs to know is where to >> find the web app, and that's sufficiently standard that it can be done >> off-the-shelf; for instance, you push your code to Heroku, and they >> set everything up to pass requests to your app. Not possible with PHP, >> since you need *custom* web server config to manage your rewrite >> rules. > > That's at odds with what I've read online which admittedly may be all > junk. I wanted to try Flask so I installed the Ubuntu packages but then > got stuck on a huge document that suggested I needed to install things > called Nginx and Gunicorn. You've now mentioned another: Heroku. I'm > sure the complex instructions I found are not really required -- it was > probably just the usual "this is what I did so this is how it's done" > document, but I'm having trouble finding the simpler way to do it. > > Since no web server configuration is needed (I have a working Apache > installation that mirrors, as closely as possible, what my hosting > provider uses) it should be relatively easy. Can you tell me, or can > you point me to a resource that tells me, where to put the app? I don't > yet know what "push your code to Heroku" means. "don't need _any_ web server configuration" is rather, er, optimistic. For Apache you'd need the mod_proxy_uwsgi module installed, and the config would be something like this: DocumentRoot /srv/www/appname/appname ProxyPass uwsgi://127.0.0.1:3031/ ProxyPass ! and you need an app container listening on the port defined above, e.g. uwsgi with config like: /etc/uwsgi/apps-available/appname.ini: [uwsgi] plugin = python3 socket = 127.0.0.1:3031 threads = 4 master = 1 chdir = /srv/www/appname module = appname:app # https://github.com/unbit/uwsgi/issues/1126 wsgi-disable-file-wrapper = true and you'll need something to run uwsgi on system startup. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12, Neil Cerutti wrote: > On 2017-10-12, Marko Rauhamaa wrote: >> Bill : >> >>> Marko Rauhamaa wrote: One example is the surprising fact that string literals in C are "char *" and not "const char *". Yep, that's the basis for a lot of the problems with 'const' in C. Unfortunately for historical reasons, a lot of people expect string literals to be mutable. That should have been stamped out decades ago, but it's too late now. >>> If not, you couldn't pass a string literal to a function >>> having prototype void f(char *s); IMO, it should be illegal to pass a string literal to a function with prototype f(char *s). You shouldn't try to modify a string literal, and if f() isn't going to modify the string, it should have been declared f(const char *s). >> That *ought* to be prevented. That's the whole point. > > I'm far less experienced in C, but I threw up my hands and stopped > bothering with const qualifiers in C due to such headaches. When in > Rome, program without const qualifiers in C. Using const with strings in C with amateurish libraries is a headache because _some_people_ will write their declarations so as to require pointers to mutable strings even when they have no intention of mutating them. Those people should be hunted down and slapped with a herring until they understand the error of their ways. The standard library is much better about that. -- Grant Edwards grant.b.edwardsYow! Kids, don't gross me at off ... "Adventures with gmail.comMENTAL HYGIENE" can be carried too FAR! -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12, Marko Rauhamaa wrote: > Chris Angelico : > >> On Thu, Oct 12, 2017 at 6:22 PM, Marko Rauhamaa wrote: >>> Additionally, you can launder any constant string into a nonconstant >>> string with strstr(3): >>> >>> const char *cs = "hello"; >>> char *s = strstr(cs, ""); >>> s[0] = 'y'; >> >> Well hey, if you want that, you can just cast the pointer. > > Point is, there is no legitimate way to implement the strstr(3) > prototype. Somebody must be lying through their teeth. That's indeed a problem. Personally, I would just use two prototypes: char *strcstr(const char *s, char *s); const char *cstrstr(const char *s, const char *s); Whether you want to invoke some linker-script magic to make them refer to the same blob of code or not is optional. -- Grant Edwards grant.b.edwardsYow! I want my nose in at lights! gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12, Steve D'Aprano wrote: > On Thu, 12 Oct 2017 04:41 pm, Grant Edwards wrote: > > >>> Even two >>> different C compilers could return different values. >> >> Nope. If sizeof char is not 1, then it's not C. > > Today I Learned. It sure was an education the first I wrote C code for a machine where 1 == sizeof char == sizeof int == sizeof long == sizeof float == sizeof double All were 32 bits. Writing protocol code that dealt with the outside world via a serial port was _painful_. -- Grant Edwards grant.b.edwardsYow! ... I want a COLOR at T.V. and a VIBRATING BED!!! gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12 15:16, Ben Bacarisse wrote: > Gregory Ewing writes: > >> Ben Bacarisse wrote: >>> That's a different type. I think you mean that a human writing C >>> (rather than bartc's code generator) would probably design the code to >>> use tokenrec ** then I agree, but the latter is not just a different way >>> to write the former. >> >> Yes, I was translating his English description of the type >> into C, using C's meaning of the word "array". It seems that >> arrays in the original language (Algol? One of Bart's >> inventions?) are somewhat richer things. > > Probably, but you can have pointers to array types in C which is what > the posted type used. Humans pass arrays in C by passing a pointer to > the first element. Pointers to arrays therefore crop up when passing 2D > (or higher) arrays, even when the code is hand written by a person. > No, actually. Multi-dimensional arrays in C are not arrays of arrays. They look very similar, but when the dimensions of the array are known at compile time, arrays of any rank are a continuous region of memory with the data, and a pointer to the start. Casting int[3][3] to int** will not do what you want it to do. If, say, you have variables of the types: int a[M][N], **b; then a[i][j] is equivalent to *(a+(i*M)+j), while b[i][j] is equivalent to *(*(b+i)+j). Observe: --- #include #include #include int main (int argc, char **argv) { int i,j; /* multi-dimensional array: the compiler knows the dimensions! */ short multi_array[3][3] = { {1, 0, 0}, {0, 1, 0}, {0, 0, 1} }; short *array_array[3]; /* fill array_array elements of multi_array */ for(i=0; i<3; ++i) { array_array[i] = calloc(3, sizeof(short)); /* This works because C arrays are row-major */ memcpy(array_array[i], &multi_array[i][0], 3*sizeof(short)); } /* print out the arrays */ puts("multi_array:"); for (i=0; i<3; ++i) { for (j=0; j<3; ++j) { printf("%d ", multi_array[i][j]); } puts(""); } puts("array_array:"); for (i=0; i<3; ++i) { for (j=0; j<3; ++j) { printf("%d ", array_array[i][j]); } puts(""); } printf("&multi_array = 0x%llX\n", (long long)&multi_array); printf("*multi_array = 0x%llX\n", (long long)(*(short**)multi_array)); printf("&array_array = 0x%llX\n", (long long)&array_array); printf("*array_array = 0x%llX\n", (long long)(*(short**)array_array)); /* clean up */ for (i=0; i<3; ++i) { free(array_array[i]); } return 0; } --- [OUTPUT] multi_array: 1 0 0 0 1 0 0 0 1 array_array: 1 0 0 0 1 0 0 0 1 &multi_array = 0x7FFE0E736470 *multi_array = 0x1 &array_array = 0x7FFE0E736450 *array_array = 0x1A42010 -- https://mail.python.org/mailman/listinfo/python-list
Re: Want to write a python code for sending and receiving frames over wifi/wlan0 using python
On 2017-10-12, Chris Angelico wrote: > On Thu, Oct 12, 2017 at 7:08 PM, T Obulesu wrote: >> Hello all, I want to send some frames defined by me{Example, >> [0x45,0x43,0x32]} to the raspberry pi from any macine(Desktop/Laptop/other >> raspberry pi). But I want to send those frames over wifi or use wlan0 using >> python Any suggestions? >> -- > > Since you use the word "frame", I'm thinking you possibly mean at a > very low level, and not packaged up into UDP/IP packets. I'm curious > as to why you'd need that; for most purposes, the easiest way would be > either TCP or UDP. But sending raw packets is entirely possible in > Python - though you have to bear in mind that many OSes restrict this > capability to administrative programs. Under Linux, theres a network capability that can be enabled for a program to allow raw packet access w/o having to be root. However, it's not very useful for Python apps, since that capability would have to be set for the Python interpreter executable (e.g. /usr/bin/python). I avoid Windows as much as possible, but in recent years, colleagues who do work with Windows have had to convert all of our applicatoins which used to use raw packets to use UDP instead. I'm told that recent windows versions have made raw packet access from userspace (even by admin apps) virtually impossible. -- Grant Edwards grant.b.edwardsYow! Hello? Enema Bondage? at I'm calling because I want gmail.comto be happy, I guess ... -- https://mail.python.org/mailman/listinfo/python-list
Re: Logging from files doesn't work
Cameron, Peter, Thank you. Your comments were spot on. Changing root logger got the logs spitting into the file. And i now can org these logs into one directory, instead of the current mess. Thank you! On Oct 11, 2017 23:41, "Cameron Simpson" wrote: > On 11Oct2017 22:27, Andrew Z wrote: > >> aha. So the issue is that main.py's __name__ attribute == "__main__" and >> test.py is "test1.test". >> > > Yeah. If you invoke a module as "python -m module_name" its __name__ field > is "__main__". That makes the boilerplate work, but breaks your expectation > that __name__ is usually module_name. > > if i manually assign names: >> main.py - > >> >> log = logging.getLogger("MAIN") >> >> test.py - > >> log = logging.getLogger("MAIN.test1.test") >> >> then logging is working perfectly well. >> >> This brings me to the question - what is wrong with me file >> naming/structure that confuses the logging module? I'm not sure i >> really want to have each little file in it's own directory too.. >> > > I confess to not using the logging module in the module-named-based > fashion that seems to be the default recommendation. I usually prefer to > set up the root logger to log somewhere suitable to the main program > (typically just stderr by default), and set up special logging for other > things as needed. > > As what may be a poor example, I've got a mail filing program which > monitors maildirs for arriving messages to refile. So I've got a class > associated with each monitored maildir with these methods: > > @property > def logdir(self): >''' The pathname of the directory in which log files are written. >''' >varlog = cs.env.LOGDIR(self.environ) >return os.path.join(varlog, 'mailfiler') > > This essentially computes "$HOME/var/log/mailfiler" as the place where all > the logfiles are saved. And this: > > def folder_logfile(self, folder_path): >''' Return path to log file associated with the named folder. >TODO: base on relative path from folder root, not just basename. >''' >return os.path.join(self.logdir, '%s.log' % > (os.path.basename(folder_path))) > > which computes "$HOME/var/log/mailfiler/spool.log" as the logfile when > working on my maildir "$HOME/mail/spool". > > And then off it goes with a FileHandler for that path for the filing > actions for that maildir. > > So you're not contrained to drop log files all through your source tree > (ewww!) > > My opinion is that you should decide where your logfiles _should_ live; it > generally has nothing (or little) to do with the module name. I keep mine, > generally, in various subdirectories of "$HOME/var/log". > > Cheers, > Cameron Simpson (formerly c...@zip.com.au) > -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Grant Edwards : > Using const with strings in C with amateurish libraries is a headache > because _some_people_ will write their declarations so as to require > pointers to mutable strings even when they have no intention of > mutating them. Those people should be hunted down and slapped with a > herring until they understand the error of their ways. Hear, hear. > The standard library is much better about that. You lost me there. Seriously, though. C strings are not the most problematic issue. How about other structures? What about: long ftell(FILE *stream); int fgetpos(FILE *stream, fpos_t *pos); Should that be "const FILE *stream"? In general, C record definitions (opaque structs) that represent encapsulated classes don't take a "const" in any context. They *could* but that isn't the tradition. For example, here's a random function from the Linux kernel: static bool tcp_fastopen_cookie_gen(struct request_sock *req, struct sk_buff *syn, struct tcp_fastopen_cookie *foc) { if (req->rsk_ops->family == AF_INET) { const struct iphdr *iph = ip_hdr(syn); __be32 path[4] = { iph->saddr, iph->daddr, 0, 0 }; return __tcp_fastopen_cookie_gen(path, foc); } #if IS_ENABLED(CONFIG_IPV6) if (req->rsk_ops->family == AF_INET6) { const struct ipv6hdr *ip6h = ipv6_hdr(syn); struct tcp_fastopen_cookie tmp; if (__tcp_fastopen_cookie_gen(&ip6h->saddr, &tmp)) { struct in6_addr *buf = (struct in6_addr *) tmp.val; int i; for (i = 0; i < 4; i++) buf->s6_addr32[i] ^= ip6h->daddr.s6_addr32[i]; return __tcp_fastopen_cookie_gen(buf, foc); } } #endif return false; } Note how both "req" and "syn" could well be declared as "const" pointers but are not. Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12, Marko Rauhamaa wrote: > Grant Edwards : > >> Using const with strings in C with amateurish libraries is a headache >> because _some_people_ will write their declarations so as to require >> pointers to mutable strings even when they have no intention of >> mutating them. Those people should be hunted down and slapped with a >> herring until they understand the error of their ways. > > Hear, hear. > >> The standard library is much better about that. > > You lost me there. I meant that in the include files for the C standard library, functions that aren't going to modify a string paramameter always declare the parameter as "const char *". > Seriously, though. C strings are not the most problematic issue. How > about other structures? What about: > >long ftell(FILE *stream); >int fgetpos(FILE *stream, fpos_t *pos); > > Should that be "const FILE *stream"? IMO, yes. > In general, C record definitions (opaque structs) that represent > encapsulated classes don't take a "const" in any context. They > *could* but that isn't the tradition. In my own code I do try to do that, but (as in the Linux kernel code you posted) you still run into problems using third-party libraries written by the, um, unenlightened. > For example, here's a random function from > the Linux kernel: > > > static bool tcp_fastopen_cookie_gen(struct request_sock *req, > struct sk_buff *syn, > struct tcp_fastopen_cookie *foc) > { [...] > Note how both "req" and "syn" could well be declared as "const" pointers > but are not. Yep. IMO, that's just sloppy programming. -- Grant Edwards grant.b.edwardsYow! Can you MAIL a BEAN at CAKE? gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 169, Issue 23
On Thu, Oct 12, 2017 08:05 AM, Steve D'Aprano wrote:> On Wed, 11 Oct 2017 10:57 pm, Stefan Ram wrote: > >> FWIW, in is book "Touch of Class" (2009) Bertrand >Meyer writes: >> >> |Such instructions are just the old goto in sheep's clothing. >> |Treat them the same way as the original: >> | >> |/Touch of Methodology/: >> | Sticking to one-entry, one-exit building blocks >> |Stay away from any "break" or similar control mechanism. > >I have a great deal of respect for Meyer, but in this case I think he has it >badly wrong on both counts (`break` and "one-entry, >one-exit"). > >Unrestricted GOTO (as in BASIC, circa 1970, where you could jump to any >line >in the code, or as in assembly) is rightly considered harmful (albeit >necessary in assembly). But if Meyer means *any* sort of jump >("similar >control mechanism"), then that would rule out not just `break` and >`continue` >but also: > >* while loops >* for loops >* if...else >* case/switch statements >* calling subroutines (functions or procedures) >* exception handling > >Remember that a function call is basically a GOTO in disguise: execution jumps >to the function, and jumps back when the function returns. In BASIC, there >was a GOSUB intermediate between a GOTO and a procedure call. > >Surely Meyer doesn't mean to say we should never call functions or use >`while`, `for` or `if`. So he has to distinguish between kinds of jumps: > >Good jumps (I presume): > >* function calls >* if...else >* looping > >Evil jumps: > >* unrestricted BASIC-style GOTO/GOSUB any line number >* break/continue > >Not sure: > >* GOTO where there are restrictions on where you can jump >* COMEFROM > >(I kid: I'm sure Meyer would oppose COMEFROM, and I expect that even >Pascal-style restricted GOTO would be on his "evil" list to >avoid.) This seems like a veritable straw man if any. I am fairly sure that "one entry, one exit" does not precisely mean "no branching whatsoever" Nor does discouraging unrestricted GOTO suggest that either. Clearly a while or for loop without break i is single-entry and single exit. The if-else has a clear single entry at the test condition, and a single exit could be imagined at the program point immediately after the if-else., etc. The case/switch does have a single exit in the same way as the if. Unfortunately, it does in itself sort of violate the single entry idea when a break does not precede the next case. That just leaves the multiple returns in a functionand the exception handling. >So the question becomes, why are such harmless, simple to understand, innocuous jumps like `break` and `continue` in the evil list, when they not only simplify code but make it more efficient? # with break for i in range(2**64): if isprime(i): print(i, "is prime") break # without break still_searching = True for i in range(2**64): if still_searching and isprime(i): print(i, "is prime") still_searching = False # without break, attempt number 2 still_searching = True i = 0 while still_searching and i < 2**64: if isprime(i): print(i, "is prime") still_searching = False # without break, the way it should be: i = 0 while not isprime(i): ... i = i+1 print(i, "is prime") I believe this is far simpler _and_ more efifcient than any of your answers above. Do you really believe that there are no prime numbers less than 2**64? Can you imagine any circumstance when "i < 2**75" would become false in this application? Can you really claim that a solution is more efficient when it repeatedly tests a condition that can never posslbly be false? That is the biggest objection programming teachers like me dislike the break statement -- it leads to very careless programming. Once you imagine that you will use a break to exit your loops, you might stop thinking about what your loop conditions are. And then you find yourself in a corner where the only way out is to break. It's like: I know that I can always call a tow truck whenever my car runs out of gas on the highway, so I'll no longer bother checking or filling my tank. I'll just drive until I'm beyohd fumes, break down, call a tow, and then tell my boss how I was unavoidably late because I broke down on the highway. Ironically, after telling us to stick to code with one entry and one exit, Meyer then contradicts himself by recommending exceptions: > |You can use exception handling as a technique of last resort > |to handle unexpected events for which the normal control > |structures let you down. Even more ironically, exception handling is most similar to a COMEFROM, which was invented as a joke. The exception handler itself has one entry (the exception) and one exit. And, unlike goto's and set_jmp() is easiliy incorporated into other control structures depending on where you want to go after any recovery steps. The code that generated the exception, of course, seemingly has more than one
Re: Lies in education [was Re: The "loop and a half"]
On 12/10/17 16:06, Grant Edwards wrote: On 2017-10-12, Steve D'Aprano wrote: On Thu, 12 Oct 2017 04:41 pm, Grant Edwards wrote: Even two different C compilers could return different values. Nope. If sizeof char is not 1, then it's not C. Today I Learned. It sure was an education the first I wrote C code for a machine where 1 == sizeof char == sizeof int == sizeof long == sizeof float == sizeof double All were 32 bits. Ah yes. In my case it was 16 bits, so sizeof long == 2 just for a little variation. Writing protocol code that dealt with the outside world via a serial port was _painful_. Amen, brother. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 12/10/2017 16:18, Marko Rauhamaa wrote: Grant Edwards : Using const with strings in C with amateurish libraries is a headache because _some_people_ will write their declarations so as to require pointers to mutable strings even when they have no intention of mutating them. Those people should be hunted down and slapped with a herring until they understand the error of their ways. Hear, hear. The standard library is much better about that. You lost me there. Seriously, though. C strings are not the most problematic issue. How about other structures? What about: long ftell(FILE *stream); int fgetpos(FILE *stream, fpos_t *pos); Should that be "const FILE *stream"? In general, C record definitions (opaque structs) that represent encapsulated classes don't take a "const" in any context. They *could* but that isn't the tradition. For example, here's a random function from the Linux kernel: static bool tcp_fastopen_cookie_gen(struct request_sock *req, struct sk_buff *syn, struct tcp_fastopen_cookie *foc) { if (req->rsk_ops->family == AF_INET) { const struct iphdr *iph = ip_hdr(syn); __be32 path[4] = { iph->saddr, iph->daddr, 0, 0 }; return __tcp_fastopen_cookie_gen(path, foc); } #if IS_ENABLED(CONFIG_IPV6) if (req->rsk_ops->family == AF_INET6) { const struct ipv6hdr *ip6h = ipv6_hdr(syn); struct tcp_fastopen_cookie tmp; if (__tcp_fastopen_cookie_gen(&ip6h->saddr, &tmp)) { struct in6_addr *buf = (struct in6_addr *) tmp.val; int i; for (i = 0; i < 4; i++) buf->s6_addr32[i] ^= ip6h->daddr.s6_addr32[i]; return __tcp_fastopen_cookie_gen(buf, foc); } } #endif return false; } If you took a working C program and removed all the consts, it would still work. I don't think the language would miss them if they were to disappear. It is anyway too crude a technique for the things people like to apply it to. > > Note how both "req" and "syn" could well be declared as "const" > pointers but are not. const pointer, or pointer to const struct? Or both? With a const struct, you are stopped from directly modifying elements, but if an element is a pointer, nothing stops you writing to what the pointer points to, unless that has a const target too. And then you've going to have problems doing normal updates. This constness just insinuates itself everywhere. -- bartc -- bartc -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Jon Ribbens writes: > On 2017-10-12, Ben Bacarisse wrote: >> Chris Angelico writes: >>> Normally, with a Python-based framework, you don't need _any_ web >>> server configuration. You simply define your URL routing within the >>> Python code. The only thing the web server needs to know is where to >>> find the web app, and that's sufficiently standard that it can be done >>> off-the-shelf; for instance, you push your code to Heroku, and they >>> set everything up to pass requests to your app. Not possible with PHP, >>> since you need *custom* web server config to manage your rewrite >>> rules. >> >> That's at odds with what I've read online which admittedly may be all >> junk. I wanted to try Flask so I installed the Ubuntu packages but then >> got stuck on a huge document that suggested I needed to install things >> called Nginx and Gunicorn. You've now mentioned another: Heroku. I'm >> sure the complex instructions I found are not really required -- it was >> probably just the usual "this is what I did so this is how it's done" >> document, but I'm having trouble finding the simpler way to do it. >> >> Since no web server configuration is needed (I have a working Apache >> installation that mirrors, as closely as possible, what my hosting >> provider uses) it should be relatively easy. Can you tell me, or can >> you point me to a resource that tells me, where to put the app? I don't >> yet know what "push your code to Heroku" means. > > "don't need _any_ web server configuration" is rather, er, optimistic. It did seem so. I could not imagine any way it would "just" work unless it was already set up to "just work". > For Apache you'd need the mod_proxy_uwsgi module installed, and the > config would be something like this: > > DocumentRoot /srv/www/appname/appname > > ProxyPass uwsgi://127.0.0.1:3031/ > > > ProxyPass ! > > > and you need an app container listening on the port defined above, > e.g. uwsgi with config like: > > /etc/uwsgi/apps-available/appname.ini: > > [uwsgi] > plugin = python3 > socket = 127.0.0.1:3031 > threads = 4 > master = 1 > chdir = /srv/www/appname > module = appname:app > # https://github.com/unbit/uwsgi/issues/1126 > wsgi-disable-file-wrapper = true > > and you'll need something to run uwsgi on system startup. I see. If I'm reading this right, the app requests are passed through to another server -- uWSGI. How does this typically work on low-cost hosting? I may be able to set up the ProxyPass locally (i.e. in .htaccess) but I won't be able to write /etc/uwsgi/apps-available/appname.ini. Maybe there are a locally defined .ini files that uwsgi reads? As for running something on startup... I suppose I can ask. Maybe it's usual to run it anyway. -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12, Rhodri James wrote: > On 12/10/17 16:06, Grant Edwards wrote: >> On 2017-10-12, Steve D'Aprano wrote: >>> On Thu, 12 Oct 2017 04:41 pm, Grant Edwards wrote: >>> > Even two different C compilers could return different values. Nope. If sizeof char is not 1, then it's not C. >>> >>> Today I Learned. >> >> It sure was an education the first I wrote C code for >> a machine where >> >> 1 == sizeof char == sizeof int == sizeof long == sizeof float == sizeof >> double >> >> All were 32 bits. > > Ah yes. In my case it was 16 bits, so sizeof long == 2 just for a > little variation. It does help when a char is an integral number of octets. Working with a machine where everything is 20 bits would be even worse. I wonder if anybody ever designed a CPU where the word size was odd? -- Grant Edwards grant.b.edwardsYow! How many retured at bricklayers from FLORIDA gmail.comare out purchasing PENCIL SHARPENERS right NOW?? -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Thomas Jollans writes: > On 2017-10-12 15:16, Ben Bacarisse wrote: >> Gregory Ewing writes: >> >>> Ben Bacarisse wrote: That's a different type. I think you mean that a human writing C (rather than bartc's code generator) would probably design the code to use tokenrec ** then I agree, but the latter is not just a different way to write the former. >>> >>> Yes, I was translating his English description of the type >>> into C, using C's meaning of the word "array". It seems that >>> arrays in the original language (Algol? One of Bart's >>> inventions?) are somewhat richer things. >> >> Probably, but you can have pointers to array types in C which is what >> the posted type used. Humans pass arrays in C by passing a pointer to >> the first element. Pointers to arrays therefore crop up when passing 2D >> (or higher) arrays, even when the code is hand written by a person. >> > > No, actually. Multi-dimensional arrays in C are not arrays of arrays. That's exactly what they are (in their simplest form). Other structures using pointers can be accessed in the same way so some people call those multi-dimensional arrays, but that can be a bit confusing. > They look very similar, but when the dimensions of the array are known > at compile time, arrays of any rank are a continuous region of memory > with the data, and a pointer to the start. > > Casting int[3][3] to int** will not do what you want it to do. Exactly. This is why I raised this as an example where you get a pointer to an array type. int ** is something else altogether. When you pass an int[3][3] to a function, it pops up in the function as an int (*)[3]. You can (due to another of C's odd rules) write the parameter as int a[][3], or int a[3][3], but the first array in the declarator is replaced by a pointer (and the size is ignored). > If, say, you have variables of the types: > > int a[M][N], **b; > > then a[i][j] is equivalent to *(a+(i*M)+j), No it isn't. That expression does not even have type int. In fact you will be surprised to learn that a[i][j] it is equivalent to *(*(a+i)+j). > while b[i][j] is equivalent to *(*(b+i)+j). That much is true. The fact that the genuine 2D array access (a[i][j]) is equivalent an expression of the same form as the pointer to pointer access (b[i][j]) looks odd because, as you know, they are doing different things. But they do different things because the types are different. > Observe: > short multi_array[3][3] = { > {1, 0, 0}, > {0, 1, 0}, > {0, 0, 1} > }; > short *array_array[3]; I would not have used that name. This is an array of pointers. > /* fill array_array elements of multi_array */ > for(i=0; i<3; ++i) { > array_array[i] = calloc(3, sizeof(short)); > /* This works because C arrays are row-major */ > memcpy(array_array[i], &multi_array[i][0], 3*sizeof(short)); Some people would find array_array[i] = malloc(sizeof multi_array[i]); memcpy(array_array[i], multi_array[i], sizeof multi_array[i]); to be clearer and more maintainable. You don't repeat the element type and there's no need to reference the (possibly arbitrary) size 3. It makes it very clear that enough space is being allocated for what is being copied. > } > > /* print out the arrays */ > puts("multi_array:"); > for (i=0; i<3; ++i) { > for (j=0; j<3; ++j) { > printf("%d ", multi_array[i][j]); Try *(multi_array+(i*3)+j) here to see what happens (that's your re-write with 'a' and 'M' substituted). > } > puts(""); > } -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 169, Issue 23
The opinions I give in this post are not as strong as the opinions I expressed before about the loop claiming to count all the way to 2**64. But I'll give them anyway. I don't mind having return's inside an if statement, when the function ends with that if statement. It becomes very clear then that there is a choice of possible results, and that exactly one of those choices apply. def foo(): ... if condition: .. return 1 ... else .. return 2 I would expect this to be the same as the "# with multiple exits" with a possibly very minor increase in clarity. I have used several IDE's that let you mask out chunks of code based on their indentation level. Sometimes I use that concept as an estimate of readability (minimizing how much a reader has to look at to understand the structure of the code. Contrast my multiple-exit with the one I quoted: def foo(): def foo(): if (condition) if (condition0 [...][...] else: return 2 [...] If someone was only reading lines indented once, and skimming the rest as details unimportant to the structure, he might have a misleading assumption about the return value in the code on the right.On the left, he would look be forced to look one level deeper to find the return's, and find two outcomes. This same level-of-indentation measure also argues against break and continue, since statements would also be further indented, which might make them easier to miss. But, in any case, I do not mind multiple return's clearly marked with if/else. On the other hand, I still recommend against return statements inside of loops. It shouldn't be hard to find the appropriate way to leave the loop, and return afterwards. My position is also in line with one of my hard and fast rules for early programming students: Rule: If the operation does not repeat, do not put it into a loop. I don't even make an exception for return statements. And my justification for not making an exception is not only to simply the pedagogy (absolutism is much easier to explain), but also goes along with the other maxim: The code should be obvious! There are just so many times when I see students expect a return statement within a loop to be able to return more than one value. It happens both when reading code, and when writing code, and even happens for upperclassmen, who should know better. Clearly, if such a misinterpretation is prevalent, the code is not obvious. And that's even ignoring the benefit of being able to set a breakpoint at the very bottom of a function when debugging. Roger Christman Pennsylvania State University On Thu, Oct 12, 2017 12:26 AM, Steve D'Aprano wrote: > > >Message: 3 >Date: Thu, 12 Oct 2017 12:26:07 +1100 >From: Steve D'Aprano >To: python-list@python.org >Subject: Re: Looping [was Re: Python and the need for speed] >Message-ID: <59dec4b0$0$14935$b1db1813$d948b...@news.astraweb.com> >Content-Type: text/plain; charset=utf-8 > > >But from the point of view of the subroutines, the rule "one exit" is >like the >rule "no break" for loops: it makes the code more complex and less >efficient. >If you're done, you're done, and you might as well return out of the function >rather than write boilerplate code to pad it out until you get to the very >end. With only a single condition to test, there's not much difference >between the two: > ># with single exit # with multiple exits >def foo(): def foo(): >if condition: if condition: >result = 1 return 1 >else: return 2 >result = 2 >return result > > >but as the number of decision points increase, the complexity required to keep >a single exit also increases. > > > -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12, Ben Bacarisse wrote: > I see. If I'm reading this right, the app requests are passed through > to another server -- uWSGI. Yes. It doesn't have to be uWSGI; it could be gunicorn, or you could probably use Apache's mod_fcgid. As a last resort you could use CGI, which wouldn't involve any long-running processes, which has the benefit of not requiring any special support from your host but the disadvantage of most likely being very slow indeed. > How does this typically work on low-cost hosting? I may be able to set > up the ProxyPass locally (i.e. in .htaccess) but I won't be able to > write /etc/uwsgi/apps-available/appname.ini. Maybe there are a locally > defined .ini files that uwsgi reads? You need to choose a host that supports one of the relevant systems mentioned above. If you already have a host then it's possible they already do, otherwise you may need to choose another. -- https://mail.python.org/mailman/listinfo/python-list
Heroku (was Re: Lies in education [was Re: The "loop and a half"])
On Fri, Oct 13, 2017 at 1:09 AM, Ben Bacarisse wrote: > Chris Angelico writes: > >> On Thu, Oct 12, 2017 at 7:32 PM, Thomas Jollans wrote: >>> On 2017-10-12 07:31, Chris Angelico wrote: On Thu, Oct 12, 2017 at 12:19 PM, Ben Bacarisse wrote: > Provided some early part of the URL is handled by PHP, the rest of the > URL path is provided to PHP in $_SERVER["PATH_INFO"]. Is it possible to do that without having ".php" visible in the path? >>> >>> Just like with Python-based frameworks, this requires a few lines of web >>> server configuration. >>> >>> On Apache, you might use mod_wsgi to tell the server how to run the code >>> in one case, and a combination of mod_php and mod_rewrite in the other. >>> If you're using FastCGI with nginx or lighttpd, I believe the >>> configuration would look pretty similar in both cases. >>> >>> Then again, I don't do much web programming any more and generally stay >>> away from PHP, so I may be misremembering. >> >> Normally, with a Python-based framework, you don't need _any_ web >> server configuration. You simply define your URL routing within the >> Python code. The only thing the web server needs to know is where to >> find the web app, and that's sufficiently standard that it can be done >> off-the-shelf; for instance, you push your code to Heroku, and they >> set everything up to pass requests to your app. Not possible with PHP, >> since you need *custom* web server config to manage your rewrite >> rules. > > That's at odds with what I've read online which admittedly may be all > junk. I wanted to try Flask so I installed the Ubuntu packages but then > got stuck on a huge document that suggested I needed to install things > called Nginx and Gunicorn. You've now mentioned another: Heroku. I'm > sure the complex instructions I found are not really required -- it was > probably just the usual "this is what I did so this is how it's done" > document, but I'm having trouble finding the simpler way to do it. > > Since no web server configuration is needed (I have a working Apache > installation that mirrors, as closely as possible, what my hosting > provider uses) it should be relatively easy. Can you tell me, or can > you point me to a resource that tells me, where to put the app? I don't > yet know what "push your code to Heroku" means. I abbreviated that down to nothing, but since you ask, here's a really REALLY simple run-down of how to use Heroku: 1) Create a git repository to manage your code. (You should be doing this anyway.) 2) Install the Heroku CLI for your platform 3) Run "heroku login" and enter your credentials (once) 4) Run "heroku create" from your project repo to generate a URL to use for the project 5) Ensure that you list all your requirements in a file called "requirements.txt". Heroku uses this to (a) recognize that it's a Python project, and (b) install your dependencies, with "pip install -r requirements.txt". 6) Tell Heroku how to find your main file by making a file called "Procfile" 7) Run: "git push heroku master" There are other ways to do things (notably, Heroku will work with GitHub and Travis to do CI/CD just by pushing code to the master branch on GitHub - Travis will run your tests and then push to Heroku for you), but this is about the simplest it gets. Yes, there are a good few steps there, but most of them are simple one-offs, or are things you should do anyway. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12 03:47, ROGER GRAYDON CHRISTMAN wrote: Actually, FORTRAN and COBOL and Algol (for its control structures) Trying to support both of the first two was entertaining -- when you declared a variable, it wasn't enough to say it was an Integer: you had to also declare whether it was represented in Binary or Decimal, and also specify the desired precision. The IBM/360 architecture supported both binary and decimal integers, where the decimals were stored as BCD nybbles of arbitrary fixed length (as opposed to binary integers matching the machine word size) The world migrated away from PL/I back in those days because of the one-size fits none consequences of trying to do everything. So I always find myself looking askance when language designers try to repeat the exercise. You know, like designing a largely-interpreted object-oriented language with libraries supporting a functional programming style. I think I've seen a language like that somewhere around this forum. But I like it anyway I think the difference is that those other languages tried to be "complete" closed languages. Python, on the other hand, doesn't try to do everything itself, and it's open, so you can add functionality written in other languages and call external programs that already exist. [snip] -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Jon Ribbens writes: > On 2017-10-12, Ben Bacarisse wrote: >> I see. If I'm reading this right, the app requests are passed through >> to another server -- uWSGI. > > Yes. It doesn't have to be uWSGI; it could be gunicorn, or you could > probably use Apache's mod_fcgid. As a last resort you could use CGI, > which wouldn't involve any long-running processes, which has the > benefit of not requiring any special support from your host but the > disadvantage of most likely being very slow indeed. > >> How does this typically work on low-cost hosting? I may be able to set >> up the ProxyPass locally (i.e. in .htaccess) but I won't be able to >> write /etc/uwsgi/apps-available/appname.ini. Maybe there are a locally >> defined .ini files that uwsgi reads? > > You need to choose a host that supports one of the relevant systems > mentioned above. If you already have a host then it's possible they > already do, otherwise you may need to choose another. Ah, thanks. You've cleared up some of miasma of terms that seems to surround the various Python-for-the-web options. I'd like to try it, but not enough to switch hosting and, probably, spend more money. -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Cooperative class tree filtering
Hello, suppose you have you have three classes A, B, C where C is a subclass of B and B of A. They provide a method with signature `filter(element)`. It is called by an external function that collects the elements and then to an instance of the classes A, B and C is given a chance to filter these elements, one at a time. So the `filter(element)` method returns `True` if the element has to be included in the final set and `False` if it doesn't, easy peasy. (This is a simplified example of a real use case). What I want to have is that if an instance of class C has doesn't know what to return about an element, it calls `super()` to return the value from the same method implemented in its superclass, and so on up on the tree. To show it in code: class A: def filter(self, element): # the default implementation always returns True return True class B(A): def filter(self, element): if element == 'foo': return True elif element == 'bar': return False else: return super().filter(element) class C(B): def filter(self, element): if element == 'bar': return True else: return super().filter(element) def collect_elements(instance): "A semplified element collect function" all_elts = {'foo', 'bar', 'baz', 'zoo'} filtered_elts = set(el for el in all_elts if instance.filter(el)) return filtered_elts b = B() c = C() print(collect_elements(b)) print(collect_elements(c)) which run gives the following result: >>> {'foo', 'zoo', 'baz'} {'bar', 'foo', 'zoo', 'baz'} Now, what i ideally want is to get rid of that super() call at the end of the methods in classes B and c and to code that "fallback to what my superclass says" coded into A's implementation, where it kicks in if the method in the target instance returns None. So to write it in code, I would like some like: class A: def _filter_impl(self, element): # the default implementation always returns True return True def filter(self, element): # here a logic that if self._filter_impl(element) returns # None, it defaults to super(type(self), self)._filter_impl(element) # until A._filter_impl() is reached pass class B(A): def _filter_impl(self, element): if element == 'foo': return True elif element == 'bar': return False class C(B): def filter(self, element): if element == 'bar': return True I've tried some variants of the 'super()' trick, that sometimes seems to change behavior if it's written like that or like super(type(self), self) in no clear (to me, and I failed to find extensive doc on super()'s behavior) way, with things that stop working if mixins are involved (even if the mixins do not reimplement the methods involved here). Eventually i ended implementing a decorator: from functools import partial, wraps class delegate_super: """A method decorator that delegates part of the computation to the same method on the ancestor class.""" _name = None _owner = None def __init__(self, meth): self._meth = meth @wraps(meth) def wrapper(*args, **kwargs): return self.delegator(*args, **kwargs) self.wrapper = wrapper def __get__(self, instance, owner): return partial(self.wrapper, instance) def __set_name__(self, owner, name): self._owner = owner self._name = name def delegator(self, instance, *args, **kwargs): result = self._meth(instance, *args, **kwargs) if result is None: result = getattr(super(self._owner, instance), self._name)( *args, **kwargs) return result class A: def filter(self, element): # the default implementation always returns True return True class B(A): @delegate_super def filter(self, element): if element == 'foo': return True elif element == 'bar': return False class C(B): @delegate_super def filter(self, element): if element == 'bar': return True else: return super().filter(element) def collect_elements(instance): "A semplified element collect function" all_elts = {'foo', 'bar', 'baz', 'zoo'} filtered_elts = set(el for el in all_elts if instance.filter(el)) return filtered_elts b = B() c = C() print(collect_elements(b)) print(collect_elements(c)) which has the same result as before: >>> {'foo', 'zoo', 'baz'} {'bar', 'foo', 'zoo', 'baz'} I would really like to find a way to do this that doesn't involve decorating the methods in A subclasses to free the final developer to remember t
Re: Heroku (was Re: Lies in education [was Re: The "loop and a half"])
Chris Angelico writes: > On Fri, Oct 13, 2017 at 1:09 AM, Ben Bacarisse wrote: >> Chris Angelico writes: >> >>> On Thu, Oct 12, 2017 at 7:32 PM, Thomas Jollans wrote: On 2017-10-12 07:31, Chris Angelico wrote: > On Thu, Oct 12, 2017 at 12:19 PM, Ben Bacarisse > wrote: >> Provided some early part of the URL is handled by PHP, the rest of the >> URL path is provided to PHP in $_SERVER["PATH_INFO"]. > > Is it possible to do that without having ".php" visible in the path? Just like with Python-based frameworks, this requires a few lines of web server configuration. On Apache, you might use mod_wsgi to tell the server how to run the code in one case, and a combination of mod_php and mod_rewrite in the other. If you're using FastCGI with nginx or lighttpd, I believe the configuration would look pretty similar in both cases. Then again, I don't do much web programming any more and generally stay away from PHP, so I may be misremembering. >>> >>> Normally, with a Python-based framework, you don't need _any_ web >>> server configuration. You simply define your URL routing within the >>> Python code. The only thing the web server needs to know is where to >>> find the web app, and that's sufficiently standard that it can be done >>> off-the-shelf; for instance, you push your code to Heroku, and they >>> set everything up to pass requests to your app. Not possible with PHP, >>> since you need *custom* web server config to manage your rewrite >>> rules. >> >> That's at odds with what I've read online which admittedly may be all >> junk. I wanted to try Flask so I installed the Ubuntu packages but then >> got stuck on a huge document that suggested I needed to install things >> called Nginx and Gunicorn. You've now mentioned another: Heroku. I'm >> sure the complex instructions I found are not really required -- it was >> probably just the usual "this is what I did so this is how it's done" >> document, but I'm having trouble finding the simpler way to do it. >> >> Since no web server configuration is needed (I have a working Apache >> installation that mirrors, as closely as possible, what my hosting >> provider uses) it should be relatively easy. Can you tell me, or can >> you point me to a resource that tells me, where to put the app? I don't >> yet know what "push your code to Heroku" means. > > I abbreviated that down to nothing, but since you ask, here's a really > REALLY simple run-down of how to use Heroku: I think I see what you mean now. You meant no configuration is needed because you use (or buy?) a cloud service that's all set up for it already? >From this and other posts I think the position is that I do need to do some server configuration (and essentially install a proxy server) to run Python web applications on my typical Apache set-up. And I would then have to shop around for suitable hosting that is already set up for running them. Thanks. That's not quite what I was after but it's good to know how to do that should I want to that later. -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On Fri, 13 Oct 2017 02:06 am, Grant Edwards wrote: > It sure was an education the first I wrote C code for > a machine where > > 1 == sizeof char == sizeof int == sizeof long == sizeof float == sizeof > double > > All were 32 bits. Does that imply that on that machine 1 byte = 32 bits? I don't suppose you remember the name of the machine do you? > Writing protocol code that dealt with the outside world via a serial > port was _painful_. -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Solution Manual Test Bank for Financial and Managerial Accounting for MBAs 5th Edition by Easton
Greetings Students, We do have Solution Manuals and Test Bank for FINANCIAL AND MANAGERIAL ACCOUNTING FOR MBAs 5TH EDITION BY EASTON at reasonable price. You can get above mentioned resources by sending email to pro.fast(@)hotmail(dot)com Send your order queries at PRO.FAST(@)HOTMAIL(DOT)COM Below are details given for this book Book Name: FINANCIAL AND MANAGERIAL ACCOUNTING FOR MBAs Authors: Peter D. Easton, Robert F. Halsey, Mary Lea McAnally, Al L. Hartgraves, Wayne J. Morse Edition: 5th E ISBN-10: 1618532324 ISBN-13: 9781618532329 Product Format: MS Word Total Modules: 25 Please mention complete details for your book so we could send you sample accordingly. Best Regards, P.S : Please do not post your reply here. We do not monitor queries here. Simply send us an email directly to PRO.FAST (@) HOTMAIL (DOT) COM I tried to send an email to the email you provided but it's not working. I need the test bank as soon as possible. Please contact me on my email:totah1234@gmail. -- https://mail.python.org/mailman/listinfo/python-list
Re: Cooperative class tree filtering
Sorry, i've made a mistake in the second C body, it's written like: > "me" == Alberto Berti writes: me> I've tried some variants of the 'super()' trick, that sometimes seems to me> change behavior if it's written like that or like super(type(self), me> self) in no clear (to me, and I failed to find extensive doc on me> super()'s behavior) way, with things that stop working if mixins are me> involved (even if the mixins do not reimplement the methods involved me> here). Eventually i ended implementing a decorator: me> from functools import partial, wraps me> class delegate_super: me> """A method decorator that delegates part of the computation to the same me> method on the ancestor class.""" me> _name = None me> _owner = None me> def __init__(self, meth): me> self._meth = meth me> @wraps(meth) me> def wrapper(*args, **kwargs): me> return self.delegator(*args, **kwargs) me> self.wrapper = wrapper me> def __get__(self, instance, owner): me> return partial(self.wrapper, instance) me> def __set_name__(self, owner, name): me> self._owner = owner me> self._name = name me> def delegator(self, instance, *args, **kwargs): me> result = self._meth(instance, *args, **kwargs) me> if result is None: me> result = getattr(super(self._owner, instance), self._name)( me> *args, **kwargs) me> return result me> class A: me> def filter(self, element): me> # the default implementation always returns True me> return True me> class B(A): me> @delegate_super me> def filter(self, element): me> if element == 'foo': me> return True me> elif element == 'bar': me> return False me> class C(B): me> @delegate_super me> def filter(self, element): me> if element == 'bar': me> return True me> else: me> return super().filter(element) The correct version is: class C(B): @delegate_super def filter(self, element): if element == 'bar': return True -- https://mail.python.org/mailman/listinfo/python-list
Re: Heroku (was Re: Lies in education [was Re: The "loop and a half"])
On Fri, Oct 13, 2017 at 10:14 AM, Ben Bacarisse wrote: > Chris Angelico writes: >> I abbreviated that down to nothing, but since you ask, here's a really >> REALLY simple run-down of how to use Heroku: > > I think I see what you mean now. You meant no configuration is needed > because you use (or buy?) a cloud service that's all set up for it > already? Correct - because the setup needed is completely generic. > From this and other posts I think the position is that I do need to do > some server configuration (and essentially install a proxy server) to > run Python web applications on my typical Apache set-up. And I would > then have to shop around for suitable hosting that is already set up for > running them. > > > > Thanks. That's not quite what I was after but it's good to know how to > do that should I want to that later. Yep, it's not too hard. And that's why it's cleaner to work with Python than PHP. To use custom URL routing in PHP, you have to use custom server rules; to use custom URL routing in Python, you use "@app.route(...)" lines inside your app, and perfectly standard server rules. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-12, Steve D'Aprano wrote: > On Fri, 13 Oct 2017 02:06 am, Grant Edwards wrote: > >> It sure was an education the first I wrote C code for >> a machine where >> >> 1 == sizeof char == sizeof int == sizeof long == sizeof float == sizeof >> double >> >> All were 32 bits. > > > Does that imply that on that machine 1 byte = 32 bits? Maybe. That depends on what you mean by "byte". There is no such thing as a "byte" in C. The smallest addressable unit of memory in C is a "char". Nothing in C says that incrementing an address by 1 gets you to the next 8-bit chunk of memory. According to the "Byte" Wikipedia article: The size of the byte has historically been hardware dependent and no definitive standards existed that mandated the size -- byte-sizes from 1 to 48 bits are known to have been used in the past. The IEEE standards use the word "octet" to refer to a an 8-bit chunk of memory. When working with an architecture with a 32-bit char, you didn't use the word "byte" if you wanted to avoid confusion. > I don't suppose you remember the name of the machine do you? Texas Instruments TMS32C40. It's pretty common on DSPs to have only a single size for all datatypes. The 'C40 as pretty high-end -- it had floating point. Though I had to write routines to convert between IEE-754 and the native 32-bit format when I wanted to exchange floating point data with the outside world. :) -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Want to write a python code for sending and receiving frames over wifi/wlan0 using python
On Thursday, October 12, 2017 at 1:08:55 AM UTC-7, T Obulesu wrote: > Hello all, I want to send some frames defined by me{Example, > [0x45,0x43,0x32]} to the raspberry pi from any macine(Desktop/Laptop/other > raspberry pi). But I want to send those frames over wifi or use wlan0 using > python Any suggestions? Check out a Python library called scapy. It's used for raw packet forgery. But as others mentioned, that kind of activity will require you to run as root. Also, sending raw packets over Wifi specifically usually requires you to switch wlan0 to "monitor" mode, essentially making it unable to do anything else with it while your script is running. Also, not every Wifi adapter even supports entering monitor mode. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 2017-10-13, Stefan Ram wrote: > Grant Edwards writes: There is no such >>thing as a "byte" in C. > > »3.6 > > 1 byte > > addressable unit of data storage large enough to hold > any member of the basic character set of the execution > environment« > > ISO C standard Ah, I had forgotten about that paragraph. Now that I see the phrase "large enough to hold any member of the basic character set of the execution environment", I'm pretty sure I knew that at some point in the past. That means that in the context of the ISO C standard, on that architecture, 1 byte is 32 bits. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Running flask on AWS SAM
Hello, I have a flask based application which i am able to run locally. $ python swagger_server/app.py * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) I am trying to port this over to aws. I have all the dependencies and code organized in the same folder. Here is the transaction and error: $ SERVER_NAME=0.0.0.0:3000 sam local start-api 2017/10/12 21:02:20 Connected to Docker 1.32 2017/10/12 21:02:20 Fetching lambci/lambda:python3.6 image for python3.6 runtime... python3.6: Pulling from lambci/lambda Digest: sha256:c77ea3986c471c2f93dfa2a86492e6306989505073795da3b22defa2b10846a6 Status: Image is up to date for lambci/lambda:python3.6 Mounting swagger_server.app.app (python3.6) at http://127.0.0.1:3000/current [GET] Mounting static files from public at / You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template. 2017/10/12 21:02:30 Invoking swagger_server.app.app (python3.6) 2017/10/12 21:02:30 Decompressing /Users/shekartippur/playground/cyclopscloud/cyclopsglobal/swagger_server.zip START RequestId: 9518afce-6cf7-4f20-9a31-0a60907b5467 Version: $LATEST 'SERVER_NAME': KeyError Traceback (most recent call last): File "/var/task/connexion/apps/abstract.py", line 266, in __call__ return self.app(environ, start_response) File "/var/task/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "/var/task/flask/app.py", line 1977, in wsgi_app ctx = self.request_context(environ) File "/var/task/flask/app.py", line 1938, in request_context return RequestContext(self, environ) File "/var/task/flask/ctx.py", line 242, in __init__ self.url_adapter = app.create_url_adapter(self.request) File "/var/task/flask/app.py", line 1765, in create_url_adapter server_name=self.config['SERVER_NAME']) File "/var/task/werkzeug/routing.py", line 1299, in bind_to_environ wsgi_server_name = environ['SERVER_NAME'] KeyError: 'SERVER_NAME' END RequestId: 9518afce-6cf7-4f20-9a31-0a60907b5467 REPORT RequestId: 9518afce-6cf7-4f20-9a31-0a60907b5467 Duration: 3257 ms Billed Duration: 3300 ms Memory Size: 0 MB Max Memory Used: 38 MB I looked up the error and dint find much help. Wondering what I could be missing. -- https://mail.python.org/mailman/listinfo/python-list
unorderable types: list() > int()
Hello, pos = {"CLown":10,"BArbie":20} I want to return integer (10) for the keyword that starts with "CL" cl_ = [v for k, v in pos.items() if k.startswith('CL')] cl_pos = cl_[0] if cl_pos > 0: blah.. There are 2 issues with the above: a. ugly - cl_pos = cl_ [0] . I was thinking something like cl_ = [v for k, v in pos.items() if k.startswith('CL')][0] but that is too much for the eyes - in 2 weeks i'll rewrite this into something i can understand without banging against the desk. So what can be a better approach here ? b. in "cl_pos > 0:, cl_pos apparently is still a list. Though the run in a python console has no issues and report cl_pos as int. Appreciate. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
bartc wrote: (2) Declare data to be put into read-only memory as you say. That's fine with a 'const int * p', but what about a 'int * const p'? If the compiler can tell where p is initially pointing, it could put the pointer in read-only memory. Probably unlikely to happen in real code, though. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Stefan Ram wrote: void i_know_i_was_passed_a_pointer_to_an_array_and_how_many_elements_are_in_it ( char( *a )[ 4 ] ) { for( int i = 0; i < 4; ++i ) putchar( ( *a )[ i ]); } Only because you've statically made the array size part of the type. Your original example didn't do that; presumably it was intended to accept arrays of any size and cope with them dynamically. That's usually what you want, and the way you do that in C is to pass a pointer to the first element and convey the size separately. So the kind of declaration you used above is hardly ever seen in idiomatic C code. (I've *never* seen it done in real life.) -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Grant Edwards wrote: It sure was an education the first I wrote C code for a machine where 1 == sizeof char == sizeof int == sizeof long == sizeof float == sizeof double All were 32 bits. Unicode-ready -- way ahead of its time! -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On Fri, 13 Oct 2017 03:37 pm, Gregory Ewing wrote: > If the compiler can tell where p is initially pointing, it could > put the pointer in read-only memory. If it's read-only, how can the compiler write to it? (I come from the days when ROM was actual ROM, burned in at the factory.) -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On Fri, Oct 13, 2017 at 4:16 PM, Steve D'Aprano wrote: > On Fri, 13 Oct 2017 03:37 pm, Gregory Ewing wrote: > >> If the compiler can tell where p is initially pointing, it could >> put the pointer in read-only memory. > > If it's read-only, how can the compiler write to it? > > > (I come from the days when ROM was actual ROM, burned in at the factory.) Code pages (nothing to do with eight-bit character sets, I mean memory pages containing program code) are often - and should always be - read-only by default. The compiler can put constants into the code segment and reference them that way. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: unorderable types: list() > int()
On Fri, 13 Oct 2017 03:23 pm, Andrew Z wrote: > Hello, > pos = {"CLown":10,"BArbie":20} > I want to return integer (10) for the keyword that starts with "CL" > > > cl_ = [v for k, v in pos.items() if k.startswith('CL')] > cl_pos = cl_[0] > if cl_pos > 0: > >blah.. > > > There are 2 issues with the above: > a. ugly - cl_pos = cl_ [0] . I was thinking something like > > > cl_ = [v for k, v in pos.items() if k.startswith('CL')][0] > > but that is too much for the eyes - in 2 weeks i'll rewrite this into > something i can understand without banging against the desk. > So what can be a better approach here ? What you wrote is perfectly fine. But if you don't like it, then use a temporary variable, as you do above. > b. in "cl_pos > 0:, cl_pos apparently is still a list. Though the run in a > python console has no issues and report cl_pos as int. It isn't a list. What makes you think it is? py> pos = {"CLown":10,"BArbie":20} py> cl_ = [v for k, v in pos.items() if k.startswith('CL')] py> cl_pos = cl_[0] py> type(cl_pos) py> cl_pos 10 py> cl_pos > 0 True You probably wrote "cl_ > 0" by mistake. -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Grant Edwards wrote: On 2017-10-13, Stefan Ram wrote: 1 byte addressable unit of data storage large enough to hold any member of the basic character set of the execution environment« ISO C standard Hmmm. So an architecture with memory addressed in octets and Unicode as the basic character set would have a char of 8 bits and a byte of 32 bits? Not only does "byte" not always mean "8 bits", but "char" isn't always short for "character"... -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On Fri, Oct 13, 2017 at 4:28 PM, Gregory Ewing wrote: > Grant Edwards wrote: >> >> On 2017-10-13, Stefan Ram wrote: >> >>> 1 byte >>> >>> addressable unit of data storage large enough to hold >>> any member of the basic character set of the execution >>> environment« >>> >>>ISO C standard > > > Hmmm. So an architecture with memory addressed in octets > and Unicode as the basic character set would have a > char of 8 bits and a byte of 32 bits? > > Not only does "byte" not always mean "8 bits", but > "char" isn't always short for "character"... Certainly not. A byte would be 21 bits! Seriously though, I don't think anyone would design hardware like this. But I'd love to see what happens. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Steve D'Aprano wrote: On Fri, 13 Oct 2017 03:37 pm, Gregory Ewing wrote: If the compiler can tell where p is initially pointing, it could put the pointer in read-only memory. If it's read-only, how can the compiler write to it? (I come from the days when ROM was actual ROM, burned in at the factory.) So, the factory is allowed to write to it. Possibly it's writing data that came from... a compiler? A memory that couldn't be written to at all, ever, would be a bit useless! -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
Chris Angelico wrote: Certainly not. A byte would be 21 bits! Only if 21 bits were *also* an addressable unit of storage in addition to octets. That would be an interesting architecture indeed. If you really wanted that, it might be easier just to make the memory bit-addressable. In which case a char would be 1 bit! I believe Burroughs built a bit-addressable machine at one point. It was meant to be user-microprogrammable, so you designed an instruction set for what you wanted to do, and then programmed in that. -- Greg -- https://mail.python.org/mailman/listinfo/python-list