qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
9,353,457
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently. How do you pass variables to and from functions properly. In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not work.) ``` a = "foo" def func_1(): b = "bar" print a,b return (b) func_1() print b ``` I am 'expecting' b to be available after the function call, as I have returned it... I appreciate this me not understanding properly how to implement/manage variables Thanks.
2012/02/19
[ "https://Stackoverflow.com/questions/9353457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1191626/" ]
I think this is what you want to do: ``` a = "foo" def func_1(): b = "bar" print a,b return b # Took out parenthasis returned_b = func_1() # Added variable to hold the returned "b" print returned_b ``` It looks like you are just learning to code in general. Your issues look to be with understanding how computer code typically works, not so much with Python in particular. A couple of other things. In the line `a = "foo"`, a is a global variable. This is often frowned upon in programming because it can create confusion (although I feel like it may be used more in Python in particular). It looks like you are having trouble understanding an aspect of how variables work called 'scope'. When you declared the variable `b` inside of `func_1()`, it had only function scope. Once the function exited, the variable no longer existed unless you returned the value AND stored it in another variable, that may, coincidentally, also have been called `b`. I'm not sure you will be able to learn these concepts out of a normal Python book geared towards people who already know how to program. What you probably need is a book that teaches you how to program in general, and also uses Python as the language of choice. As I mentioned in a comment up top, finding the right learning source is key, otherwise you can be in for a world of frustration. Here is an example of how a "normal" program might be set up: ``` def main(): # Calling main() "runs" the program a = add(1,2) print a def add(first, second): # functions are normally declared outside of other functions, result = first + second # that way, they can be used anywhere return result ```
I think you mean, how do I access values that I return from a function. Say you have a function: ``` def func_1(): b = 1 return b ``` If you want the return value from that function, set some variable equal to it, like so: ``` someVariable = func_1() #func_1 executes it's code, and returns the value contained in b ``` You pass arguments to functions by placing them in the parentheses in the function declaration line: ``` a = "foo" def func_1(some_foo): #here some_foo represents a variable you are passing to func_1 b = "bar" print some_foo, b #now you're referencing the variable you passed return b #Now you call the function like this: func_1(a) #passing a (which equals "foo") ``` To pass multiple arguments, your function declaration would look like this: ``` def func_1(some_foo1, some_foo2,...): ``` It's also important to remember that variables declared/initialized inside of a function are only accessible within that function block. Therefore: ``` def func_1(some_foo1): print some_foo1 a = some_foo1 #Doesn't work. The variable some_foo1 doesn't exist outside of `func_1` ```
9,353,457
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently. How do you pass variables to and from functions properly. In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not work.) ``` a = "foo" def func_1(): b = "bar" print a,b return (b) func_1() print b ``` I am 'expecting' b to be available after the function call, as I have returned it... I appreciate this me not understanding properly how to implement/manage variables Thanks.
2012/02/19
[ "https://Stackoverflow.com/questions/9353457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1191626/" ]
I think this is what you want to do: ``` a = "foo" def func_1(): b = "bar" print a,b return b # Took out parenthasis returned_b = func_1() # Added variable to hold the returned "b" print returned_b ``` It looks like you are just learning to code in general. Your issues look to be with understanding how computer code typically works, not so much with Python in particular. A couple of other things. In the line `a = "foo"`, a is a global variable. This is often frowned upon in programming because it can create confusion (although I feel like it may be used more in Python in particular). It looks like you are having trouble understanding an aspect of how variables work called 'scope'. When you declared the variable `b` inside of `func_1()`, it had only function scope. Once the function exited, the variable no longer existed unless you returned the value AND stored it in another variable, that may, coincidentally, also have been called `b`. I'm not sure you will be able to learn these concepts out of a normal Python book geared towards people who already know how to program. What you probably need is a book that teaches you how to program in general, and also uses Python as the language of choice. As I mentioned in a comment up top, finding the right learning source is key, otherwise you can be in for a world of frustration. Here is an example of how a "normal" program might be set up: ``` def main(): # Calling main() "runs" the program a = add(1,2) print a def add(first, second): # functions are normally declared outside of other functions, result = first + second # that way, they can be used anywhere return result ```
The `b` inside `func_1()` is local to the function and not available outside of the function. You need to *assign* the returned value of the function `func_1()` to a variable name in the main body. ``` b = func_1() print b ```
9,353,457
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently. How do you pass variables to and from functions properly. In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not work.) ``` a = "foo" def func_1(): b = "bar" print a,b return (b) func_1() print b ``` I am 'expecting' b to be available after the function call, as I have returned it... I appreciate this me not understanding properly how to implement/manage variables Thanks.
2012/02/19
[ "https://Stackoverflow.com/questions/9353457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1191626/" ]
I think this is what you want to do: ``` a = "foo" def func_1(): b = "bar" print a,b return b # Took out parenthasis returned_b = func_1() # Added variable to hold the returned "b" print returned_b ``` It looks like you are just learning to code in general. Your issues look to be with understanding how computer code typically works, not so much with Python in particular. A couple of other things. In the line `a = "foo"`, a is a global variable. This is often frowned upon in programming because it can create confusion (although I feel like it may be used more in Python in particular). It looks like you are having trouble understanding an aspect of how variables work called 'scope'. When you declared the variable `b` inside of `func_1()`, it had only function scope. Once the function exited, the variable no longer existed unless you returned the value AND stored it in another variable, that may, coincidentally, also have been called `b`. I'm not sure you will be able to learn these concepts out of a normal Python book geared towards people who already know how to program. What you probably need is a book that teaches you how to program in general, and also uses Python as the language of choice. As I mentioned in a comment up top, finding the right learning source is key, otherwise you can be in for a world of frustration. Here is an example of how a "normal" program might be set up: ``` def main(): # Calling main() "runs" the program a = add(1,2) print a def add(first, second): # functions are normally declared outside of other functions, result = first + second # that way, they can be used anywhere return result ```
You've returned it, but not assigned it to anything: ``` def func_1(): b = "bar" a = 2 return a, b a, b = func_1() print b ```
60,445,837
i have an api end point where i am uploading data to using python. end point accepts ``` putHeaders = { 'Authorization': user, 'Content-Type': 'application/octet-stream' } ``` My current code is doing this .Save a dictionary as csv file .Encode csv to utf8 ``` dataFile = open(fileData['name'], 'r').read()).encode('utf-8') ``` .Upload file to api end point ``` fileUpload = requests.put(url, headers=putHeaders, data=(dataFile)) ``` What i am trying to acheive is loading the data without saving so far i tried converting my dictionary to bytes using data = json.dumps(payload).encode('utf-8') and loading to api end point . This works but the output in api end point is not correct. [![enter image description here](https://i.stack.imgur.com/ihIe3.png)](https://i.stack.imgur.com/ihIe3.png) Question Does anyone know how to upload csv type data without actually saving the file ?
2020/02/28
[ "https://Stackoverflow.com/questions/60445837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10004110/" ]
Here's a [working example](https://stackblitz.com/edit/react-ts-w55wqg). You have to install the `@types/faker` package also for getting type definitions. ``` import React, { Component } from 'react'; import { render } from 'react-dom'; import Hello from './Hello'; import './style.css'; import faker from 'faker'; interface AppProps { } interface AppState { name: string; } class App extends Component<AppProps, AppState> { constructor(props) { super(props); this.state = { name: faker.name.firstName() }; } render() { return ( <div> <Hello name={this.state.name} /> </div> ); } } render(<App />, document.getElementById('root')); ``` This is `tsconfig.json` ``` { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react" }, "include": [ "src" ] } ```
I had the same issue and tried the above suggested solution without success. What worked for me, was changing the following line in `tsconfig.json`: `//"module": "esnext", "module": "commonjs",` Or, pass it at the command-line: `ts-node -O '{"module": "commonjs"}' ./server/generate.ts > ./server/database.json` Explanation [1]: Current node.js stable releases do not support ES modules. Additionally, ts-node does not have the required hooks into node.js to support ES modules. You will need to set "module": "commonjs" in your tsconfig.json for your code to work. [1] <https://github.com/TypeStrong/ts-node#import-statements>
2,754,753
I use pylons in my job, but I'm new to django. I'm making an rss filtering application, and so I'd like to have two backend processes that run on a schedule: one to crawl rss feeds for each user, and another to determine relevance of individual posts relative to users' past preferences. In pylons, I'd just write paster commands to update the db with that data. Is there an equivalent in django? EG is there a way to run the equivalent of `python manage.py shell` in a non-interactive mode?
2010/05/02
[ "https://Stackoverflow.com/questions/2754753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303931/" ]
Yes, this is actually how I run my cron backup scripts. You just need to load your virtualenv if you're using virtual environments and your project settings. I hope you can follow this, but after the line `# manage.py shell` you can write your code just as if you were in `manage.py shell` You can import your virtualenv like so: ``` import site site.addsitedir(VIRTUALENV_PATH + '/lib/python2.6/site-packages') ``` You can then add the django project to the path ``` import sys sys.path.append(DJANGO_ROOT) sys.path.append(PROJECT_PATH) ``` Next you load the django settings and chdir to the django project ``` import os from django.core.management import setup_environ from myproject import settings setup_environ(settings) os.chdir(PROJECT_PATH) ``` After this point your environment will be set just like if you started with `manage.py shell` You can then run anything just as if you were in the interactive shell. ``` from application.models import MyModel for element in MyModel: element.delete() ``` Here is my backup file in full. I've abstracted the process out into functions. This would be named `daily_backup` and be put into the `cron.daily` folder to be run daily. You can see how to set up the environment and modify the functionality as needed. ``` #!/usr/bin/env python import sys import os import site import logging from datetime import datetime PROJECT_NAME = 'myproject' DJANGO_ROOT = '/var/www/django' PROJECT_PATH = DJANGO_ROOT + '/' + PROJECT_NAME VIRTUALENV_PATH = '/var/www/envs/'+ PROJECT_NAME BACKUP_DIR = '/var/www/backups/%s/daily' % (PROJECT_NAME) TODAY = datetime.now().strftime('%Y%m%d-%H%M%S') FILE_NAME = PROJECT_NAME + '_' + TODAY site.addsitedir(VIRTUALENV_PATH + '/lib/python2.6/site-packages') sys.path.append(DJANGO_ROOT) sys.path.append(PROJECT_PATH) from django.core.management import setup_environ from myproject import settings setup_environ(settings) os.chdir(PROJECT_PATH) # manage.py shell from django.conf import settings logging.basicConfig(level=logging.WARN) def _setup(): if not os.path.exists(BACKUP_DIR): logging.debug('Creating backup directory ' + BACKUP_DIR) os.mkdir(BACKUP_DIR) os.mkdir(BACKUP_DIR + '/databases') else: logging.debug('Using backup directory ' + BACKUP_DIR) def _remove_old(): logging.debug('Cleaning out old backups') # keep past 7 days command = "find %s* -name '%s*' -mtime +7 -exec rm {} \\;" % (BACKUP_DIR, PROJECT_NAME) os.system(command) def _create_backup(): logging.debug('Backup database') if settings.DATABASE_ENGINE == 'mysql': command = 'mysqldump -u %s --password=%s %s > %s/databases/%s.sql' % (settings.DATABASE_USER, settings.DATABASE_PASSWORD, settings.DATABASE_NAME, BACKUP_DIR, FILE_NAME) else: command = '%s/bin/python %s/manage.py dumpdata --indent=4 > %s/databases/%s.json' % (VIRTUALENV_PATH, PROJECT_PATH, BACKUP_DIR, FILE_NAME) os.system(command) logging.debug('Backup project') command = 'tar -czf %s/%s.tgz -C %s %s/' % (BACKUP_DIR, FILE_NAME, DJANGO_ROOT, PROJECT_NAME) os.system(command) if __name__ == '__main__': _setup() _remove_old() _create_backup() ```
Sounds like you need some twod.wsgi in your life: <http://packages.python.org/twod.wsgi/>
2,754,753
I use pylons in my job, but I'm new to django. I'm making an rss filtering application, and so I'd like to have two backend processes that run on a schedule: one to crawl rss feeds for each user, and another to determine relevance of individual posts relative to users' past preferences. In pylons, I'd just write paster commands to update the db with that data. Is there an equivalent in django? EG is there a way to run the equivalent of `python manage.py shell` in a non-interactive mode?
2010/05/02
[ "https://Stackoverflow.com/questions/2754753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303931/" ]
I think that's what [Custom Management Commands](http://docs.djangoproject.com/en/dev/howto/custom-management-commands/) are there for.
Sounds like you need some twod.wsgi in your life: <http://packages.python.org/twod.wsgi/>
5,482,546
so I have a list with a whole bunch of tuples ``` j = [('jHKT', 'Dlwp Dfbd Gwlgfwqs (1kkk)', 53.0), ('jHKT', 'jbdbjf Bwvbly (1kk1)', 35.0), ('jHKT', 'Tfstzfy (2006)', 9.0), ('jHKT', 'fjznfnt Dwjbzn (1kk1)', 25.0), ('jHKT', 'Vznbsq sfnkz (1k8k)', 4.0), ('jHKT', 'fxzt, Clwwny! (2005)', 8.0), ('jHKT', "Dwfs Thzs jfbn Wf'lf jbllzfd? (1kk1)", 12.0), ('jHKT', 'Chbzljbn wf thf Bwbld (1kk8)', 30.0), ('jHKT', 'Vblfdzctzwn (2006)', 8.0), ('jHKT', 'jwltbl Kwjbbt (1kk5)', 13.0)] ``` and I tried to sort it using the third element of the tuple as the index: note that the list above is just a partial list...the actual list contains thousands of elements anyways so I did: ``` j = sorted(j, key=lambda e : e[2]) ``` but then when I do that, it ends up messing up the third element of the tuple and I highly doubt that it actually sorted...here's another partial list of the output ``` ('jHKT', 'Frz yzng (2004)', 0.0) ('jHKT', 'kff thr Mvp (2003)', 0.0) ('jHKT', 'HzpHkpBvttlr.ckm: Hzp Hkp 4 Lzfr (2001)', 0.0) ('jHKT', 'z Wvlk thr Lznr (1970)', 0.0) ('jHKT', '1971: erzsknrrs kf svr (2007)', 0.0) ('jHKT', 'Wzld Rzdr, Thr (1960)', 0.0) ('jHKT', 'Dzshdkgz (2005)', 0.0) ('jHKT', 'Lzttlr Thzngs, Thr (2006)', 0.0) ('jHKT', 'Trrmznvl rrrkr (2002)', 0.0) ('jHKT', 'Hqngry Bvchrlkrs Clqb, Thr (1999)', 0.0) ('jHKT', 'Swrrt Lkvr, Bzttrr (1967)', 0.0) ('jHKT', 'Trn tk Chz tk (1990)', 0.0) ('jHKT', 'Bvr-Crl-knv (1987)', 0.0) ('jHKT', 'Rknny & Czndy zn vll kf qs (2006)', 0.0) ``` in this case, it ended up resetting all of the third element of the tuples into 0... what did I do wrong?? I'm using python 3 **##############################EDIT####################################** also, when I tried to print the list of tuples, it would return this error: ``` print(j) IOError: [Errno 22] Invalid argument ``` and the printing would abruptly stop...: ``` ('sadfasdf (1991)', 'xcvwert (1985)', 0.0), ('r3sdaf (1991)', 'jkzxkk (1993)', 0.0), ('werwww (1991)', 'Third WhTraceback (most recent call last): ``` and then the error appears **################EDIT###################** On the other hand, printing the list by iterating works just fine so ``` for i in j: print(i) ``` works fine whereas just print(j) would return that error
2011/03/30
[ "https://Stackoverflow.com/questions/5482546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
I think your code works correctly and you see the first part of the list, where key is realy 0.0. You just sort the list in ascending order :-)
It's probably worth comparing the sorted and unsorted lists to see if the sort is actually changing data. You could try something as simple as: ``` print sum(e[2] for e in j) j = sorted(j, key=lambda e : e[2]) print sum(e[2] for e in j) ```
5,482,546
so I have a list with a whole bunch of tuples ``` j = [('jHKT', 'Dlwp Dfbd Gwlgfwqs (1kkk)', 53.0), ('jHKT', 'jbdbjf Bwvbly (1kk1)', 35.0), ('jHKT', 'Tfstzfy (2006)', 9.0), ('jHKT', 'fjznfnt Dwjbzn (1kk1)', 25.0), ('jHKT', 'Vznbsq sfnkz (1k8k)', 4.0), ('jHKT', 'fxzt, Clwwny! (2005)', 8.0), ('jHKT', "Dwfs Thzs jfbn Wf'lf jbllzfd? (1kk1)", 12.0), ('jHKT', 'Chbzljbn wf thf Bwbld (1kk8)', 30.0), ('jHKT', 'Vblfdzctzwn (2006)', 8.0), ('jHKT', 'jwltbl Kwjbbt (1kk5)', 13.0)] ``` and I tried to sort it using the third element of the tuple as the index: note that the list above is just a partial list...the actual list contains thousands of elements anyways so I did: ``` j = sorted(j, key=lambda e : e[2]) ``` but then when I do that, it ends up messing up the third element of the tuple and I highly doubt that it actually sorted...here's another partial list of the output ``` ('jHKT', 'Frz yzng (2004)', 0.0) ('jHKT', 'kff thr Mvp (2003)', 0.0) ('jHKT', 'HzpHkpBvttlr.ckm: Hzp Hkp 4 Lzfr (2001)', 0.0) ('jHKT', 'z Wvlk thr Lznr (1970)', 0.0) ('jHKT', '1971: erzsknrrs kf svr (2007)', 0.0) ('jHKT', 'Wzld Rzdr, Thr (1960)', 0.0) ('jHKT', 'Dzshdkgz (2005)', 0.0) ('jHKT', 'Lzttlr Thzngs, Thr (2006)', 0.0) ('jHKT', 'Trrmznvl rrrkr (2002)', 0.0) ('jHKT', 'Hqngry Bvchrlkrs Clqb, Thr (1999)', 0.0) ('jHKT', 'Swrrt Lkvr, Bzttrr (1967)', 0.0) ('jHKT', 'Trn tk Chz tk (1990)', 0.0) ('jHKT', 'Bvr-Crl-knv (1987)', 0.0) ('jHKT', 'Rknny & Czndy zn vll kf qs (2006)', 0.0) ``` in this case, it ended up resetting all of the third element of the tuples into 0... what did I do wrong?? I'm using python 3 **##############################EDIT####################################** also, when I tried to print the list of tuples, it would return this error: ``` print(j) IOError: [Errno 22] Invalid argument ``` and the printing would abruptly stop...: ``` ('sadfasdf (1991)', 'xcvwert (1985)', 0.0), ('r3sdaf (1991)', 'jkzxkk (1993)', 0.0), ('werwww (1991)', 'Third WhTraceback (most recent call last): ``` and then the error appears **################EDIT###################** On the other hand, printing the list by iterating works just fine so ``` for i in j: print(i) ``` works fine whereas just print(j) would return that error
2011/03/30
[ "https://Stackoverflow.com/questions/5482546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
i too think its ok[in quick glance] .. check this link .. it's about various sorting techniques in python <http://wiki.python.org/moin/HowTo/Sorting/>
It's probably worth comparing the sorted and unsorted lists to see if the sort is actually changing data. You could try something as simple as: ``` print sum(e[2] for e in j) j = sorted(j, key=lambda e : e[2]) print sum(e[2] for e in j) ```
5,482,546
so I have a list with a whole bunch of tuples ``` j = [('jHKT', 'Dlwp Dfbd Gwlgfwqs (1kkk)', 53.0), ('jHKT', 'jbdbjf Bwvbly (1kk1)', 35.0), ('jHKT', 'Tfstzfy (2006)', 9.0), ('jHKT', 'fjznfnt Dwjbzn (1kk1)', 25.0), ('jHKT', 'Vznbsq sfnkz (1k8k)', 4.0), ('jHKT', 'fxzt, Clwwny! (2005)', 8.0), ('jHKT', "Dwfs Thzs jfbn Wf'lf jbllzfd? (1kk1)", 12.0), ('jHKT', 'Chbzljbn wf thf Bwbld (1kk8)', 30.0), ('jHKT', 'Vblfdzctzwn (2006)', 8.0), ('jHKT', 'jwltbl Kwjbbt (1kk5)', 13.0)] ``` and I tried to sort it using the third element of the tuple as the index: note that the list above is just a partial list...the actual list contains thousands of elements anyways so I did: ``` j = sorted(j, key=lambda e : e[2]) ``` but then when I do that, it ends up messing up the third element of the tuple and I highly doubt that it actually sorted...here's another partial list of the output ``` ('jHKT', 'Frz yzng (2004)', 0.0) ('jHKT', 'kff thr Mvp (2003)', 0.0) ('jHKT', 'HzpHkpBvttlr.ckm: Hzp Hkp 4 Lzfr (2001)', 0.0) ('jHKT', 'z Wvlk thr Lznr (1970)', 0.0) ('jHKT', '1971: erzsknrrs kf svr (2007)', 0.0) ('jHKT', 'Wzld Rzdr, Thr (1960)', 0.0) ('jHKT', 'Dzshdkgz (2005)', 0.0) ('jHKT', 'Lzttlr Thzngs, Thr (2006)', 0.0) ('jHKT', 'Trrmznvl rrrkr (2002)', 0.0) ('jHKT', 'Hqngry Bvchrlkrs Clqb, Thr (1999)', 0.0) ('jHKT', 'Swrrt Lkvr, Bzttrr (1967)', 0.0) ('jHKT', 'Trn tk Chz tk (1990)', 0.0) ('jHKT', 'Bvr-Crl-knv (1987)', 0.0) ('jHKT', 'Rknny & Czndy zn vll kf qs (2006)', 0.0) ``` in this case, it ended up resetting all of the third element of the tuples into 0... what did I do wrong?? I'm using python 3 **##############################EDIT####################################** also, when I tried to print the list of tuples, it would return this error: ``` print(j) IOError: [Errno 22] Invalid argument ``` and the printing would abruptly stop...: ``` ('sadfasdf (1991)', 'xcvwert (1985)', 0.0), ('r3sdaf (1991)', 'jkzxkk (1993)', 0.0), ('werwww (1991)', 'Third WhTraceback (most recent call last): ``` and then the error appears **################EDIT###################** On the other hand, printing the list by iterating works just fine so ``` for i in j: print(i) ``` works fine whereas just print(j) would return that error
2011/03/30
[ "https://Stackoverflow.com/questions/5482546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
As others said, the code is perfectly fine. You should try to isolate the situation and try to find out where exactly the issue happened. * Does it happen in a simple script which only contains the list assignment and the sort operation? * Do other list operations work? Try slicing, iterating over it, or sorting without a custom function. * Does it happen in a slice of the current list? [Bisection method](http://en.wikipedia.org/wiki/Bisection_method) is your friend here.
It's probably worth comparing the sorted and unsorted lists to see if the sort is actually changing data. You could try something as simple as: ``` print sum(e[2] for e in j) j = sorted(j, key=lambda e : e[2]) print sum(e[2] for e in j) ```
70,541,783
I'm python user learning R. Frequently, I need to check if columns of a dataframe contain NaN(s). In python, I can simply do ``` import pandas as pd df = pd.DataFrame({'colA': [1, 2, None, 3], 'colB': ['A', 'B', 'C', 'D']}) df.isna().any() ``` giving me ``` colA True colB False dtype: bool ``` In R I'm struggling to find an easy solution. People refer to some apply-like methods but that seems overly complex for such a primitive task. The closest solution I've found is this: ``` library(tidyverse) df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) !complete.cases(t(df)) ``` giving ``` [1] TRUE FALSE ``` That's OKyish but I don't see the column names. If the dataframe has 50 columns I don't know which one has NaNs. Is there a better R solution?
2021/12/31
[ "https://Stackoverflow.com/questions/70541783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2743931/" ]
The best waty to check if columns have NAs is to apply a loop to the columns with a function to check whether there is `any(is.na)`. ``` lapply(df, function(x) any(is.na(x))) $colA [1] TRUE $colB [1] FALSE ``` I can see you load the tidyverse yet did not use it in your example. If we want to do this within the tidyverse, we can use purrr: ``` library(purrr) df %>% map(~any(is.na(.x))) ``` Or with dplyr: ``` library(dplyr) df %>% summarise(across(everything(), ~any(is.na(.x)))) colA colB 1 TRUE FALSE ```
The easiest way would be: ``` df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) is.na(df) ``` **Output:** ``` colA colB [1,] FALSE FALSE [2,] FALSE FALSE [3,] TRUE FALSE [4,] FALSE FALSE ``` **Update**, if you only want to see the rows containing NA: ``` > df[rowSums(is.na(df)) > 0,] colA colB 3 NA C ``` **Update2**, or to get only ColNames with information about NA (thanks to RSale for `anyNA`): ``` > lapply(df, anyNA) $colA [1] TRUE $colB [1] FALSE ```
70,541,783
I'm python user learning R. Frequently, I need to check if columns of a dataframe contain NaN(s). In python, I can simply do ``` import pandas as pd df = pd.DataFrame({'colA': [1, 2, None, 3], 'colB': ['A', 'B', 'C', 'D']}) df.isna().any() ``` giving me ``` colA True colB False dtype: bool ``` In R I'm struggling to find an easy solution. People refer to some apply-like methods but that seems overly complex for such a primitive task. The closest solution I've found is this: ``` library(tidyverse) df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) !complete.cases(t(df)) ``` giving ``` [1] TRUE FALSE ``` That's OKyish but I don't see the column names. If the dataframe has 50 columns I don't know which one has NaNs. Is there a better R solution?
2021/12/31
[ "https://Stackoverflow.com/questions/70541783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2743931/" ]
You can use anyNA: Checks for NA in a vector ``` df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) sapply(df, anyNA) colA colB TRUE FALSE ``` Edit ---- [jay.sf](https://stackoverflow.com/questions/70541783/the-simplest-way-to-check-for-nans-in-columns-r/70541887#comment124698260_70541887) is right. This will check for NaNs. ``` df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) anyNAN <- function(x) { any(is.nan(x)) } sapply(df, anyNAN) ```
The easiest way would be: ``` df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) is.na(df) ``` **Output:** ``` colA colB [1,] FALSE FALSE [2,] FALSE FALSE [3,] TRUE FALSE [4,] FALSE FALSE ``` **Update**, if you only want to see the rows containing NA: ``` > df[rowSums(is.na(df)) > 0,] colA colB 3 NA C ``` **Update2**, or to get only ColNames with information about NA (thanks to RSale for `anyNA`): ``` > lapply(df, anyNA) $colA [1] TRUE $colB [1] FALSE ```
70,541,783
I'm python user learning R. Frequently, I need to check if columns of a dataframe contain NaN(s). In python, I can simply do ``` import pandas as pd df = pd.DataFrame({'colA': [1, 2, None, 3], 'colB': ['A', 'B', 'C', 'D']}) df.isna().any() ``` giving me ``` colA True colB False dtype: bool ``` In R I'm struggling to find an easy solution. People refer to some apply-like methods but that seems overly complex for such a primitive task. The closest solution I've found is this: ``` library(tidyverse) df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) !complete.cases(t(df)) ``` giving ``` [1] TRUE FALSE ``` That's OKyish but I don't see the column names. If the dataframe has 50 columns I don't know which one has NaNs. Is there a better R solution?
2021/12/31
[ "https://Stackoverflow.com/questions/70541783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2743931/" ]
You can use anyNA: Checks for NA in a vector ``` df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) sapply(df, anyNA) colA colB TRUE FALSE ``` Edit ---- [jay.sf](https://stackoverflow.com/questions/70541783/the-simplest-way-to-check-for-nans-in-columns-r/70541887#comment124698260_70541887) is right. This will check for NaNs. ``` df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) anyNAN <- function(x) { any(is.nan(x)) } sapply(df, anyNAN) ```
The best waty to check if columns have NAs is to apply a loop to the columns with a function to check whether there is `any(is.na)`. ``` lapply(df, function(x) any(is.na(x))) $colA [1] TRUE $colB [1] FALSE ``` I can see you load the tidyverse yet did not use it in your example. If we want to do this within the tidyverse, we can use purrr: ``` library(purrr) df %>% map(~any(is.na(.x))) ``` Or with dplyr: ``` library(dplyr) df %>% summarise(across(everything(), ~any(is.na(.x)))) colA colB 1 TRUE FALSE ```
67,126,748
I have a problem with my python(python3.8.5) project! I have two docker containers. One is used for the frontend(container2) using flask. There I have a website where I can send requests(package requests) to the second container(backend). In the backend(container1) I have to create a zip file containing multiple file. That part is done. Now the problem is how can I get this file to the frontend(container2) and from there I need to download it via the website. So I need a solution to send a http request (now I have requests.get(URL to backend)) from the frontend to the backend. In the response I need the zip file which I can download then from the website. I googled already many hours but I cannot find a good solution. I thing it would be good if I don't have to store the zip file on the frontend and on the backend. If possible I would like to have it stored just on the backend and send it to the frontend and directly download it. I hope you understand my problem and can help me. Br
2021/04/16
[ "https://Stackoverflow.com/questions/67126748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15661344/" ]
A probably incomplete solution, that does what you describe. Depending on other concerns (like file size) this might not be what you really want, but it works. As an example I have 2 flask servers: flask1 (backend) and flask2 (frontend): flask1: ``` from flask import Flask, send_file, request app = Flask(__name__) @app.route('/get_file') def get_image(): return send_file(request.args.get('name')) ``` flask2: ``` from flask import Flask, send_file, request import io import requests app = Flask(__name__) @app.route('/get_something') def get_image(): r = requests.get("http://localhost:5000/get_file?name="+request.args.get('name')) return send_file(io.BytesIO(r.content), mimetype=r.headers['Content-Type'], as_attachment=True, attachment_filename="file") ``` To test you can run them on different ports, like: ``` FLASK_APP=flask1.py flask run --port=5000 FLASK_APP=flask2.py flask run --port=8080 ``` Then if you go to the browser and access the frontend with an URL like: http://localhost:8080/get\_something?name=download.png the frontend will "pass" the request to the backend, then re-send what it receives, hence returning the file. Things that code above does not address: file naming and errors.
You could proxy the request from frontend. I assume you use something like react. So if you add a line like: ``` "proxy": "http://backend-container:8080" ``` to your package.json, frontend should proxy to the backend. Now you can send requests like http://front-end/api/hello and it will hit the backend. Not sure if it is the best solution but might work. examples: <https://create-react-app.dev/docs/proxying-api-requests-in-development/> <https://medium.com/bb-tutorials-and-thoughts/react-how-to-proxy-to-backend-server-5588a9e0347> <https://www.twilio.com/blog/react-app-with-node-js-server-proxy>
71,451,635
This is my first question in here. Question is mostly about Python but a little bit about writing crypto trading bot. I need to calculate some indicators about trading like Bollinger Bands, RSI or etc in my bot. Indicators are calculated from candlesticks data in trading. And candlesticks data updated in their time period. For example if use candlestiks data in period 5 minute i need to calculate indicators every 5 min (after candlesticks update), or if i use candlesticks data in period 1 hour period i need to calculate indicators every 1 hour. So, think that i have two classes. One is named with "TradeControl" and it has a attribute named with "candlestick\_data". And second class is named with "CandlestickUpdater". I want to manage updates for "candlestick\_data" in "TradeControl" class from "CandlestickUpdater" class. My problem is about parallel process (or threading) in python. I don't know how to do it proper way. Is there anybody here to give me some advice or sample code. And i am also wondering if i should use mutex-like structures to guard against conditions like race condition. What i am trying to do in code is like below. Also, if you have a different suggestion, I would like to consider it. ``` class TradeControl(): def __init__(self): self.candlestick_data = 0 def update_candlestick(self): """Candlesticks data will be requested from exchange and updated in here""" pass def run_trading_bot(self): while True: """Main trading algorithm is running and using self.candlestick_data in here""" pass pass pass class CandlestickUpdater(): def __init__(self, controller: TradeControl): self.controller = controller def run_candlestick_updater(self): while True: """Candlesticks data updates will be checked in here""" if need_to_update: """TradeControl will be informed in here""" self.controller.update_candlestick() pass pass pass pass ``` Thanks for your replies,
2022/03/12
[ "https://Stackoverflow.com/questions/71451635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It's not quite obvious from your description what `CandlestickUpdater` is for. It looks like its purpose is to notify `TradeControl` that time has come to update `candlestick_data`, whereas updating logic itself is in the `TradeControl.update_candlestick` method. So basically `CandlestickUpdater` is a timer. There are different python libs from scheduling events. [sched](https://docs.python.org/3/library/sched.html) for example. It seems that it can be used for scheduling `TradeControl.update_candlestick` method with a required time period. If you still want to have `CandlestickUpdater` class, I think it can actually work as it's written in your code. You can these classes in threads this way: ```py from threading import Thread trade_control = TradeControl() candlestick_updater = CandlestickUpdater(controller=trace_control) Thread(target=trade_control.update_candlestick).start() Thread(target=candlestick_updater.run_candlestick_updater).start() ``` Speaking of race condition. Well, it can be the case, but it depends on your implementation of `update_candlestick` and `run_trading_bot`. It's better to create `TradeControl.lock: threading.Lock` attribute and use it when updating `candlestick_data`: <https://docs.python.org/3/library/threading.html#lock-objects>. There is also another way of communicating between threads without direct methods calls. Look at the [blinker](https://pypi.org/project/blinker/). It's nice lib to implement event-driven scenarios. You just need to create a "signal" object (outside of `TradeControl` and `CandlestickUpdater` classes) and connect `TradeControl.update_candlestick` method to it. Then you just call "signal.send" method in "CandlestickUpdater.run\_candlestick\_updater" and connected functions will be executed. It can be a little bit tricky to connect instance method to signal. But there are some solutions for it. The easiest one is to make `CandlestickUpdater.run_candlestick_updater` static if it's possible for you.
> > **Q :** *" ... should (I) use mutex-like structures to guard against conditions like race condition "... ?* > > > **A :** Given the facts, how the Python Interpreter works ( since ever & most probably forever, as Guido von Rossum has expressed himself ) with all its threads, distributing ***"a permission to work"*** for ~ 100 [ms] quanta of time, via central **G**-lobal **I**-nterpreter **L**-lock ( GIL-lock ), there are no race-conditions to meet in Python ( unless software-created live-locks or some indeed artificially generated mutually blocked obscurities ). In other words, all Python Interpreter threads are principally collision-free, as GIL-lock re-`[SERIAL]`-ises any and all threads to one-and-only-ONE-works-(if-GIL-lock-owner)-ALL-others-WAIT... > > **Q :** *" My problem is about parallel process (or threading) in python. "* > > > **A :** Thread are never even "just"-`[CONCURRENT]` in Python, so never form a True-`[PARALLEL]` form of process-orchestration at all. Processes escape from the GIL-lock re-`[SERIAL]`-isation tyrany, yet, at many add-on costs and barriers from a shift into a new paradigm of [distributed-processing](/questions/tagged/distributed-processing "show questions tagged 'distributed-processing'") If Process-based `[CONCURRENT]`-processinghappens to get onto the scene : ------------------------------------------------------------------------- If going into process-based "just"-`[CONCURRENT]`-processing ( using `joblib.Parallel(...)delayed(...)`, `multiprocessing` or other modules ), there you start with as many independent ( each being inside still GIL-lock driven, but independently one from any other - an uncoordinated freedom of mutually independent GIL-locks' reservations ) processes, top-down copies ( all Win, some MacOS ) of the original Python Interpreter ( yes, due to RAM-footprint + RAM-I/O it is `[SPACE]`- and `[TIME]`-domain expensive ). Here you cannot enjoy calling local-process Class-method or similar mechanics for propagating state-changes in-process, as your "receiver" may reside in the original Python Interpreter process, which has principally separate address-space that your local-process cannot ( and shall never ) be allowed to touch, the less change a single bit thereof. Yet we may use here tools for distributed-computing signalling and/or message-passing, like [zeromq](/questions/tagged/zeromq "show questions tagged 'zeromq'"), [pyzmq](/questions/tagged/pyzmq "show questions tagged 'pyzmq'"), [nanomsg](/questions/tagged/nanomsg "show questions tagged 'nanomsg'"), [pynng](/questions/tagged/pynng "show questions tagged 'pynng'") and the likes, that meet your needs, some of which have vast Quant/Fintech installed base with many language bindings/wrappers ( we use ZeroMQ since v2.11+ among python AI/ML-Ensemble-of-Predictors, MQL4 for driving FX-Broker XTOs & MQL4 Backtesting simulation-farm, python non-blocking distributed logger, python remote CLI agents, scale-out C language tools for multiple systems' integration glue logic, signal-provisioning service, subscriber-management, ... macro-system health-monitor & alarm system ) The above sketched distributed-computing macro-system spans several platforms and has no problems to process sub-millisecond cadence of FX-market stream of `QUOTE`-events, handle tens of thousands managed-trade positions ( driving live FX-market XTO-modifications ) and maintain all QuantFX-technical indicator re-calculations on the fly. --- Building one's own event-responsive MVC-framework -OR-re-use a robust & stable & feature-rich one : --------------------------------------------------------------------------------------------------- Having said the above, you may re-use another concept, when living in a comfort of plenty of time when going into just an H1-timeframe operations. have o look on `Tkinter.mainloop()`-examples, with tools for both event-driven & timed-callbacks, that will permit you anything within the ceiling of your imagination, including GUI and infinitely many modes of Man-Machine-Interaction modes and gadgets.
70,648,020
[![enter image description here](https://i.stack.imgur.com/dbDhf.png)](https://i.stack.imgur.com/dbDhf.png) I configured python 3.6 in JetBrains initially but uninstalled it today since it reached end-of-life. I installed version 3.10 but I keep getting the error that "Python 3.1 has reached end of date." Clicking on 'Configure Python Interpreter'>Project Settings>Modules>Dependencies>Python 3.10 doesn't solve the problem.[![enter image description here](https://i.stack.imgur.com/J6AWY.png)](https://i.stack.imgur.com/J6AWY.png) Using File->settings and searching for interpreter shows only this option [![enter image description here](https://i.stack.imgur.com/iCagV.png)](https://i.stack.imgur.com/iCagV.png). Used "Use SDK of module" and "specified Python Interpreter" options but the error persists. I can't find any other resolution on the JetBrains support page for this. Thank you for your help! * I tried removing all existing configuration SDK from File | Project Structure | Platform Settings | SDKs and adding Python 3.10 again. * A screenshot of the interpreter configured in an existing virtual environment is attached here. [![enter image description here](https://i.stack.imgur.com/3Gop3.png)](https://i.stack.imgur.com/3Gop3.png) * When I click ok, I get this error.[![enter image description here](https://i.stack.imgur.com/MThnm.png)](https://i.stack.imgur.com/MThnm.png) * I figured this may be since my venv was initially configured in the 3.6 version but I'm not able to configure a new venv with Python 3.10. (The Ok option is greyed out) [![enter image description here](https://i.stack.imgur.com/iJcKv.png)](https://i.stack.imgur.com/iJcKv.png) While trying to add venv manually using /venv or /venv2, I get the error- 'Specified path cannot be found' [![enter image description here](https://i.stack.imgur.com/rlTIz.png)](https://i.stack.imgur.com/rlTIz.png)
2022/01/10
[ "https://Stackoverflow.com/questions/70648020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13706804/" ]
We can do this with only one function, `Array.find()`. We can do this by checking if it is equal to the `Remove invalid product` inside the function. See the example below. ```js const responses = [{ "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid product" } ]; console.log(responses.find(status => status?.status === 'Remove invalid product')?.status ? responses.find(status => status?.status === 'Remove invalid product').status : "No invalid product found"); ``` **Hoped this helped!**
You can do it using `array.find()`. Try this code it's help you ! ``` function App() { const responses = [ { "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid product" } ]; return ( <div> checkResponses : {responses.find(x => { if (x && x.status == "Remove invalid product") return x.status }).status}</div> ); }; export default App; ```
70,648,020
[![enter image description here](https://i.stack.imgur.com/dbDhf.png)](https://i.stack.imgur.com/dbDhf.png) I configured python 3.6 in JetBrains initially but uninstalled it today since it reached end-of-life. I installed version 3.10 but I keep getting the error that "Python 3.1 has reached end of date." Clicking on 'Configure Python Interpreter'>Project Settings>Modules>Dependencies>Python 3.10 doesn't solve the problem.[![enter image description here](https://i.stack.imgur.com/J6AWY.png)](https://i.stack.imgur.com/J6AWY.png) Using File->settings and searching for interpreter shows only this option [![enter image description here](https://i.stack.imgur.com/iCagV.png)](https://i.stack.imgur.com/iCagV.png). Used "Use SDK of module" and "specified Python Interpreter" options but the error persists. I can't find any other resolution on the JetBrains support page for this. Thank you for your help! * I tried removing all existing configuration SDK from File | Project Structure | Platform Settings | SDKs and adding Python 3.10 again. * A screenshot of the interpreter configured in an existing virtual environment is attached here. [![enter image description here](https://i.stack.imgur.com/3Gop3.png)](https://i.stack.imgur.com/3Gop3.png) * When I click ok, I get this error.[![enter image description here](https://i.stack.imgur.com/MThnm.png)](https://i.stack.imgur.com/MThnm.png) * I figured this may be since my venv was initially configured in the 3.6 version but I'm not able to configure a new venv with Python 3.10. (The Ok option is greyed out) [![enter image description here](https://i.stack.imgur.com/iJcKv.png)](https://i.stack.imgur.com/iJcKv.png) While trying to add venv manually using /venv or /venv2, I get the error- 'Specified path cannot be found' [![enter image description here](https://i.stack.imgur.com/rlTIz.png)](https://i.stack.imgur.com/rlTIz.png)
2022/01/10
[ "https://Stackoverflow.com/questions/70648020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13706804/" ]
You can do it using `array.find()`. Try this code it's help you ! ``` function App() { const responses = [ { "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid product" } ]; return ( <div> checkResponses : {responses.find(x => { if (x && x.status == "Remove invalid product") return x.status }).status}</div> ); }; export default App; ```
**strong text** ``` const responses = [ { "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid product" } ]; console.log(responses.find(variable => variable?.hasOwnProperty('status'))?.status); ```
70,648,020
[![enter image description here](https://i.stack.imgur.com/dbDhf.png)](https://i.stack.imgur.com/dbDhf.png) I configured python 3.6 in JetBrains initially but uninstalled it today since it reached end-of-life. I installed version 3.10 but I keep getting the error that "Python 3.1 has reached end of date." Clicking on 'Configure Python Interpreter'>Project Settings>Modules>Dependencies>Python 3.10 doesn't solve the problem.[![enter image description here](https://i.stack.imgur.com/J6AWY.png)](https://i.stack.imgur.com/J6AWY.png) Using File->settings and searching for interpreter shows only this option [![enter image description here](https://i.stack.imgur.com/iCagV.png)](https://i.stack.imgur.com/iCagV.png). Used "Use SDK of module" and "specified Python Interpreter" options but the error persists. I can't find any other resolution on the JetBrains support page for this. Thank you for your help! * I tried removing all existing configuration SDK from File | Project Structure | Platform Settings | SDKs and adding Python 3.10 again. * A screenshot of the interpreter configured in an existing virtual environment is attached here. [![enter image description here](https://i.stack.imgur.com/3Gop3.png)](https://i.stack.imgur.com/3Gop3.png) * When I click ok, I get this error.[![enter image description here](https://i.stack.imgur.com/MThnm.png)](https://i.stack.imgur.com/MThnm.png) * I figured this may be since my venv was initially configured in the 3.6 version but I'm not able to configure a new venv with Python 3.10. (The Ok option is greyed out) [![enter image description here](https://i.stack.imgur.com/iJcKv.png)](https://i.stack.imgur.com/iJcKv.png) While trying to add venv manually using /venv or /venv2, I get the error- 'Specified path cannot be found' [![enter image description here](https://i.stack.imgur.com/rlTIz.png)](https://i.stack.imgur.com/rlTIz.png)
2022/01/10
[ "https://Stackoverflow.com/questions/70648020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13706804/" ]
We can do this with only one function, `Array.find()`. We can do this by checking if it is equal to the `Remove invalid product` inside the function. See the example below. ```js const responses = [{ "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid product" } ]; console.log(responses.find(status => status?.status === 'Remove invalid product')?.status ? responses.find(status => status?.status === 'Remove invalid product').status : "No invalid product found"); ``` **Hoped this helped!**
**strong text** ``` const responses = [ { "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid product" } ]; console.log(responses.find(variable => variable?.hasOwnProperty('status'))?.status); ```
12,491,731
I am using tkMessageBox.showinfo ([info at tutorialspoint](http://www.tutorialspoint.com/python/tk_messagebox.htm)) to popup warnings in my program. The problem happens only when the warning is called with a second TopLevel window (apart from the main one) on screen: in this case the warning remains hidden behind the second TL window. I tried to call it thus: ``` tkMessageBox.showinfo(title='Warning',message=s).lift() ``` but it doesnt work. Any ideas?
2012/09/19
[ "https://Stackoverflow.com/questions/12491731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538256/" ]
I think the message box is only ever guaranteed to be above its parent. If you create a second toplevel and you want a messagebox to be on top of that second window, make that second window the parent of the messagebox. ``` tl2 = tk.Toplevel(...) ... tkMessageBox.showinfo("Say Hello", "Hello World", parent=tl2) ```
I do not see the issue that you describe. The code I wrote below is just about the minimum needed to create a window which creates a second window. The second window creates an info box using the `showinfo` method. I wonder whether you have something besides this. (Note that I made the windows somewhat large in order to attempt cover up the info window.) ``` from Tkinter import Tk, Button, Toplevel import tkMessageBox top = Tk() def make_window(): t = Toplevel(top) t.title("I'm Window 2. Look at me too!") B2 = Button(t, text = "Click me", command = hello) B2.pack() t.geometry('500x500+50+50') def hello(): tkMessageBox.showinfo("Say Hello", "Hello World") B1 = Button(top, text = "New Window", command = make_window) B1.pack() top.title("I'm Window 1. Look at me!") top.geometry('500x500+100+100') top.mainloop() ``` This was tested on Windows 7 (64-bit) using Python 2.7 (32-bit). It produces something like this: ![enter image description here](https://i.stack.imgur.com/20apT.png)
57,672,921
For clarity, i was looking for a way to compile multiple regex at once. For simplicity, let's say that every expression should be in the format `(.*) something (.*)`. There will be no more than 60 expressions to be tested. As seen [here](https://stackoverflow.com/questions/42136040/how-to-combine-multiple-regex-into-single-one-in-python), i finally wrote the following. ```py import re re1 = r'(.*) is not (.*)' re2 = r'(.*) is the same size as (.*)' re3 = r'(.*) is a word, not (.*)' re4 = r'(.*) is world know, not (.*)' sentences = ["foo2 is a word, not bar2"] for sentence in sentences: match = re.compile("(%s|%s|%s|%s)" % (re1, re2, re3, re4)).search(sentence) if match is not None: print(match.group(1)) print(match.group(2)) print(match.group(3)) ``` As regex are separated by a pipe, i thought that it will be automatically exited once a rule has been matched. Executing the code, i have ``` foo2 is a word, not bar2 None None ``` But by inverting re3 and re1 in re.compile `match = re.compile("(%s|%s|%s|%s)" % (re3, re2, re1, re4)).search(sentence)`, i have ``` foo2 is a word, not bar2 foo2 bar2 ``` As far as i can understand, first rule is executed but not the others. Can someone please point me on the right direction on this case ? Kind regards,
2019/08/27
[ "https://Stackoverflow.com/questions/57672921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2243607/" ]
There are various issues with your example: 1. You are using a *capturing* group, so it gets the index `1` that you'd expect to reference the first group of the inner regexes. Use a non-capturing group `(?:%s|%s|%s|%s)` instead. 2. Group indexes increase even inside `|`. So`(?:(a)|(b)|(c))` you'd get: ``` >>> re.match(r'(?:(a)|(b)|(c))', 'a').groups() ('a', None, None) >>> re.match(r'(?:(a)|(b)|(c))', 'b').groups() (None, 'b', None) >>> re.match(r'(?:(a)|(b)|(c))', 'c').groups() (None, None, 'c') ``` It seems like you'd expect to only have one group 1 that returns either `a`, `b` or `c` depending on the branch... no, indexes are assigned in order from left to right without taking account the grammar of the regex. The [`regex`](https://pypi.org/project/regex/) module does what you want with numbering the groups. If you want to use the built-in module you'll have to live with the fact that numbering is not the same between different branches of the regex *if* you use named groups: ``` >>> import regex >>> regex.match(r'(?:(?P<x>a)|(?P<x>b)|(?P<x>c))', 'a').groups() ('a',) >>> regex.match(r'(?:(?P<x>a)|(?P<x>b)|(?P<x>c))', 'b').groups() ('b',) >>> regex.match(r'(?:(?P<x>a)|(?P<x>b)|(?P<x>c))', 'c').groups() ('c',) ``` (Trying to use that regex with `re` will give an error for duplicated groups).
Giacomo answered the question. However, I also suggest: 1) put the "compile" before the loop, 2) gather non empty groups in a list, 3) think about using (.+) instead of (.\*) in re1,re2,etc. ``` rex= re.compile("%s|%s|%s|%s" % (re1, re2, re3, re4)) for sentence in sentences: match = rex.search(sentence) if match: l=[ g for g in match.groups() if g!=None ] print(l[0],l[1]) ```
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was not a perfect square') ``` But it's ugly and I don't really trust it for large integers. I could iterate through the squares and give up if I've exceeded the value, but I assume it would be kinda slow to do something like that. Also I guess I'd probably be reinventing the wheel, something like this must surely exist in python already...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
Sorry for the very late response; I just stumbled onto this page. In case anyone visits this page in the future, the python module gmpy2 is designed to work with very large inputs, and includes among other things an integer square root function. Example: ``` >>> import gmpy2 >>> gmpy2.isqrt((10**100+1)**2) mpz(10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001L) >>> gmpy2.isqrt((10**100+1)**2 - 1) mpz(10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L) ``` Granted, everything will have the "mpz" tag, but mpz's are compatible with int's: ``` >>> gmpy2.mpz(3)*4 mpz(12) >>> int(gmpy2.mpz(12)) 12 ``` See [my other answer](https://stackoverflow.com/a/31224469/2554867) for a discussion of this method's performance relative to some other answers to this question. Download: <https://code.google.com/p/gmpy/>
One option would be to use the `decimal` module, and do it in sufficiently-precise floats: ``` import decimal def isqrt(n): nd = decimal.Decimal(n) with decimal.localcontext() as ctx: ctx.prec = n.bit_length() i = int(nd.sqrt()) if i**2 != n: raise ValueError('input was not a perfect square') return i ``` which I think should work: ``` >>> isqrt(1) 1 >>> isqrt(7**14) == 7**7 True >>> isqrt(11**1000) == 11**500 True >>> isqrt(11**1000+1) Traceback (most recent call last): File "<ipython-input-121-e80953fb4d8e>", line 1, in <module> isqrt(11**1000+1) File "<ipython-input-100-dd91f704e2bd>", line 10, in isqrt raise ValueError('input was not a perfect square') ValueError: input was not a perfect square ```
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was not a perfect square') ``` But it's ugly and I don't really trust it for large integers. I could iterate through the squares and give up if I've exceeded the value, but I assume it would be kinda slow to do something like that. Also I guess I'd probably be reinventing the wheel, something like this must surely exist in python already...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
Python's default `math` library has an integer square root function: > > ### [`math.isqrt(n)`](https://docs.python.org/3/library/math.html#math.isqrt) > > > Return the integer square root of the nonnegative integer *n*. This is the floor of the exact square root of *n*, or equivalently the greatest integer a such that *a² ≤ n*. > > >
Your function fails for large inputs: ``` In [26]: isqrt((10**100+1)**2) ValueError: input was not a perfect square ``` There is a [recipe on the ActiveState site](http://code.activestate.com/recipes/577821-integer-square-root-function/) which should hopefully be more reliable since it uses integer maths only. It is based on an earlier StackOverflow question: [Writing your own square root function](https://stackoverflow.com/questions/1623375/writing-your-own-square-root-function)
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was not a perfect square') ``` But it's ugly and I don't really trust it for large integers. I could iterate through the squares and give up if I've exceeded the value, but I assume it would be kinda slow to do something like that. Also I guess I'd probably be reinventing the wheel, something like this must surely exist in python already...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
Seems like you could check like this: ``` if int(math.sqrt(n))**2 == n: print n, 'is a perfect square' ``` Update: As you pointed out the above fails for large values of `n`. For those the following looks promising, which is an adaptation of the example C code, by Martin Guy @ UKC, June 1985, for the relatively simple looking binary numeral digit-by-digit calculation method mentioned in the Wikipedia article [Methods of computing square roots](http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_.28base_2.29): ``` from math import ceil, log def isqrt(n): res = 0 bit = 4**int(ceil(log(n, 4))) if n else 0 # smallest power of 4 >= the argument while bit: if n >= res + bit: n -= res + bit res = (res >> 1) + bit else: res >>= 1 bit >>= 2 return res if __name__ == '__main__': from math import sqrt # for comparison purposes for i in range(17)+[2**53, (10**100+1)**2]: is_perfect_sq = isqrt(i)**2 == i print '{:21,d}: math.sqrt={:12,.7G}, isqrt={:10,d} {}'.format( i, sqrt(i), isqrt(i), '(perfect square)' if is_perfect_sq else '') ``` Output: ```none 0: math.sqrt= 0, isqrt= 0 (perfect square) 1: math.sqrt= 1, isqrt= 1 (perfect square) 2: math.sqrt= 1.414214, isqrt= 1 3: math.sqrt= 1.732051, isqrt= 1 4: math.sqrt= 2, isqrt= 2 (perfect square) 5: math.sqrt= 2.236068, isqrt= 2 6: math.sqrt= 2.44949, isqrt= 2 7: math.sqrt= 2.645751, isqrt= 2 8: math.sqrt= 2.828427, isqrt= 2 9: math.sqrt= 3, isqrt= 3 (perfect square) 10: math.sqrt= 3.162278, isqrt= 3 11: math.sqrt= 3.316625, isqrt= 3 12: math.sqrt= 3.464102, isqrt= 3 13: math.sqrt= 3.605551, isqrt= 3 14: math.sqrt= 3.741657, isqrt= 3 15: math.sqrt= 3.872983, isqrt= 3 16: math.sqrt= 4, isqrt= 4 (perfect square) 9,007,199,254,740,992: math.sqrt=9.490627E+07, isqrt=94,906,265 100,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,020,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,001: math.sqrt= 1E+100, isqrt=10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,001 (perfect square) ```
Inspired by all answers, decided to implement in pure C++ several best methods from these answers. As everybody knows C++ is always faster than Python. To glue C++ and Python I used [Cython](https://cython.org/). It allows to make out of C++ a Python module and then call C++ functions directly from Python functions. Also as complementary I provided not only Python-adopted code, but pure C++ with tests too. Here are timings from pure C++ tests: ``` Test 'GMP', bits 64, time 0.000001 sec Test 'AndersKaseorg', bits 64, time 0.000003 sec Test 'Babylonian', bits 64, time 0.000006 sec Test 'ChordTangent', bits 64, time 0.000018 sec Test 'GMP', bits 50000, time 0.000118 sec Test 'AndersKaseorg', bits 50000, time 0.002777 sec Test 'Babylonian', bits 50000, time 0.003062 sec Test 'ChordTangent', bits 50000, time 0.009120 sec ``` and same C++ functions but as adopted Python module have timings: ``` Bits 50000 math.isqrt: 2.819 ms gmpy2.isqrt: 0.166 ms ISqrt_GMP: 0.252 ms ISqrt_AndersKaseorg: 3.338 ms ISqrt_Babylonian: 3.756 ms ISqrt_ChordTangent: 10.564 ms ``` My Cython-C++ is nice in a sence as a framework for those people who want to write and test his own C++ method from Python directly. As you noticed in above timings as example I used following methods: 1. [math.isqrt](https://docs.python.org/3/library/math.html#math.isqrt), implementation from standard library. 2. [gmpy2.isqrt](https://gmpy2.readthedocs.io/en/latest/mpz.html), GMPY2 library's implementation. 3. [ISqrt\_GMP](https://gmpy2.readthedocs.io/en/latest/mpz.html) - same as GMPY2, but using my Cython module, there I use C++ GMP library (`<gmpxx.h>`) directly. 4. [ISqrt\_AndersKaseorg](https://stackoverflow.com/a/53983683/941531), code taken from [answer](https://stackoverflow.com/a/53983683/941531) of @AndersKaseorg. 5. [ISqrt\_Babylonian](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method), method taken from Wikipedia [article](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method), so-called Babylonian method. My own implementation as I understand it. 6. [ISqrt\_ChordTangent](https://stackoverflow.com/a/71530812/941531), it is my own method that I called Chord-Tangent, because it uses chord and tangent line to iteratively shorten interval of search. This method is described in moderate details in [my other article](https://stackoverflow.com/a/71530812/941531). This method is nice because it searches not only square root, but also K-th root for any K. I drew a [small picture](https://i.stack.imgur.com/s2AS9.jpg) showing details of this algorithm. Regarding compiling C++/Cython code, I used [GMP](http://gmplib.org/) library. You need to install it first, under Linux it is easy through `sudo apt install libgmp-dev`. Under Windows easiest is to install really great program [VCPKG](https://vcpkg.io/), this is software Package Manager, similar to APT in Linux. VCPKG compiles all packages from sources using [Visual Studio](https://visualstudio.com/) (don't forget to [install](https://visualstudio.microsoft.com/free-developer-offers/) Community version of Visual Studio). After installing VCPKG you can install GMP by `vcpkg install gmp`. Also you may install [MPIR](http://mpir.org/), this is alternative fork of GMP, you can install it through `vcpkg install mpir`. After GMP is installed under Windows please edit my Python code and replace path to include directory and library file. VCPKG at the end of installation should show you path to ZIP file with GMP library, there are .lib and .h files. You may notice in Python code that I also designed special handy `cython_compile()` function that I use to compile any C++ code into Python module. This function is really good as it allows for you to easily plug-in any C++ code into Python, this can be reused many times. If you have any questions or suggestions, or something doesn't work on your PC, please write in comments. Below first I show code in Python, afterwards in C++. See `Try it online!` link above C++ code to run code online on GodBolt servers. Both code snippets I fully runnable from scratch as they are, nothing needs to be edited in them. ```py def cython_compile(srcs): import json, hashlib, os, glob, importlib, sys, shutil, tempfile srch = hashlib.sha256(json.dumps(srcs, sort_keys = True, ensure_ascii = True).encode('utf-8')).hexdigest().upper()[:12] pdir = 'cyimp' if len(glob.glob(f'{pdir}/cy{srch}*')) == 0: class ChDir: def __init__(self, newd): self.newd = newd def __enter__(self): self.curd = os.getcwd() os.chdir(self.newd) return self def __exit__(self, ext, exv, tb): os.chdir(self.curd) os.makedirs(pdir, exist_ok = True) with tempfile.TemporaryDirectory(dir = pdir) as td, ChDir(str(td)) as chd: os.makedirs(pdir, exist_ok = True) for k, v in srcs.items(): with open(f'cys{srch}_{k}', 'wb') as f: f.write(v.replace('{srch}', srch).encode('utf-8')) import numpy as np from setuptools import setup, Extension from Cython.Build import cythonize sys.argv += ['build_ext', '--inplace'] setup( ext_modules = cythonize( Extension( f'{pdir}.cy{srch}', [f'cys{srch}_{k}' for k in filter(lambda e: e[e.rfind('.') + 1:] in ['pyx', 'c', 'cpp'], srcs.keys())], depends = [f'cys{srch}_{k}' for k in filter(lambda e: e[e.rfind('.') + 1:] not in ['pyx', 'c', 'cpp'], srcs.keys())], extra_compile_args = ['/O2', '/std:c++latest', '/ID:/dev/_3party/vcpkg_bin/gmp/include/', ], ), compiler_directives = {'language_level': 3, 'embedsignature': True}, annotate = True, ), include_dirs = [np.get_include()], ) del sys.argv[-2:] for f in glob.glob(f'{pdir}/cy{srch}*'): shutil.copy(f, f'./../') print('Cython module:', f'cy{srch}') return importlib.import_module(f'{pdir}.cy{srch}') def cython_import(): srcs = { 'lib.h': """ #include <cstring> #include <cstdint> #include <stdexcept> #include <tuple> #include <iostream> #include <string> #include <type_traits> #include <sstream> #include <gmpxx.h> #pragma comment(lib, "D:/dev/_3party/vcpkg_bin/gmp/lib/gmp.lib") #define ASSERT_MSG(cond, msg) { if (!(cond)) throw std::runtime_error("Assertion (" #cond ") failed at line " + std::to_string(__LINE__) + "! Msg '" + std::string(msg) + "'."); } #define ASSERT(cond) ASSERT_MSG(cond, "") #define LN { std::cout << "LN " << __LINE__ << std::endl; } using u32 = uint32_t; using u64 = uint64_t; template <typename T> size_t BitLen(T n) { if constexpr(std::is_same_v<std::decay_t<T>, mpz_class>) return mpz_sizeinbase(n.get_mpz_t(), 2); else { size_t cnt = 0; while (n >= (1ULL << 32)) { cnt += 32; n >>= 32; } while (n >= (1 << 8)) { cnt += 8; n >>= 8; } while (n) { ++cnt; n >>= 1; } return cnt; } } template <typename T> T ISqrt_Babylonian(T const & y) { // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method if (y <= 1) return y; T x = T(1) << (BitLen(y) / 2), a = 0, b = 0, limit = 3; while (true) { size_t constexpr loops = 3; for (size_t i = 0; i < loops; ++i) { if (i + 1 >= loops) a = x; b = y; b /= x; x += b; x >>= 1; } if (b < a) std::swap(a, b); if (b - a > limit) continue; ++b; for (size_t i = 0; a <= b; ++a, ++i) if (a * a > y) { if (i == 0) break; else return a - 1; } ASSERT(false); } } template <typename T> T ISqrt_AndersKaseorg(T const & n) { // https://stackoverflow.com/a/53983683/941531 if (n > 0) { T y = 0, x = T(1) << ((BitLen(n) + 1) >> 1); while (true) { y = (x + n / x) >> 1; if (y >= x) return x; x = y; } } else if (n == 0) return 0; else ASSERT_MSG(false, "square root not defined for negative numbers"); } template <typename T> T ISqrt_GMP(T const & y) { // https://gmplib.org/manual/Integer-Roots mpz_class r, n; bool constexpr is_mpz = std::is_same_v<std::decay_t<T>, mpz_class>; if constexpr(is_mpz) n = y; else { static_assert(sizeof(T) <= 8); n = u32(y >> 32); n <<= 32; n |= u32(y); } mpz_sqrt(r.get_mpz_t(), n.get_mpz_t()); if constexpr(is_mpz) return r; else return (u64(mpz_get_ui(mpz_class(r >> 32).get_mpz_t())) << 32) | u64(mpz_get_ui(mpz_class(r & u32(-1)).get_mpz_t())); } template <typename T> T KthRoot_ChordTangent(T const & n, size_t k = 2) { // https://i.stack.imgur.com/et9O0.jpg if (n <= 1) return n; auto KthPow = [&](auto const & x){ T y = x * x; for (size_t i = 2; i < k; ++i) y *= x; return y; }; auto KthPowDer = [&](auto const & x){ T y = x * u32(k); for (size_t i = 1; i + 1 < k; ++i) y *= x; return y; }; size_t root_bit_len = (BitLen(n) + k - 1) / k; T hi = T(1) << root_bit_len, x_begin = hi >> 1, x_end = hi, y_begin = KthPow(x_begin), y_end = KthPow(x_end), x_mid = 0, y_mid = 0, x_n = 0, y_n = 0, tangent_x = 0, chord_x = 0; for (size_t icycle = 0; icycle < (1 << 30); ++icycle) { if (x_end <= x_begin + 2) break; if constexpr(0) { // Do Binary Search step if needed x_mid = (x_begin + x_end) >> 1; y_mid = KthPow(x_mid); if (y_mid > n) { x_end = x_mid; y_end = y_mid; } else { x_begin = x_mid; y_begin = y_mid; } } // (y_end - y_begin) / (x_end - x_begin) = (n - y_begin) / (x_n - x_begin) -> x_n = x_begin + (n - y_begin) * (x_end - x_begin) / (y_end - y_begin); y_n = KthPow(x_n); tangent_x = x_n + (n - y_n) / KthPowDer(x_n) + 1; chord_x = x_n + (n - y_n) * (x_end - x_n) / (y_end - y_n); //ASSERT(chord_x <= tangent_x); x_begin = chord_x; x_end = tangent_x; y_begin = KthPow(x_begin); y_end = KthPow(x_end); //ASSERT(y_begin <= n); //ASSERT(y_end > n); } for (size_t i = 0; x_begin <= x_end; ++x_begin, ++i) if (x_begin * x_begin > n) { if (i == 0) break; else return x_begin - 1; } ASSERT(false); return 0; } mpz_class FromLimbs(uint64_t * limbs, uint64_t * cnt) { mpz_class r; mpz_import(r.get_mpz_t(), *cnt, -1, 8, -1, 0, limbs); return r; } void ToLimbs(mpz_class const & n, uint64_t * limbs, uint64_t * cnt) { uint64_t cnt_before = *cnt; size_t cnt_res = 0; mpz_export(limbs, &cnt_res, -1, 8, -1, 0, n.get_mpz_t()); ASSERT(cnt_res <= cnt_before); std::memset(limbs + cnt_res, 0, (cnt_before - cnt_res) * 8); *cnt = cnt_res; } void ISqrt_GMP_Py(uint64_t * limbs, uint64_t * cnt) { ToLimbs(ISqrt_GMP<mpz_class>(FromLimbs(limbs, cnt)), limbs, cnt); } void ISqrt_AndersKaseorg_Py(uint64_t * limbs, uint64_t * cnt) { ToLimbs(ISqrt_AndersKaseorg<mpz_class>(FromLimbs(limbs, cnt)), limbs, cnt); } void ISqrt_Babylonian_Py(uint64_t * limbs, uint64_t * cnt) { ToLimbs(ISqrt_Babylonian<mpz_class>(FromLimbs(limbs, cnt)), limbs, cnt); } void ISqrt_ChordTangent_Py(uint64_t * limbs, uint64_t * cnt) { ToLimbs(KthRoot_ChordTangent<mpz_class>(FromLimbs(limbs, cnt), 2), limbs, cnt); } """, 'main.pyx': r""" # distutils: language = c++ # distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION import numpy as np cimport numpy as np cimport cython from libc.stdint cimport * cdef extern from "cys{srch}_lib.h" nogil: void ISqrt_ChordTangent_Py(uint64_t * limbs, uint64_t * cnt); void ISqrt_GMP_Py(uint64_t * limbs, uint64_t * cnt); void ISqrt_AndersKaseorg_Py(uint64_t * limbs, uint64_t * cnt); void ISqrt_Babylonian_Py(uint64_t * limbs, uint64_t * cnt); @cython.boundscheck(False) @cython.wraparound(False) def ISqrt(method, n): mask64 = (1 << 64) - 1 def ToLimbs(): return np.copy(np.frombuffer(n.to_bytes((n.bit_length() + 63) // 64 * 8, 'little'), dtype = np.uint64)) words = (n.bit_length() + 63) // 64 t = n r = np.zeros((words,), dtype = np.uint64) for i in range(words): r[i] = np.uint64(t & mask64) t >>= 64 return r def FromLimbs(x): return int.from_bytes(x.tobytes(), 'little') n = 0 for i in range(x.shape[0]): n |= int(x[i]) << (i * 64) return n n = ToLimbs() cdef uint64_t[:] cn = n cdef uint64_t ccnt = len(n) cdef uint64_t cmethod = {'GMP': 0, 'AndersKaseorg': 1, 'Babylonian': 2, 'ChordTangent': 3}[method] with nogil: (ISqrt_GMP_Py if cmethod == 0 else ISqrt_AndersKaseorg_Py if cmethod == 1 else ISqrt_Babylonian_Py if cmethod == 2 else ISqrt_ChordTangent_Py)( <uint64_t *>&cn[0], <uint64_t *>&ccnt ) return FromLimbs(n[:ccnt]) """, } return cython_compile(srcs) def main(): import math, gmpy2, timeit, random mod = cython_import() fs = [ ('math.isqrt', math.isqrt), ('gmpy2.isqrt', gmpy2.isqrt), ('ISqrt_GMP', lambda n: mod.ISqrt('GMP', n)), ('ISqrt_AndersKaseorg', lambda n: mod.ISqrt('AndersKaseorg', n)), ('ISqrt_Babylonian', lambda n: mod.ISqrt('Babylonian', n)), ('ISqrt_ChordTangent', lambda n: mod.ISqrt('ChordTangent', n)), ] times = [0] * len(fs) ntests = 1 << 6 bits = 50000 for i in range(ntests): n = random.randrange(1 << (bits - 1), 1 << bits) ref = None for j, (fn, f) in enumerate(fs): timeit_cnt = 3 tim = timeit.timeit(lambda: f(n), number = timeit_cnt) / timeit_cnt times[j] += tim x = f(n) if j == 0: ref = x else: assert x == ref, (fn, ref, x) print('Bits', bits) print('\n'.join([f'{fs[i][0]:>19}: {round(times[i] / ntests * 1000, 3):>7} ms' for i in range(len(fs))])) if __name__ == '__main__': main() ``` and C++: [Try it online!](https://godbolt.org/z/bssTrszcj) ```cpp #include <cstdint> #include <cstring> #include <stdexcept> #include <tuple> #include <iostream> #include <string> #include <type_traits> #include <sstream> #include <gmpxx.h> #define ASSERT_MSG(cond, msg) { if (!(cond)) throw std::runtime_error("Assertion (" #cond ") failed at line " + std::to_string(__LINE__) + "! Msg '" + std::string(msg) + "'."); } #define ASSERT(cond) ASSERT_MSG(cond, "") #define LN { std::cout << "LN " << __LINE__ << std::endl; } using u32 = uint32_t; using u64 = uint64_t; template <typename T> size_t BitLen(T n) { if constexpr(std::is_same_v<std::decay_t<T>, mpz_class>) return mpz_sizeinbase(n.get_mpz_t(), 2); else { size_t cnt = 0; while (n >= (1ULL << 32)) { cnt += 32; n >>= 32; } while (n >= (1 << 8)) { cnt += 8; n >>= 8; } while (n) { ++cnt; n >>= 1; } return cnt; } } template <typename T> T ISqrt_Babylonian(T const & y) { // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method if (y <= 1) return y; T x = T(1) << (BitLen(y) / 2), a = 0, b = 0, limit = 3; while (true) { size_t constexpr loops = 3; for (size_t i = 0; i < loops; ++i) { if (i + 1 >= loops) a = x; b = y; b /= x; x += b; x >>= 1; } if (b < a) std::swap(a, b); if (b - a > limit) continue; ++b; for (size_t i = 0; a <= b; ++a, ++i) if (a * a > y) { if (i == 0) break; else return a - 1; } ASSERT(false); } } template <typename T> T ISqrt_AndersKaseorg(T const & n) { // https://stackoverflow.com/a/53983683/941531 if (n > 0) { T y = 0, x = T(1) << ((BitLen(n) + 1) >> 1); while (true) { y = (x + n / x) >> 1; if (y >= x) return x; x = y; } } else if (n == 0) return 0; else ASSERT_MSG(false, "square root not defined for negative numbers"); } template <typename T> T ISqrt_GMP(T const & y) { // https://gmplib.org/manual/Integer-Roots mpz_class r, n; bool constexpr is_mpz = std::is_same_v<std::decay_t<T>, mpz_class>; if constexpr(is_mpz) n = y; else { static_assert(sizeof(T) <= 8); n = u32(y >> 32); n <<= 32; n |= u32(y); } mpz_sqrt(r.get_mpz_t(), n.get_mpz_t()); if constexpr(is_mpz) return r; else return (u64(mpz_get_ui(mpz_class(r >> 32).get_mpz_t())) << 32) | u64(mpz_get_ui(mpz_class(r & u32(-1)).get_mpz_t())); } template <typename T> std::string IntToStr(T n) { if constexpr(std::is_same_v<std::decay_t<T>, mpz_class>) return n.get_str(); else { std::ostringstream ss; ss << n; return ss.str(); } } template <typename T> T KthRoot_ChordTangent(T const & n, size_t k = 2) { // https://i.stack.imgur.com/et9O0.jpg if (n <= 1) return n; auto KthPow = [&](auto const & x){ T y = x * x; for (size_t i = 2; i < k; ++i) y *= x; return y; }; auto KthPowDer = [&](auto const & x){ T y = x * u32(k); for (size_t i = 1; i + 1 < k; ++i) y *= x; return y; }; size_t root_bit_len = (BitLen(n) + k - 1) / k; T hi = T(1) << root_bit_len, x_begin = hi >> 1, x_end = hi, y_begin = KthPow(x_begin), y_end = KthPow(x_end), x_mid = 0, y_mid = 0, x_n = 0, y_n = 0, tangent_x = 0, chord_x = 0; for (size_t icycle = 0; icycle < (1 << 30); ++icycle) { //std::cout << "x_begin, x_end = " << IntToStr(x_begin) << ", " << IntToStr(x_end) << ", n " << IntToStr(n) << std::endl; if (x_end <= x_begin + 2) break; if constexpr(0) { // Do Binary Search step if needed x_mid = (x_begin + x_end) >> 1; y_mid = KthPow(x_mid); if (y_mid > n) { x_end = x_mid; y_end = y_mid; } else { x_begin = x_mid; y_begin = y_mid; } } // (y_end - y_begin) / (x_end - x_begin) = (n - y_begin) / (x_n - x_begin) -> x_n = x_begin + (n - y_begin) * (x_end - x_begin) / (y_end - y_begin); y_n = KthPow(x_n); tangent_x = x_n + (n - y_n) / KthPowDer(x_n) + 1; chord_x = x_n + (n - y_n) * (x_end - x_n) / (y_end - y_n); //ASSERT(chord_x <= tangent_x); x_begin = chord_x; x_end = tangent_x; y_begin = KthPow(x_begin); y_end = KthPow(x_end); //ASSERT(y_begin <= n); //ASSERT(y_end > n); } for (size_t i = 0; x_begin <= x_end; ++x_begin, ++i) if (x_begin * x_begin > n) { if (i == 0) break; else return x_begin - 1; } ASSERT(false); return 0; } mpz_class FromLimbs(uint64_t * limbs, uint64_t * cnt) { mpz_class r; mpz_import(r.get_mpz_t(), *cnt, -1, 8, -1, 0, limbs); return r; } void ToLimbs(mpz_class const & n, uint64_t * limbs, uint64_t * cnt) { uint64_t cnt_before = *cnt; size_t cnt_res = 0; mpz_export(limbs, &cnt_res, -1, 8, -1, 0, n.get_mpz_t()); ASSERT(cnt_res <= cnt_before); std::memset(limbs + cnt_res, 0, (cnt_before - cnt_res) * 8); *cnt = cnt_res; } void ISqrt_ChordTangent_Py(uint64_t * limbs, uint64_t * cnt) { ToLimbs(KthRoot_ChordTangent<mpz_class>(FromLimbs(limbs, cnt), 2), limbs, cnt); } void ISqrt_GMP_Py(uint64_t * limbs, uint64_t * cnt) { ToLimbs(ISqrt_GMP<mpz_class>(FromLimbs(limbs, cnt)), limbs, cnt); } void ISqrt_AndersKaseorg_Py(uint64_t * limbs, uint64_t * cnt) { ToLimbs(ISqrt_AndersKaseorg<mpz_class>(FromLimbs(limbs, cnt)), limbs, cnt); } void ISqrt_Babylonian_Py(uint64_t * limbs, uint64_t * cnt) { ToLimbs(ISqrt_Babylonian<mpz_class>(FromLimbs(limbs, cnt)), limbs, cnt); } // Testing #include <chrono> #include <random> #include <vector> #include <iomanip> inline double Time() { static auto const gtb = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - gtb) .count(); } template <typename T, typename F> std::vector<T> Test0(std::string const & test_name, size_t bits, size_t ntests, F && f) { std::mt19937_64 rng{123}; std::vector<T> nums; for (size_t i = 0; i < ntests; ++i) { T n = 0; for (size_t j = 0; j < bits; j += 32) { size_t const cbits = std::min<size_t>(32, bits - j); n <<= cbits; n ^= u32(rng()) >> (32 - cbits); } nums.push_back(n); } auto tim = Time(); for (auto & n: nums) n = f(n); tim = Time() - tim; std::cout << "Test " << std::setw(15) << ("'" + test_name + "'") << ", bits " << std::setw(6) << bits << ", time " << std::fixed << std::setprecision(6) << std::setw(9) << tim / ntests << " sec" << std::endl; return nums; } void Test() { auto f = [](auto ty, size_t bits, size_t ntests){ using T = std::decay_t<decltype(ty)>; auto tim = Time(); auto a = Test0<T>("GMP", bits, ntests, [](auto const & x){ return ISqrt_GMP<T>(x); }); auto b = Test0<T>("AndersKaseorg", bits, ntests, [](auto const & x){ return ISqrt_AndersKaseorg<T>(x); }); ASSERT(b == a); auto c = Test0<T>("Babylonian", bits, ntests, [](auto const & x){ return ISqrt_Babylonian<T>(x); }); ASSERT(c == a); auto d = Test0<T>("ChordTangent", bits, ntests, [](auto const & x){ return KthRoot_ChordTangent<T>(x); }); ASSERT(d == a); std::cout << "Bits " << bits << " nums " << ntests << " time " << std::fixed << std::setprecision(1) << (Time() - tim) << " sec" << std::endl; }; for (auto p: std::vector<std::pair<int, int>>{{15, 1 << 19}, {30, 1 << 19}}) f(u64(), p.first, p.second); for (auto p: std::vector<std::pair<int, int>>{{64, 1 << 15}, {8192, 1 << 10}, {50000, 1 << 5}}) f(mpz_class(), p.first, p.second); } int main() { try { Test(); return 0; } catch (std::exception const & ex) { std::cout << "Exception: " << ex.what() << std::endl; return -1; } } ```
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was not a perfect square') ``` But it's ugly and I don't really trust it for large integers. I could iterate through the squares and give up if I've exceeded the value, but I assume it would be kinda slow to do something like that. Also I guess I'd probably be reinventing the wheel, something like this must surely exist in python already...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
Sorry for the very late response; I just stumbled onto this page. In case anyone visits this page in the future, the python module gmpy2 is designed to work with very large inputs, and includes among other things an integer square root function. Example: ``` >>> import gmpy2 >>> gmpy2.isqrt((10**100+1)**2) mpz(10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001L) >>> gmpy2.isqrt((10**100+1)**2 - 1) mpz(10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L) ``` Granted, everything will have the "mpz" tag, but mpz's are compatible with int's: ``` >>> gmpy2.mpz(3)*4 mpz(12) >>> int(gmpy2.mpz(12)) 12 ``` See [my other answer](https://stackoverflow.com/a/31224469/2554867) for a discussion of this method's performance relative to some other answers to this question. Download: <https://code.google.com/p/gmpy/>
Floats cannot be precisely represented on computers. You can test for a desired proximity setting epsilon to a small value within the accuracy of python's floats. ``` def isqrt(n): epsilon = .00000000001 i = int(n**.5 + 0.5) if abs(i**2 - n) < epsilon: return i raise ValueError('input was not a perfect square') ```
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was not a perfect square') ``` But it's ugly and I don't really trust it for large integers. I could iterate through the squares and give up if I've exceeded the value, but I assume it would be kinda slow to do something like that. Also I guess I'd probably be reinventing the wheel, something like this must surely exist in python already...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
Here's a very straightforward implementation: ``` def i_sqrt(n): i = n.bit_length() >> 1 # i = floor( (1 + floor(log_2(n))) / 2 ) m = 1 << i # m = 2^i # # Fact: (2^(i + 1))^2 > n, so m has at least as many bits # as the floor of the square root of n. # # Proof: (2^(i+1))^2 = 2^(2i + 2) >= 2^(floor(log_2(n)) + 2) # >= 2^(ceil(log_2(n) + 1) >= 2^(log_2(n) + 1) > 2^(log_2(n)) = n. QED. # while m*m > n: m >>= 1 i -= 1 for k in xrange(i-1, -1, -1): x = m | (1 << k) if x*x <= n: m = x return m ``` This is just a binary search. Initialize the value `m` to be the largest power of 2 that does not exceed the square root, then check whether each smaller bit can be set while keeping the result no larger than the square root. (Check the bits one at a time, in descending order.) For reasonably large values of `n` (say, around `10**6000`, or around `20000` bits), this seems to be: * Faster than the Newton's method implementation [described by user448810](https://stackoverflow.com/a/15391420/2554867). * Much, much slower than the `gmpy2` built-in method in [my other answer](https://stackoverflow.com/a/17495624/2554867). * Comparable to, but somewhat slower than, the Longhand Square Root [described by nibot](https://stackoverflow.com/a/23279113/2554867). All of these approaches succeed on inputs of this size, but on my machine, this function takes around 1.5 seconds, while @Nibot's takes about 0.9 seconds, @user448810's takes around 19 seconds, and the gmpy2 built-in method takes less than a millisecond(!). Example: ``` >>> import random >>> import timeit >>> import gmpy2 >>> r = random.getrandbits >>> t = timeit.timeit >>> t('i_sqrt(r(20000))', 'from __main__ import *', number = 5)/5. # This function 1.5102493192883117 >>> t('exact_sqrt(r(20000))', 'from __main__ import *', number = 5)/5. # Nibot 0.8952787937686366 >>> t('isqrt(r(20000))', 'from __main__ import *', number = 5)/5. # user448810 19.326695976676184 >>> t('gmpy2.isqrt(r(20000))', 'from __main__ import *', number = 5)/5. # gmpy2 0.0003599147067689046 >>> all(i_sqrt(n)==isqrt(n)==exact_sqrt(n)[0]==int(gmpy2.isqrt(n)) for n in (r(1500) for i in xrange(1500))) True ``` This function can be generalized easily, though it's not quite as nice because I don't have quite as precise of an initial guess for `m`: ``` def i_root(num, root, report_exactness = True): i = num.bit_length() / root m = 1 << i while m ** root < num: m <<= 1 i += 1 while m ** root > num: m >>= 1 i -= 1 for k in xrange(i-1, -1, -1): x = m | (1 << k) if x ** root <= num: m = x if report_exactness: return m, m ** root == num return m ``` However, note that `gmpy2` also has an `i_root` method. In fact this method could be adapted and applied to any (nonnegative, increasing) function `f` to determine an "integer inverse of `f`". However, to choose an efficient initial value of `m` you'd still want to know something about `f`. **Edit: Thanks to @Greggo for pointing out that the `i_sqrt` function can be rewritten to avoid using any multiplications.** This yields an impressive performance boost! ``` def improved_i_sqrt(n): assert n >= 0 if n == 0: return 0 i = n.bit_length() >> 1 # i = floor( (1 + floor(log_2(n))) / 2 ) m = 1 << i # m = 2^i # # Fact: (2^(i + 1))^2 > n, so m has at least as many bits # as the floor of the square root of n. # # Proof: (2^(i+1))^2 = 2^(2i + 2) >= 2^(floor(log_2(n)) + 2) # >= 2^(ceil(log_2(n) + 1) >= 2^(log_2(n) + 1) > 2^(log_2(n)) = n. QED. # while (m << i) > n: # (m<<i) = m*(2^i) = m*m m >>= 1 i -= 1 d = n - (m << i) # d = n-m^2 for k in xrange(i-1, -1, -1): j = 1 << k new_diff = d - (((m<<1) | j) << k) # n-(m+2^k)^2 = n-m^2-2*m*2^k-2^(2k) if new_diff >= 0: d = new_diff m |= j return m ``` Note that by construction, the `k`th bit of `m << 1` is not set, so bitwise-or may be used to implement the addition of `(m<<1) + (1<<k)`. Ultimately I have `(2*m*(2**k) + 2**(2*k))` written as `(((m<<1) | (1<<k)) << k)`, so it's three shifts and one bitwise-or (followed by a subtraction to get `new_diff`). Maybe there is still a more efficient way to get this? Regardless, it's far better than multiplying `m*m`! Compare with above: ``` >>> t('improved_i_sqrt(r(20000))', 'from __main__ import *', number = 5)/5. 0.10908999762373242 >>> all(improved_i_sqrt(n) == i_sqrt(n) for n in xrange(10**6)) True ```
Floats cannot be precisely represented on computers. You can test for a desired proximity setting epsilon to a small value within the accuracy of python's floats. ``` def isqrt(n): epsilon = .00000000001 i = int(n**.5 + 0.5) if abs(i**2 - n) < epsilon: return i raise ValueError('input was not a perfect square') ```
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was not a perfect square') ``` But it's ugly and I don't really trust it for large integers. I could iterate through the squares and give up if I've exceeded the value, but I assume it would be kinda slow to do something like that. Also I guess I'd probably be reinventing the wheel, something like this must surely exist in python already...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
***Note:** There is now [`math.isqrt`](https://docs.python.org/3/library/math.html#math.isqrt) in stdlib, available since Python 3.8.* Newton's method works perfectly well on integers: ```python def isqrt(n): x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x ``` This returns the largest integer *x* for which *x* \* *x* does not exceed *n*. If you want to check if the result is exactly the square root, simply perform the multiplication to check if *n* is a perfect square. I discuss this algorithm, and three other algorithms for calculating square roots, at [my blog](http://programmingpraxis.com/2012/06/01/square-roots/).
**Long-hand square root algorithm** It turns out that there is an algorithm for computing square roots that you can compute by hand, something like long-division. Each iteration of the algorithm produces exactly one digit of the resulting square root while consuming two digits of the number whose square root you seek. While the "long hand" version of the algorithm is specified in decimal, it works in any base, with binary being simplest to implement and perhaps the fastest to execute (depending on the underlying bignum representation). Because this algorithm operates on numbers digit-by-digit, it produces exact results for arbitrarily large perfect squares, and for non-perfect-squares, can produce as many digits of precision (to the right of the decimal place) as desired. There are two nice writeups on the "Dr. Math" site that explain the algorithm: * [Square Roots in Binary](https://web.archive.org/web/20180224082738/http://mathforum.org/library/drmath/view/52656.html) * [Longhand Square Roots](https://web.archive.org/web/20180121185502/http://mathforum.org/library/drmath/view/52610.html) And here's an implementation in Python: ``` def exact_sqrt(x): """Calculate the square root of an arbitrarily large integer. The result of exact_sqrt(x) is a tuple (a, r) such that a**2 + r = x, where a is the largest integer such that a**2 <= x, and r is the "remainder". If x is a perfect square, then r will be zero. The algorithm used is the "long-hand square root" algorithm, as described at http://mathforum.org/library/drmath/view/52656.html Tobin Fricke 2014-04-23 Max Planck Institute for Gravitational Physics Hannover, Germany """ N = 0 # Problem so far a = 0 # Solution so far # We'll process the number two bits at a time, starting at the MSB L = x.bit_length() L += (L % 2) # Round up to the next even number for i in xrange(L, -1, -1): # Get the next group of two bits n = (x >> (2*i)) & 0b11 # Check whether we can reduce the remainder if ((N - a*a) << 2) + n >= (a<<2) + 1: b = 1 else: b = 0 a = (a << 1) | b # Concatenate the next bit of the solution N = (N << 2) | n # Concatenate the next bit of the problem return (a, N-a*a) ``` You could easily modify this function to conduct additional iterations to calculate the fractional part of the square root. I was most interested in computing roots of large perfect squares. I'm not sure how this compares to the "integer Newton's method" algorithm. I suspect that Newton's method is faster, since it can in principle generate multiple bits of the solution in one iteration, while the "long hand" algorithm generates exactly one bit of the solution per iteration. Source repo: <https://gist.github.com/tobin/11233492>
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was not a perfect square') ``` But it's ugly and I don't really trust it for large integers. I could iterate through the squares and give up if I've exceeded the value, but I assume it would be kinda slow to do something like that. Also I guess I'd probably be reinventing the wheel, something like this must surely exist in python already...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
One option would be to use the `decimal` module, and do it in sufficiently-precise floats: ``` import decimal def isqrt(n): nd = decimal.Decimal(n) with decimal.localcontext() as ctx: ctx.prec = n.bit_length() i = int(nd.sqrt()) if i**2 != n: raise ValueError('input was not a perfect square') return i ``` which I think should work: ``` >>> isqrt(1) 1 >>> isqrt(7**14) == 7**7 True >>> isqrt(11**1000) == 11**500 True >>> isqrt(11**1000+1) Traceback (most recent call last): File "<ipython-input-121-e80953fb4d8e>", line 1, in <module> isqrt(11**1000+1) File "<ipython-input-100-dd91f704e2bd>", line 10, in isqrt raise ValueError('input was not a perfect square') ValueError: input was not a perfect square ```
The script below extracts integer square roots. It uses no divisions, only bitshifts, so it is quite fast. It uses [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method) on the inverse square root, a technique made famous by *Quake III Arena* as mentioned in the Wikipedia article, [Fast inverse square root](https://en.wikipedia.org/wiki/Fast_inverse_square_root). The strategy of the algorithm to compute `s = sqrt(Y)` is as follows. 1. Reduce the argument Y to y in the range [1/4, 1), i.e., y = Y/B, with 1/4 <= y < 1, where B is an even power of 2, so `B = 2**(2*k)` for some integer k. We want to find X, where x = X/B, and x = 1 / sqrt(y). 2. Determine a first approximation to X using a quadratic [minimax polynomial](https://en.wikipedia.org/wiki/Minimax_approximation_algorithm). 3. Refine X using Newton's method. 4. Calculate `s = X*Y/(2**(3*k))`. We don't actually create fractions or perform any divisions. All the arithmetic is done with integers, and we use bit shifting to divide by various powers of B. Range reduction lets us find a good initial approximation to feed to Newton's method. Here's a version of the 2nd degree minimax polynomial approximation to the inverse square root in the interval [1/4, 1): [![Minimax poly for 1/sqrt(x)](https://latex.codecogs.com/svg.image?y=(463x%5E2-896x+698)/256)](https://latex.codecogs.com/svg.image?y=(463x%5E2-896x+698)/256) (Sorry, I've reversed the meaning of x & y here, to conform to the usual conventions). The maximum error of this approximation is around 0.0355 ~= 1/28. Here's a graph showing the error: [![Minimax poly error graph](https://i.stack.imgur.com/1P3uy.png)](https://i.stack.imgur.com/1P3uy.png) Using this poly, our initial x starts with at least 4 or 5 bits of precision. Each round of Newton's method doubles the precision, so it doesn't take many rounds to get thousands of bits, if we want them. --- ``` """ Integer square root Uses no divisions, only shifts "Quake" style algorithm, i.e., Newton's method for 1 / sqrt(y) Uses a quadratic minimax polynomial for the first approximation Written by PM 2Ring 2022.01.23 """ def int_sqrt(y): if y < 0: raise ValueError("int_sqrt arg must be >= 0, not %s" % y) if y < 2: return y # print("\n*", y, "*") # Range reduction. # Find k such that 1/4 <= y/b < 1, where b = 2 ** (k*2) j = y.bit_length() # Round k*2 up to the next even number k2 = j + (j & 1) # k and some useful multiples k = k2 >> 1 k3 = k2 + k k6 = k3 << 1 kd = k6 + 1 # b cubed b3 = 1 << k6 # Minimax approximation: x/b ~= 1 / sqrt(y/b) x = (((463 * y * y) >> k2) - (896 * y) + (698 << k2)) >> 8 # print(" ", x, h) # Newton's method for 1 / sqrt(y/b) epsilon = 1 << k for i in range(1, 99): dx = x * (b3 - y * x * x) >> kd x += dx # print(f" {i}: {x} {dx}") if abs(dx) <= epsilon: break # s == sqrt(y) s = x * y >> k3 # Adjust if too low ss = s + 1 return ss if ss * ss <= y else s def test(lo, hi, step=1): for y in range(lo, hi, step): s = int_sqrt(y) ss = s + 1 s2, ss2 = s * s, ss * ss assert s2 <= y < ss2, (y, s2, ss2) print("ok") test(0, 100000, 1) ``` This code is certainly *slower* than `math.isqrt` and `decimal.Decimal.sqrt`. Its purpose is simply to illustrate the algorithm. It would be interesting to see how fast it would be if it were implemented in C... --- Here's a [live version](https://sagecell.sagemath.org/?z=eJx9VE1v2zgQvftXPGjRruyojiUXRhJYQfewBXpo0Rbd7aVAQFm0xUgmtSTVSAjS394h9WFnUVSABMzozczjmxkGQYB30vID1zD_NUxzaKXsbAZ6_jHcQCrk4rswQkkTQcmqgynE3hoPCT41rOQBjO0qDlYdlBa2OEb-p1jyZYQP_MEq-afBkdtC5dgrjRiXVE7bsJufKjEQgVwzK3Y4CimOrEWtqk6qo2CVj7MFx15oY8HqWquWMJaI9XS_UmnLJbIOH98j-SzkAckqSZareJmsZ0EQzGY530NIezcUv-l57tFhi1VvuUczYTj-ZVXD_9Za6TAYg8D0AceGGGQctylWESlk8cIEeIHhNEO-5Cwft42W6Hqif6DWlC8MvslFEKGLECyC-fDrM5MHagLPm5072nJwvxUyRwnT7ApSgVnEl6-xTdFdZlQqjvBQcGpehhQJFguE5SLpU96Tq1tmwt5VXB5sEU6VVONyLhI0Nazy4kreWvDvpKJsjhnXHlomlOIeFwjv8RLxGF-CUbxRR47G8H1TkS6VFXXF-9koKYpCb28R9_a6d1yg7O2Ns9fYbkdA7hwbAsRDiQy7JuO5tzIXHjt0uRl1fD-MybNpuEFLovxIz6bsMutJt5QiDMPXmzUW1CN6545fmczxCuHV9aZ30Uk311e-VDL3iKvnjXOTH6GNUMxHKr8f85EAr42olJxO4p0OKmgsaeyo9yE18_p6fhqe3LFuiVlIErzytJ3V9tTzCdfiIiXwZI9s9wEexdMNHtsnPObt0zBqw6SyzIQ55aJZGsidKnvZNWfleEiDNH22uGag1nku6wH2V37vNoSyW6VQqYce68Bm6u6wE-QlHH0X7uMmGryi5TOz2RtizzXbWb-2lhsbViqljStEGq_cE9HFw-uUFGONVXdNnTPL07eMEpx2uxAu7dl2G7oZ6LZK8UU3fPISLCWuEz_H4hcxPvls6lt36lulHLOe0ln73KnPrpyT_7kc3pVQtEm8n-SIRlkmADOG0x1EEC_U1qEjhHSDDKF9-mFKVRkM4-kU9gc40eoxrkYy_7_T9Ll-AjbIm1w=&lang=python), running on the SageMathCell server. Set `hi` <= 0 to calculate and display the results for a single value set in `lo`. You can put expressions in the input boxes, eg set `hi` to 0 and `lo` to `2 * 10**100` to get `sqrt(2) * 10**50`.
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was not a perfect square') ``` But it's ugly and I don't really trust it for large integers. I could iterate through the squares and give up if I've exceeded the value, but I assume it would be kinda slow to do something like that. Also I guess I'd probably be reinventing the wheel, something like this must surely exist in python already...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
**Long-hand square root algorithm** It turns out that there is an algorithm for computing square roots that you can compute by hand, something like long-division. Each iteration of the algorithm produces exactly one digit of the resulting square root while consuming two digits of the number whose square root you seek. While the "long hand" version of the algorithm is specified in decimal, it works in any base, with binary being simplest to implement and perhaps the fastest to execute (depending on the underlying bignum representation). Because this algorithm operates on numbers digit-by-digit, it produces exact results for arbitrarily large perfect squares, and for non-perfect-squares, can produce as many digits of precision (to the right of the decimal place) as desired. There are two nice writeups on the "Dr. Math" site that explain the algorithm: * [Square Roots in Binary](https://web.archive.org/web/20180224082738/http://mathforum.org/library/drmath/view/52656.html) * [Longhand Square Roots](https://web.archive.org/web/20180121185502/http://mathforum.org/library/drmath/view/52610.html) And here's an implementation in Python: ``` def exact_sqrt(x): """Calculate the square root of an arbitrarily large integer. The result of exact_sqrt(x) is a tuple (a, r) such that a**2 + r = x, where a is the largest integer such that a**2 <= x, and r is the "remainder". If x is a perfect square, then r will be zero. The algorithm used is the "long-hand square root" algorithm, as described at http://mathforum.org/library/drmath/view/52656.html Tobin Fricke 2014-04-23 Max Planck Institute for Gravitational Physics Hannover, Germany """ N = 0 # Problem so far a = 0 # Solution so far # We'll process the number two bits at a time, starting at the MSB L = x.bit_length() L += (L % 2) # Round up to the next even number for i in xrange(L, -1, -1): # Get the next group of two bits n = (x >> (2*i)) & 0b11 # Check whether we can reduce the remainder if ((N - a*a) << 2) + n >= (a<<2) + 1: b = 1 else: b = 0 a = (a << 1) | b # Concatenate the next bit of the solution N = (N << 2) | n # Concatenate the next bit of the problem return (a, N-a*a) ``` You could easily modify this function to conduct additional iterations to calculate the fractional part of the square root. I was most interested in computing roots of large perfect squares. I'm not sure how this compares to the "integer Newton's method" algorithm. I suspect that Newton's method is faster, since it can in principle generate multiple bits of the solution in one iteration, while the "long hand" algorithm generates exactly one bit of the solution per iteration. Source repo: <https://gist.github.com/tobin/11233492>
Your function fails for large inputs: ``` In [26]: isqrt((10**100+1)**2) ValueError: input was not a perfect square ``` There is a [recipe on the ActiveState site](http://code.activestate.com/recipes/577821-integer-square-root-function/) which should hopefully be more reliable since it uses integer maths only. It is based on an earlier StackOverflow question: [Writing your own square root function](https://stackoverflow.com/questions/1623375/writing-your-own-square-root-function)
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was not a perfect square') ``` But it's ugly and I don't really trust it for large integers. I could iterate through the squares and give up if I've exceeded the value, but I assume it would be kinda slow to do something like that. Also I guess I'd probably be reinventing the wheel, something like this must surely exist in python already...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
**Update:** [Python 3.8 has a `math.isqrt` function](https://docs.python.org/3/library/math.html#math.isqrt) in the standard library! I benchmarked every (correct) function here on both small (0…222) and large (250001) inputs. The clear winners in both cases are [`gmpy2.isqrt` suggested by mathmandan](https://stackoverflow.com/a/17495624/115030) in first place, followed by Python 3.8’s [`math.isqrt`](https://docs.python.org/3.8/library/math.html#math.isqrt) in second, followed by the [ActiveState recipe linked by NPE](https://stackoverflow.com/a/15391114/115030) in third. The ActiveState recipe has a bunch of divisions that can be replaced by shifts, which makes it a bit faster (but still behind the native functions): ```python def isqrt(n): if n > 0: x = 1 << (n.bit_length() + 1 >> 1) while True: y = (x + n // x) >> 1 if y >= x: return x x = y elif n == 0: return 0 else: raise ValueError("square root not defined for negative numbers") ``` Benchmark results: * [`gmpy2.isqrt()` (mathmandan)](https://stackoverflow.com/a/17495624/115030): 0.08 µs small, 0.07 ms large * `int(gmpy2.isqrt())`\*: 0.3 µs small, 0.07 ms large * Python 3.8 [`math.isqrt`](https://docs.python.org/3.8/library/math.html#math.isqrt): 0.13 µs small, 0.9 ms large * **ActiveState (optimized as above)**: 0.6 µs small, 17.0 ms large * [ActiveState (NPE)](https://stackoverflow.com/a/15391114/115030): 1.0 µs small, 17.3 ms large * [castlebravo long-hand](https://stackoverflow.com/a/39708338/115030): 4 µs small, 80 ms large * [mathmandan improved](https://stackoverflow.com/a/31224469/115030): 2.7 µs small, 120 ms large * [martineau](https://stackoverflow.com/a/15391068/115030) (with [this correction](https://stackoverflow.com/questions/15390807/integer-square-root-in-python/23279113#comment94803887_15391068)): 2.3 µs small, 140 ms large * [nibot](https://stackoverflow.com/a/23279113/115030): 8 µs small, 1000 ms large * [mathmandan](https://stackoverflow.com/a/31224469/115030): 1.8 µs small, 2200 ms large * [castlebravo Newton’s method](https://stackoverflow.com/a/39708338/115030): 1.5 µs small, 19000 ms large * [user448810](https://stackoverflow.com/a/15391420/115030): 1.4 µs small, 20000 ms large (\* Since `gmpy2.isqrt` returns a `gmpy2.mpz` object, which behaves mostly but not exactly like an `int`, you may need to convert it back to an `int` for some uses.)
Your function fails for large inputs: ``` In [26]: isqrt((10**100+1)**2) ValueError: input was not a perfect square ``` There is a [recipe on the ActiveState site](http://code.activestate.com/recipes/577821-integer-square-root-function/) which should hopefully be more reliable since it uses integer maths only. It is based on an earlier StackOverflow question: [Writing your own square root function](https://stackoverflow.com/questions/1623375/writing-your-own-square-root-function)
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was not a perfect square') ``` But it's ugly and I don't really trust it for large integers. I could iterate through the squares and give up if I've exceeded the value, but I assume it would be kinda slow to do something like that. Also I guess I'd probably be reinventing the wheel, something like this must surely exist in python already...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
***Note:** There is now [`math.isqrt`](https://docs.python.org/3/library/math.html#math.isqrt) in stdlib, available since Python 3.8.* Newton's method works perfectly well on integers: ```python def isqrt(n): x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x ``` This returns the largest integer *x* for which *x* \* *x* does not exceed *n*. If you want to check if the result is exactly the square root, simply perform the multiplication to check if *n* is a perfect square. I discuss this algorithm, and three other algorithms for calculating square roots, at [my blog](http://programmingpraxis.com/2012/06/01/square-roots/).
Seems like you could check like this: ``` if int(math.sqrt(n))**2 == n: print n, 'is a perfect square' ``` Update: As you pointed out the above fails for large values of `n`. For those the following looks promising, which is an adaptation of the example C code, by Martin Guy @ UKC, June 1985, for the relatively simple looking binary numeral digit-by-digit calculation method mentioned in the Wikipedia article [Methods of computing square roots](http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_.28base_2.29): ``` from math import ceil, log def isqrt(n): res = 0 bit = 4**int(ceil(log(n, 4))) if n else 0 # smallest power of 4 >= the argument while bit: if n >= res + bit: n -= res + bit res = (res >> 1) + bit else: res >>= 1 bit >>= 2 return res if __name__ == '__main__': from math import sqrt # for comparison purposes for i in range(17)+[2**53, (10**100+1)**2]: is_perfect_sq = isqrt(i)**2 == i print '{:21,d}: math.sqrt={:12,.7G}, isqrt={:10,d} {}'.format( i, sqrt(i), isqrt(i), '(perfect square)' if is_perfect_sq else '') ``` Output: ```none 0: math.sqrt= 0, isqrt= 0 (perfect square) 1: math.sqrt= 1, isqrt= 1 (perfect square) 2: math.sqrt= 1.414214, isqrt= 1 3: math.sqrt= 1.732051, isqrt= 1 4: math.sqrt= 2, isqrt= 2 (perfect square) 5: math.sqrt= 2.236068, isqrt= 2 6: math.sqrt= 2.44949, isqrt= 2 7: math.sqrt= 2.645751, isqrt= 2 8: math.sqrt= 2.828427, isqrt= 2 9: math.sqrt= 3, isqrt= 3 (perfect square) 10: math.sqrt= 3.162278, isqrt= 3 11: math.sqrt= 3.316625, isqrt= 3 12: math.sqrt= 3.464102, isqrt= 3 13: math.sqrt= 3.605551, isqrt= 3 14: math.sqrt= 3.741657, isqrt= 3 15: math.sqrt= 3.872983, isqrt= 3 16: math.sqrt= 4, isqrt= 4 (perfect square) 9,007,199,254,740,992: math.sqrt=9.490627E+07, isqrt=94,906,265 100,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,020,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,001: math.sqrt= 1E+100, isqrt=10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,001 (perfect square) ```
72,394,305
I used this command: `python manage.py runserver 0:8080` After I logined the system I can reach rest API pages, but can't reach other pages. Although I send a request, the command output does not log. ``` Quit the server with CONTROL-C. ```
2022/05/26
[ "https://Stackoverflow.com/questions/72394305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15506634/" ]
You *can* actually convert from a string holding a base-16 number to a numeric value in plain Sqlite, but it's kind of ugly, using a [recursive CTE](https://sqlite.org/lang_with.html#recursive_common_table_expressions): ```sql WITH RECURSIVE hexnumbers(hexstr) AS (VALUES ('0x123'), ('0x4'), ('0x7f')), parse_hex(num, hexstr, digit, remaining) AS (SELECT 0, upper(hexstr), 3, length(hexstr) - 2 FROM hexnumbers UNION ALL SELECT (num * 16) + CASE substr(hexstr, digit, 1) WHEN '0' THEN 0 WHEN '1' THEN 1 WHEN '2' THEN 2 WHEN '3' THEN 3 WHEN '4' THEN 4 WHEN '5' THEN 5 WHEN '6' THEN 6 WHEN '7' THEN 7 WHEN '8' THEN 8 WHEN '9' THEN 9 WHEN 'A' THEN 0xA WHEN 'B' THEN 0xB WHEN 'C' THEN 0xC WHEN 'D' THEN 0xD WHEN 'E' THEN 0xE WHEN 'F' THEN 0xF END, hexstr, digit + 1, remaining - 1 FROM parse_hex WHERE remaining > 0) SELECT hexstr, num FROM parse_hex WHERE remaining = 0; ``` gives ```none hexstr num ------ --- 0X4 4 0X7F 127 0X123 291 ``` --- If you want to go the C function route, your implementation function should look something like: ```c void hex_to_dec(sqlite3_context *context, int argc, sqlite3_value **argv) { int vtype = sqlite3_value_numeric_type(argv[0]); if (vtype == SQLITE_TEXT) const char *str = sqlite3_value_text(argv[0]); if (str && *str) { sqlite3_result_int64(context, strtol(str, NULL, 16)); } } else if (vtype == SQLITE_INTEGER) { sqlite3_result_value(context, argv[0]); } } ``` except maybe with more error checking. The one in @choroba's answer creates a blob, not an integer, which isn't want you want.
SQLite doesn't convert from hex to dec, you need to write such a function yourself. An example can be found in the [SQLite Forum](https://sqlite.org/forum/info/79dc039e21c6a1ea): ``` /* ** Function UNHEX(arg) -> blob ** ** Decodes the arg which must be an even number of hexidecimal characters into a blob and returns the blob ** */ #ifdef __cplusplus extern "C" { #endif #ifndef SQLITE_PRIVATE #define SQLITE_PRIVATE static #endif #include <stdlib.h> #include <string.h> #ifdef SQLITE_CORE #include "sqlite3.h" #else #ifdef _HAVE_SQLITE_CONFIG_H #include "config.h" #endif #include "sqlite3ext.h" SQLITE_EXTENSION_INIT1 #endif #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0600 #endif static void _unhexFunc(sqlite3_context *context, int argc, sqlite3_value **argv) { long olength = sqlite3_value_bytes(argv[0]); long length; unsigned char* data = (unsigned char*)sqlite3_value_text(argv[0]); unsigned char* blob; unsigned char* stuff; unsigned char buffer[4] = {0}; if ((olength % 2 != 0) || (olength < 2)) { return; } blob = malloc(length / 2); stuff = blob; length = olength; while (length > 0) { memcpy(buffer, data, 2); *stuff = (unsigned char)strtol(buffer, NULL, 16); stuff++; data += 2; length -= 2; } sqlite3_result_blob(context, blob, olength/2, SQLITE_TRANSIENT); free(blob); } #ifdef _WIN32 #ifndef SQLITE_CORE __declspec(dllexport) #endif #endif int sqlite3_sqlunhex_init(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi) { SQLITE_EXTENSION_INIT2(pApi); return sqlite3_create_function(db, "UNHEX", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS, 0, _unhexFunc, 0, 0); } #ifdef __cplusplus } #endif ``` You can then call it on the value if it starts with `0x`: ``` SELECT CASE WHEN col1 LIKE '0x%' THEN UNHEX(col1) ELSE col1 END FROM foo; ``` Much better way is to fix this in the application that stores the values.
32,215,510
I am quite new to use Frame of Tkinter in Python. I discovered Frame from the following [post](https://stackoverflow.com/questions/32198849/set-the-correct-tkinter-widgets-position-in-python) When i run the GUI the Check box are not in the same line. [![enter image description here](https://i.stack.imgur.com/jB3jB.png)](https://i.stack.imgur.com/jB3jB.png) For this reason i have the following two questions: 1) is it possible to use "grid" in the frame in order to place the widget where i wish? 2) Is it possible to place for example "Camera white balance" and "average white balance" in the same row? in grid is for example row=0, column=0 and row=0, column=1 3) if i add a line below the button "Input raw image file" using the code: ``` self.sep = Frame(self, height=2, width=450, bd=1, relief=SUNKEN) self.sep.grid(row=1, column=0, columnspan=4, padx=5, pady=5) ``` The Run works forever without showing the GUI. My code is: ``` from __future__ import division from Tkinter import * import tkMessageBox import tkFileDialog class MainWindow(Frame): def __init__(self): Frame.__init__(self) self.master.title("FOO frame") self.master.minsize(350, 150) self.grid(sticky=W+N+S+E) top_frame = Frame(self) middle_frame = Frame(self) bottom_frame = Frame(self) top_frame.pack(side="top", fill="x") middle_frame.pack(side="top", fill="x") bottom_frame.pack(side="top", fill="x") self.open = Button(top_frame,text="Input raw image file", command=self.open, activeforeground="red") self.open.pack(side="left") self.CheckVar_camera_white_balance = IntVar() self.CheckVar_camera_white_balance = Checkbutton(middle_frame, text="Camera white balance", variable=self.CheckVar_camera_white_balance, onvalue=1, offvalue=0) self.CheckVar_camera_white_balance.pack(side="top", fill="x") self.CheckVar_average_whole_image_white_balance = IntVar() self.CheckVar_average_whole_image_white_balance = Checkbutton(middle_frame, text="Average white balance", variable=self.CheckVar_average_whole_image_white_balance, onvalue=1, offvalue=0) self.CheckVar_average_whole_image_white_balance.pack() self.CheckVar_correct_chromatic_aberration = IntVar() self.CheckVar_correct_chromatic_aberration = Checkbutton(middle_frame, text="Correct chromatic aberration", variable=self.CheckVar_correct_chromatic_aberration, onvalue=1, offvalue=0) self.CheckVar_correct_chromatic_aberration.pack() self.CheckVar_fix_dead_pixels = IntVar() self.CheckVar_fix_dead_pixels = Checkbutton(middle_frame, text="Fix dead pixels", variable=self.CheckVar_fix_dead_pixels, onvalue=1, offvalue=0) self.CheckVar_fix_dead_pixels.pack() # functions def open(self): self.filename_open = tkFileDialog.askopenfilenames(defaultextension='.*') if __name__ == "__main__": d = MainWindow() d.mainloop() ```
2015/08/25
[ "https://Stackoverflow.com/questions/32215510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493192/" ]
Answers to your Questions Bryan Oakley gave you. Here is some code so you can imagine what he is talking about: ``` from __future__ import division from Tkinter import * import tkFileDialog import tkMessageBox from ttk import Separator class MainWindow(Frame): def __init__(self): Frame.__init__(self) self.master.title("FOO frame") self.master.minsize(350, 150) self.grid(sticky=W+N+S+E) top_frame = Frame(self) middle_frame = Frame(self) bottom_frame = Frame(self) top_frame.pack(side="top", fill="x") middle_frame.pack(side="top", fill="x") bottom_frame.pack(side="top", fill="x") self.open = Button(top_frame,text="Input raw image file", command=self.open, activeforeground="red") self.open.pack(side="left") self.sep = Separator(middle_frame, orient=HORIZONTAL) self.sep.grid(row=0, column=0, columnspan=2, sticky="WE", pady=5) self.CheckVar_camera_white_balance = IntVar() self.CheckVar_camera_white_balance = Checkbutton(middle_frame, text="Camera white balance", variable=self.CheckVar_camera_white_balance, onvalue=1, offvalue=0) self.CheckVar_camera_white_balance.grid(row=1, column=0, sticky="W") self.CheckVar_average_whole_image_white_balance = IntVar() self.CheckVar_average_whole_image_white_balance = Checkbutton(middle_frame, text="Average white balance", variable=self.CheckVar_average_whole_image_white_balance, onvalue=1, offvalue=0) self.CheckVar_average_whole_image_white_balance.grid(row=1, column=1, sticky="W") self.CheckVar_correct_chromatic_aberration = IntVar() self.CheckVar_correct_chromatic_aberration = Checkbutton(middle_frame, text="Correct chromatic aberration", variable=self.CheckVar_correct_chromatic_aberration, onvalue=1, offvalue=0) self.CheckVar_correct_chromatic_aberration.grid(row=2, column=0, columnspan=2, sticky="W") self.CheckVar_fix_dead_pixels = IntVar() self.CheckVar_fix_dead_pixels = Checkbutton(middle_frame, text="Fix dead pixels", variable=self.CheckVar_fix_dead_pixels, onvalue=1, offvalue=0) self.CheckVar_fix_dead_pixels.grid(row=3, column=0, columnspan=2, sticky="W") # functions def open(self): self.filename_open = tkFileDialog.askopenfilenames(defaultextension='.*') if __name__ == "__main__": d = MainWindow() d.mainloop() ``` If you separator you can use the `Seperator`class, i was adding the seperator to the `middle_frame` so you have more control of this widget. Now you can use `column` to set "Camera white balance" and "average white balance" side by side. The columnspan attribute defines the number of columns a widget should span. So if you have more than 2 columns update that attribute. Finally if you use `sticky` you can define on which side the widget should stay.
1. Yes, it is possible to use `grid` In any frame you wish 2. Yes, it is possible to place "Camera white balance" and "average white balance" in the same row. 3. The reason the code runs forever without displaying anything is because you are using both grid (for the separator) and pack (for the frames). They both have the same parent so you can only use one or the other. To get things to align you should read the documentation to learn about all of the options available when calling `grid` and `pack`. These options allow you to center itemsm or align them alon an edge, control padding, and so on.
35,114,144
My Celery task raises a custom exception `NonTransientProcessingError`, which is then caught by `AsyncResult.get()`. Tasks.py: ``` class NonTransientProcessingError(Exception): pass @shared_task() def throw_exception(): raise NonTransientProcessingError('Error raised by POC model for test purposes') ``` In the Python console: ``` from my_app.tasks import * r = throw_exception.apply_async() try: r.get() except NonTransientProcessingError as e: print('caught NonTrans in type specific except clause') ``` But my custom exception is **`my_app.tasks.`**`NonTransientProcessingError`, whereas the exception raised by `AsyncResult.get()` is **`celery.backends.base.`**`NonTransientProcessingError`, so my `except` clause fails. ``` Traceback (most recent call last): File "<input>", line 4, in <module> File "/...venv/lib/python3.5/site-packages/celery/result.py", line 175, in get raise meta['result'] celery.backends.base.NonTransientProcessingError: Error raised by POC model for test purposes ``` If I catch the exception within the task, it works fine. It is only when the exception is raised to the `.get()` call that it is renamed. How can I raise a custom exception and catch it correctly? I have confirmed that the same happens when I define a `Task` class and raise the custom exception in its `on_failure` method. The following does work: ``` try: r.get() except Exception as e: if type(e).__name__ == 'NonTransientProcessingError': print('specific exception identified') else: print('caught generic but not identified') ``` Outputs: ``` specific exception identified ``` But this can't be the best way of doing this? Ideally I'd like to catch exception superclasses for categories of behaviour. I'm using Django 1.8.6, Python 3.5 and Celery 3.1.18, with a Redis 3.1.18, Python redis lib 2.10.3 backend.
2016/01/31
[ "https://Stackoverflow.com/questions/35114144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1308967/" ]
``` import celery from celery import shared_task class NonTransientProcessingError(Exception): pass class CeleryTask(celery.Task): def on_failure(self, exc, task_id, args, kwargs, einfo): if isinstance(exc, NonTransientProcessingError): """ deal with NonTransientProcessingError """ pass def run(self, *args, **kwargs): pass @shared_task(base=CeleryTask) def add(x, y): raise NonTransientProcessingError ``` Use a base Task with on\_failure callback to catch custom exception.
It might be a bit late, but I have a solution to solve this issue. Not sure if it is the best one, but it solved my problem at least. I had the same issue. I wanted to catch the exception produced in the celery task, but the result was of the class `celery.backends.base.CustomException`. The solution is in the following form: ```py import celery, time from celery.result import AsyncResult from celery.states import FAILURE def reraise_celery_exception(info): exec("raise {class_name}('{message}')".format(class_name=info.__class__.__name__, message=info.__str__())) class CustomException(Exception): pass @celery.task(name="test") def test(): time.sleep(10) raise CustomException("Exception is raised!") def run_test(): task = test.delay() return task.id def get_result(id): task = AsyncResult(id) if task.state == FAILURE: reraise_celery_exception(task.info) ``` In this case you prevent your program from raising `celery.backends.base.CustomException`, and force it to raise the right exception.
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_iter=3, test_size=0.1, random_state=0) knn = KNeighborsClassifier() KNeighborsClassifier(algorithm='auto', leaf_size=1, metric='minkowski', n_neighbors=2, p=2, weights='uniform') knn_score = cross_validation.cross_val_score(knn,x_data_arr, target_arr, cv=cv) print "Accuracy =", knn_score.mean() ``` Thanks!!
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
you can use: ``` public String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model; } } private String capitalize(String s) { if (s == null || s.length() == 0) { return ""; } char first = s.charAt(0); if (Character.isUpperCase(first)) { return s; } else { return Character.toUpperCase(first) + s.substring(1); } } ``` see [this](http://developer.android.com/reference/android/os/Build.html#MODEL) for Build.MODEL. more info in *[Get Android Phone Model Programmatically](https://stackoverflow.com/questions/1995439/get-android-phone-model-programmatically)*.
In order to get android device name you have to add only a single line of code: ``` android.os.Build.MODEL; ``` Found here:[getting-android-device-name](http://developer.android.com/reference/android/os/Build.html)
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_iter=3, test_size=0.1, random_state=0) knn = KNeighborsClassifier() KNeighborsClassifier(algorithm='auto', leaf_size=1, metric='minkowski', n_neighbors=2, p=2, weights='uniform') knn_score = cross_validation.cross_val_score(knn,x_data_arr, target_arr, cv=cv) print "Accuracy =", knn_score.mean() ``` Thanks!!
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
you can use: ``` public String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model; } } private String capitalize(String s) { if (s == null || s.length() == 0) { return ""; } char first = s.charAt(0); if (Character.isUpperCase(first)) { return s; } else { return Character.toUpperCase(first) + s.substring(1); } } ``` see [this](http://developer.android.com/reference/android/os/Build.html#MODEL) for Build.MODEL. more info in *[Get Android Phone Model Programmatically](https://stackoverflow.com/questions/1995439/get-android-phone-model-programmatically)*.
you can also get it via bluetoothAdapter see [this](https://stackoverflow.com/a/23729614/4260932) ``` public String getPhoneName() { BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter(); String deviceName = myDevice.getName(); return deviceName; } ```
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_iter=3, test_size=0.1, random_state=0) knn = KNeighborsClassifier() KNeighborsClassifier(algorithm='auto', leaf_size=1, metric='minkowski', n_neighbors=2, p=2, weights='uniform') knn_score = cross_validation.cross_val_score(knn,x_data_arr, target_arr, cv=cv) print "Accuracy =", knn_score.mean() ``` Thanks!!
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
you can use: ``` public String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model; } } private String capitalize(String s) { if (s == null || s.length() == 0) { return ""; } char first = s.charAt(0); if (Character.isUpperCase(first)) { return s; } else { return Character.toUpperCase(first) + s.substring(1); } } ``` see [this](http://developer.android.com/reference/android/os/Build.html#MODEL) for Build.MODEL. more info in *[Get Android Phone Model Programmatically](https://stackoverflow.com/questions/1995439/get-android-phone-model-programmatically)*.
Download csv from here: <https://support.google.com/googleplay/answer/1727131?hl=en> > > See if your device works with Google Play by checking the list below. > When you download the PDF file, devices are ordered alphabetically > (A-Z) by manufacturer name. > > > Then import this file into your database. Query `RetailBranding` and `Marketing Name` by `Model = Build.Model`. To have a better performance, put these data in your database server. Get the `RetailBranding` and `Marketing Name` when the app is first launched and save it to the local database.
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_iter=3, test_size=0.1, random_state=0) knn = KNeighborsClassifier() KNeighborsClassifier(algorithm='auto', leaf_size=1, metric='minkowski', n_neighbors=2, p=2, weights='uniform') knn_score = cross_validation.cross_val_score(knn,x_data_arr, target_arr, cv=cv) print "Accuracy =", knn_score.mean() ``` Thanks!!
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
In order to get android device name you have to add only a single line of code: ``` android.os.Build.MODEL; ``` Found here:[getting-android-device-name](http://developer.android.com/reference/android/os/Build.html)
you can also get it via bluetoothAdapter see [this](https://stackoverflow.com/a/23729614/4260932) ``` public String getPhoneName() { BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter(); String deviceName = myDevice.getName(); return deviceName; } ```
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_iter=3, test_size=0.1, random_state=0) knn = KNeighborsClassifier() KNeighborsClassifier(algorithm='auto', leaf_size=1, metric='minkowski', n_neighbors=2, p=2, weights='uniform') knn_score = cross_validation.cross_val_score(knn,x_data_arr, target_arr, cv=cv) print "Accuracy =", knn_score.mean() ``` Thanks!!
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
In order to get android device name you have to add only a single line of code: ``` android.os.Build.MODEL; ``` Found here:[getting-android-device-name](http://developer.android.com/reference/android/os/Build.html)
Download csv from here: <https://support.google.com/googleplay/answer/1727131?hl=en> > > See if your device works with Google Play by checking the list below. > When you download the PDF file, devices are ordered alphabetically > (A-Z) by manufacturer name. > > > Then import this file into your database. Query `RetailBranding` and `Marketing Name` by `Model = Build.Model`. To have a better performance, put these data in your database server. Get the `RetailBranding` and `Marketing Name` when the app is first launched and save it to the local database.
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_iter=3, test_size=0.1, random_state=0) knn = KNeighborsClassifier() KNeighborsClassifier(algorithm='auto', leaf_size=1, metric='minkowski', n_neighbors=2, p=2, weights='uniform') knn_score = cross_validation.cross_val_score(knn,x_data_arr, target_arr, cv=cv) print "Accuracy =", knn_score.mean() ``` Thanks!!
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
Download csv from here: <https://support.google.com/googleplay/answer/1727131?hl=en> > > See if your device works with Google Play by checking the list below. > When you download the PDF file, devices are ordered alphabetically > (A-Z) by manufacturer name. > > > Then import this file into your database. Query `RetailBranding` and `Marketing Name` by `Model = Build.Model`. To have a better performance, put these data in your database server. Get the `RetailBranding` and `Marketing Name` when the app is first launched and save it to the local database.
you can also get it via bluetoothAdapter see [this](https://stackoverflow.com/a/23729614/4260932) ``` public String getPhoneName() { BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter(); String deviceName = myDevice.getName(); return deviceName; } ```
34,074,840
I am doing a small python script to perform a wget call, however I am encountering an issue when I am replacing the string that contains the url/ip address and that it will be given to my "wget" string ``` import os import sys usr = sys.argv[1] pswd = sys.argv[2] ipAddr = sys.argv[3] wget = "wget http://{IPaddress}" wget.format(IPaddress=ipAddr) print "The command wget is %s" %wget os.system(wget) ``` If I run that script I get the snippet below, wher I know that wget fails, because the variable ipAddr has not replaced IPaddress pattern, so I guess that the issue has to do with the slashes in the url. My question is why that pattern is not replaced? ``` python test.py 1 2 www.website.org The command wget is wget http://{IPaddress} --2015-12-03 20:26:11-- http://%7Bipaddress%7D/ Resolving {ipaddress} ({ipaddress})... failed: Name or service not known. ```
2015/12/03
[ "https://Stackoverflow.com/questions/34074840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1757475/" ]
You aren't assigning the result of the `format` call to anything - you're just throwing it away. Try this instead: ``` wget = "wget http://{IPaddress}" wget = wget.format(IPaddress=ipAddr) print "The command wget is %s" %wget os.system(wget) ``` Alternatively, this seems a bit cleaner: ``` wget = "wget http://{IPaddress}".format(IPaddress=ipAddr) print "The command wget is %s" %wget os.system(wget) ```
You need to actually format your `wget` string like this. ``` import os import sys usr = sys.argv[1] pswd = sys.argv[2] ipAddr = sys.argv[3] wget = "wget http://{IPaddress}".format(IPaddress=ipAddr) print "The command wget is %s" % wget os.system(wget) ``` `.format()` does not modify the string in place, it returns a copy of the modified string, so in your original script, the value of `wget.format(IPaddress=ipAddr)` is never actually assigned to any variable and the content of the `wget` variable remains unchanged
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows system. For reference, these are in answer to the linked SO questions below: * [in #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): an unnamed file in `/usr/lib/python2.6/.../css/` * [in comment to #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): change monospace font in browser - worked but font is italic * [in #2](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook): `custom.css` in profile subdirectory `/static/custom/custom.css` Related questions: 1. [Change ipython notebook font type](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1) 2. [Change font & background color in ipython notebook](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook) 3. [Changing (back to default) font in ipython notebook](https://stackoverflow.com/questions/20870335/changing-back-to-default-font-in-ipython-notebook) (unanswered) - **Edit:** Changing the monospace font in my browser worked, as suggested in an answer comment of #1. However the font is italic, which is not what is intended.
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In JupyterNotebook cell, Simply you can use: ``` %%html <style type='text/css'> .CodeMirror{ font-size: 17px; </style> ```
I would also suggest that you explore the options offered by the [**jupyter themer**](https://github.com/transcranial/jupyter-themer). For more modest interface changes you may be satisfied with running the syntax: ``` jupyter-themer [-c COLOR, --color COLOR] [-l LAYOUT, --layout LAYOUT] [-t TYPOGRAPHY, --typography TYPOGRAPHY] ``` where the options offered by *themer* would provide you with a less onerous way of making some changes in to the look of Jupyter Notebook. Naturally, you may still to prefer edit the **`.css`** files if the changes you want to apply are elaborate.
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows system. For reference, these are in answer to the linked SO questions below: * [in #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): an unnamed file in `/usr/lib/python2.6/.../css/` * [in comment to #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): change monospace font in browser - worked but font is italic * [in #2](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook): `custom.css` in profile subdirectory `/static/custom/custom.css` Related questions: 1. [Change ipython notebook font type](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1) 2. [Change font & background color in ipython notebook](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook) 3. [Changing (back to default) font in ipython notebook](https://stackoverflow.com/questions/20870335/changing-back-to-default-font-in-ipython-notebook) (unanswered) - **Edit:** Changing the monospace font in my browser worked, as suggested in an answer comment of #1. However the font is italic, which is not what is intended.
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In JupyterNotebook cell, Simply you can use: ``` %%html <style type='text/css'> .CodeMirror{ font-size: 17px; </style> ```
In addition to the suggestion by Konrad here, I'd like to suggest [jupyter themes](https://github.com/dunovank/jupyter-themes), which seems to have more options, such as line-height, font size, cell width etc. Command line usage: ``` jt [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT] [-nfs NBFONTSIZE] [-tf TCFONT] [-tfs TCFONTSIZE] [-dfs DFFONTSIZE] [-m MARGINS] [-cursw CURSORWIDTH] [-cursc CURSORCOLOR] [-vim] [-cellw CELLWIDTH] [-lineh LINEHEIGHT] [-altp] [-P] [-T] [-N] [-r] [-dfonts] ```
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows system. For reference, these are in answer to the linked SO questions below: * [in #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): an unnamed file in `/usr/lib/python2.6/.../css/` * [in comment to #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): change monospace font in browser - worked but font is italic * [in #2](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook): `custom.css` in profile subdirectory `/static/custom/custom.css` Related questions: 1. [Change ipython notebook font type](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1) 2. [Change font & background color in ipython notebook](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook) 3. [Changing (back to default) font in ipython notebook](https://stackoverflow.com/questions/20870335/changing-back-to-default-font-in-ipython-notebook) (unanswered) - **Edit:** Changing the monospace font in my browser worked, as suggested in an answer comment of #1. However the font is italic, which is not what is intended.
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In JupyterNotebook cell, Simply you can use: ``` %%html <style type='text/css'> .CodeMirror{ font-size: 17px; </style> ```
For chrome users, This is very simple. Just install the desired font in your OS. Then open the said browser, Go to Settings -> Appearance -> Customize font. Go to fixed width font and from drop down list select the desired font. Note: This might also change the fonts at some other places depending on the web pages that you visit.
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows system. For reference, these are in answer to the linked SO questions below: * [in #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): an unnamed file in `/usr/lib/python2.6/.../css/` * [in comment to #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): change monospace font in browser - worked but font is italic * [in #2](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook): `custom.css` in profile subdirectory `/static/custom/custom.css` Related questions: 1. [Change ipython notebook font type](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1) 2. [Change font & background color in ipython notebook](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook) 3. [Changing (back to default) font in ipython notebook](https://stackoverflow.com/questions/20870335/changing-back-to-default-font-in-ipython-notebook) (unanswered) - **Edit:** Changing the monospace font in my browser worked, as suggested in an answer comment of #1. However the font is italic, which is not what is intended.
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In addition to the suggestion by Konrad here, I'd like to suggest [jupyter themes](https://github.com/dunovank/jupyter-themes), which seems to have more options, such as line-height, font size, cell width etc. Command line usage: ``` jt [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT] [-nfs NBFONTSIZE] [-tf TCFONT] [-tfs TCFONTSIZE] [-dfs DFFONTSIZE] [-m MARGINS] [-cursw CURSORWIDTH] [-cursc CURSORCOLOR] [-vim] [-cellw CELLWIDTH] [-lineh LINEHEIGHT] [-altp] [-P] [-T] [-N] [-r] [-dfonts] ```
There is a much easier way to do without adding the CSS files and all the other methods suggested. But you have to do it every time you start the Jupiter notebook. Go to inspect in your browser and click on the element selection icon and then click on the box. And at the bottom of the page, you will be seeing the styling option for CSS where you can easily change the font-size. [![enter image description here](https://i.stack.imgur.com/HKYzW.png)](https://i.stack.imgur.com/HKYzW.png)
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows system. For reference, these are in answer to the linked SO questions below: * [in #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): an unnamed file in `/usr/lib/python2.6/.../css/` * [in comment to #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): change monospace font in browser - worked but font is italic * [in #2](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook): `custom.css` in profile subdirectory `/static/custom/custom.css` Related questions: 1. [Change ipython notebook font type](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1) 2. [Change font & background color in ipython notebook](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook) 3. [Changing (back to default) font in ipython notebook](https://stackoverflow.com/questions/20870335/changing-back-to-default-font-in-ipython-notebook) (unanswered) - **Edit:** Changing the monospace font in my browser worked, as suggested in an answer comment of #1. However the font is italic, which is not what is intended.
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
You can hover to `.ipython` folder (i.e. you can type `$ ipython locate` in your terminal/bash OR `CMD.exe Prompt` from your Anaconda Navigator to see where is your ipython is located) Then, in `.ipython`, you will see `profile_default` directory which is the default one. This directory will have `static/custom/custom.css` file located. You can now apply change to this `custom.css` file. There are a lot of styles in the `custom.css` file that you can use or search for. For example, you can see [this link](https://github.com/titipata/customize_ipython_notebook/blob/master/custom.css) (which is my own customize `custom.css` file) Basically, this `custom.css` file apply changes to your browser. You can use inspect elements in your ipython notebook to see which elements you want to change. Then, you can changes to the `custom.css` file. For example, you can add these chunk to change font in `.CodeMirror pre` to type `Monaco` ``` .CodeMirror pre {font-family: Monaco; font-size: 9pt;} ``` **Note** that now for Jupyter notebook version >= 4.1, the custom css file is moved to `~/.jupyter/custom/custom.css` instead.
In addition to the suggestion by Konrad here, I'd like to suggest [jupyter themes](https://github.com/dunovank/jupyter-themes), which seems to have more options, such as line-height, font size, cell width etc. Command line usage: ``` jt [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT] [-nfs NBFONTSIZE] [-tf TCFONT] [-tfs TCFONTSIZE] [-dfs DFFONTSIZE] [-m MARGINS] [-cursw CURSORWIDTH] [-cursc CURSORCOLOR] [-vim] [-cellw CELLWIDTH] [-lineh LINEHEIGHT] [-altp] [-P] [-T] [-N] [-r] [-dfonts] ```
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows system. For reference, these are in answer to the linked SO questions below: * [in #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): an unnamed file in `/usr/lib/python2.6/.../css/` * [in comment to #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): change monospace font in browser - worked but font is italic * [in #2](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook): `custom.css` in profile subdirectory `/static/custom/custom.css` Related questions: 1. [Change ipython notebook font type](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1) 2. [Change font & background color in ipython notebook](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook) 3. [Changing (back to default) font in ipython notebook](https://stackoverflow.com/questions/20870335/changing-back-to-default-font-in-ipython-notebook) (unanswered) - **Edit:** Changing the monospace font in my browser worked, as suggested in an answer comment of #1. However the font is italic, which is not what is intended.
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
I would also suggest that you explore the options offered by the [**jupyter themer**](https://github.com/transcranial/jupyter-themer). For more modest interface changes you may be satisfied with running the syntax: ``` jupyter-themer [-c COLOR, --color COLOR] [-l LAYOUT, --layout LAYOUT] [-t TYPOGRAPHY, --typography TYPOGRAPHY] ``` where the options offered by *themer* would provide you with a less onerous way of making some changes in to the look of Jupyter Notebook. Naturally, you may still to prefer edit the **`.css`** files if the changes you want to apply are elaborate.
There is a much easier way to do without adding the CSS files and all the other methods suggested. But you have to do it every time you start the Jupiter notebook. Go to inspect in your browser and click on the element selection icon and then click on the box. And at the bottom of the page, you will be seeing the styling option for CSS where you can easily change the font-size. [![enter image description here](https://i.stack.imgur.com/HKYzW.png)](https://i.stack.imgur.com/HKYzW.png)
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows system. For reference, these are in answer to the linked SO questions below: * [in #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): an unnamed file in `/usr/lib/python2.6/.../css/` * [in comment to #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): change monospace font in browser - worked but font is italic * [in #2](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook): `custom.css` in profile subdirectory `/static/custom/custom.css` Related questions: 1. [Change ipython notebook font type](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1) 2. [Change font & background color in ipython notebook](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook) 3. [Changing (back to default) font in ipython notebook](https://stackoverflow.com/questions/20870335/changing-back-to-default-font-in-ipython-notebook) (unanswered) - **Edit:** Changing the monospace font in my browser worked, as suggested in an answer comment of #1. However the font is italic, which is not what is intended.
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In your notebook (simple approach). Add new cell with following code ``` %%html <style type='text/css'> .CodeMirror{ font-size: 12px; } div.output_area pre { font-size: 12px; } </style> ```
For chrome users, This is very simple. Just install the desired font in your OS. Then open the said browser, Go to Settings -> Appearance -> Customize font. Go to fixed width font and from drop down list select the desired font. Note: This might also change the fonts at some other places depending on the web pages that you visit.
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows system. For reference, these are in answer to the linked SO questions below: * [in #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): an unnamed file in `/usr/lib/python2.6/.../css/` * [in comment to #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): change monospace font in browser - worked but font is italic * [in #2](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook): `custom.css` in profile subdirectory `/static/custom/custom.css` Related questions: 1. [Change ipython notebook font type](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1) 2. [Change font & background color in ipython notebook](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook) 3. [Changing (back to default) font in ipython notebook](https://stackoverflow.com/questions/20870335/changing-back-to-default-font-in-ipython-notebook) (unanswered) - **Edit:** Changing the monospace font in my browser worked, as suggested in an answer comment of #1. However the font is italic, which is not what is intended.
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
I would also suggest that you explore the options offered by the [**jupyter themer**](https://github.com/transcranial/jupyter-themer). For more modest interface changes you may be satisfied with running the syntax: ``` jupyter-themer [-c COLOR, --color COLOR] [-l LAYOUT, --layout LAYOUT] [-t TYPOGRAPHY, --typography TYPOGRAPHY] ``` where the options offered by *themer* would provide you with a less onerous way of making some changes in to the look of Jupyter Notebook. Naturally, you may still to prefer edit the **`.css`** files if the changes you want to apply are elaborate.
For chrome users, This is very simple. Just install the desired font in your OS. Then open the said browser, Go to Settings -> Appearance -> Customize font. Go to fixed width font and from drop down list select the desired font. Note: This might also change the fonts at some other places depending on the web pages that you visit.
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows system. For reference, these are in answer to the linked SO questions below: * [in #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): an unnamed file in `/usr/lib/python2.6/.../css/` * [in comment to #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): change monospace font in browser - worked but font is italic * [in #2](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook): `custom.css` in profile subdirectory `/static/custom/custom.css` Related questions: 1. [Change ipython notebook font type](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1) 2. [Change font & background color in ipython notebook](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook) 3. [Changing (back to default) font in ipython notebook](https://stackoverflow.com/questions/20870335/changing-back-to-default-font-in-ipython-notebook) (unanswered) - **Edit:** Changing the monospace font in my browser worked, as suggested in an answer comment of #1. However the font is italic, which is not what is intended.
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In addition to the suggestion by Konrad here, I'd like to suggest [jupyter themes](https://github.com/dunovank/jupyter-themes), which seems to have more options, such as line-height, font size, cell width etc. Command line usage: ``` jt [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT] [-nfs NBFONTSIZE] [-tf TCFONT] [-tfs TCFONTSIZE] [-dfs DFFONTSIZE] [-m MARGINS] [-cursw CURSORWIDTH] [-cursc CURSORCOLOR] [-vim] [-cellw CELLWIDTH] [-lineh LINEHEIGHT] [-altp] [-P] [-T] [-N] [-r] [-dfonts] ```
For chrome users, This is very simple. Just install the desired font in your OS. Then open the said browser, Go to Settings -> Appearance -> Customize font. Go to fixed width font and from drop down list select the desired font. Note: This might also change the fonts at some other places depending on the web pages that you visit.
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows system. For reference, these are in answer to the linked SO questions below: * [in #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): an unnamed file in `/usr/lib/python2.6/.../css/` * [in comment to #1](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1): change monospace font in browser - worked but font is italic * [in #2](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook): `custom.css` in profile subdirectory `/static/custom/custom.css` Related questions: 1. [Change ipython notebook font type](https://stackoverflow.com/questions/13347691/change-ipython-notebook-font-type?rq=1) 2. [Change font & background color in ipython notebook](https://stackoverflow.com/questions/18706701/change-font-background-color-in-ipython-notebook) 3. [Changing (back to default) font in ipython notebook](https://stackoverflow.com/questions/20870335/changing-back-to-default-font-in-ipython-notebook) (unanswered) - **Edit:** Changing the monospace font in my browser worked, as suggested in an answer comment of #1. However the font is italic, which is not what is intended.
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
The new location of the theme file is: `~/.jupyter/custom/custom.css`
In your notebook (simple approach). Add new cell with following code ``` %%html <style type='text/css'> .CodeMirror{ font-size: 12px; } div.output_area pre { font-size: 12px; } </style> ```
19,254,178
essentially I am writing something based off of python and I would like to, in python, be able to get the result of a javascript function. Lets say `function.js` has a bunch of functions inside it If I have some python code, in it I would like to be able to do something like the following: ``` val = some_js_function(param1,param2,...paramn) ``` now `some_js_function` would be a function from the `function.js` file. This would set the variable `val` in my Python code to the result of that JS function. **How could I go about doing this? Or do I have to rawCode a FFI for javascript myself.**
2013/10/08
[ "https://Stackoverflow.com/questions/19254178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2127988/" ]
My best theory is that this is a possible consequence of dropping and re-creating a table with the same name (<https://issues.apache.org/jira/browse/CASSANDRA-5905>). We are targeting a fix for 2.1 (<https://issues.apache.org/jira/browse/CASSANDRA-5202>); in the meantime, prefer TRUNCATE over drop/recreate.
Although its very late and you must have solve this issue as well. For others having similar problem, try this ``` sudo bash -c 'rm -rf /var/lib/cassandra/data/system/*' ``` Remember, its only for development purposes. **THIS COMMAND WILL DELETE ALL YOUR DATA.**
51,136,741
I'm trying to deploy a simple python app to Google Container Engine: I have created a cluster then run `kubectl create -f deployment.yaml` It has been created a deployment pod on my cluster. After that i have created a service as: `kubectl create -f deployment.yaml` > > Here's my Yaml configurations: > > > **pod.yaml**: > > > ``` apiVersion: v1 kind: Pod metadata: name: test-app spec: containers: - name: test-ctr image: arycloud/flask-svc ports: - containerPort: 5000 ``` > > Here's my Dockerfile: > > > ``` FROM python:alpine3.7 COPY . /app WORKDIR /app RUN pip install -r requirements.txt EXPOSE 5000 CMD python ./app.py ``` > > **deployment.yaml:** > > > ``` apiVersion: extensions/v1beta1 kind: Deployment metadata: labels: app: test-app name: test-app spec: replicas: 1 template: metadata: labels: app: test-app name: test-app spec: containers: - name: test-app image: arycloud/flask-svc resources: requests: cpu: "100m" imagePullPolicy: Always ports: - containerPort: 8080 ``` > > **service.yaml:** > > > ``` apiVersion: v1 kind: Service metadata: name: test-app labels: app: test-app spec: type: LoadBalancer ports: - name: http port: 80 protocol: TCP targetPort: 8080 nodePort: 32000 selector: app: test-app ``` > > **Ingress** > > > ``` apiVersion: extensions/v1beta1 kind: Ingress metadata: name: test-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: - http: paths: - path: / backend: serviceName: frontend servicePort: 80 ``` It creates a LoadBalancer and provides an external IP, when I open the IP it returns `Connection Refused error` What's going wrong? Help me, please! Thank You, Abdul
2018/07/02
[ "https://Stackoverflow.com/questions/51136741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644562/" ]
> > The HashedPassword + Salt is stored in a column > > > That is probably the root problem. You don't need to provide or handle a Salt. See [this answer](http://%20stackoverflow.com/a/17758221/9695604). You should not need a `GetSalt()` method. You can't simply concatenate 2 base64 strings, the decoder doesn't know how to handle that.
The Base64 format stores 6 bits per character. Which, as bytes are 8 bits, sometimes some padding is needed at the end. One or two `=` characters are appended. `=` is not otherwise used. If you concatenate two Base64 strings at the join there maybe some padding. Putting padding in the middle of a Base64 string is not valid. Instead concatenate the byte arrays, and then encode.
52,648,383
I am trying to perform a MultiOutput Regression using ElasticNet and Random Forests as follows: ```python from sklearn.ensemble import RandomForestRegressor from sklearn.multioutput import MultiOutputRegressor from sklearn.linear_model import ElasticNet X_train, X_test, y_train, y_test = train_test_split(X_features, y, test_size=0.30,random_state=0) ``` Elastic Net ```python l1_range=np.arange(0.1,1.05,0.1).tolist() regr_Enet=ElasticNetCV(cv=5,copy_X=True,n_alphas=100,l1_ratio=l1_range,selection='cyclic',normalize=False,verbose =2,n_jobs=1) regr_multi_Enet= MultiOutputRegressor(regr_Enet)##ElasticNetCV regr_multi_Enet.fit(X_train, y_train) ``` Random Forest ```python max_depth = 20 number_of_trees=100 regr_multi_RF=MultiOutputRegressor(RandomForestRegressor(n_estimators=number_of_trees,max_depth=max_depth,random_state=0,n_jobs=1,verbose=1)) regr_multi_RF.fit(X_train, y_train) y_multirf = regr_multi_RF.predict(X_test) ``` Everything is going well, however I haven't found a way to obtain the coefficients (coef\_ ) or most important features (feature\_importances\_) of the model. When I write: ```python regr_multi_Enet.coef_ regr_multi_RF.feature_importances_ ``` It shows the following error: ```python AttributeError: 'MultiOutputRegressor' object has no attribute 'feature_importances_' AttributeError: 'MultiOutputRegressor' object has no attribute 'coef_' ``` I have read the documentation on MultiOutputRegressor but I cannot find a way to extract the coefficients. How to retrieve them?
2018/10/04
[ "https://Stackoverflow.com/questions/52648383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10456915/" ]
MultiOutputRegressor itself doesn't have these attributes - you need to access the underlying estimators first using the `estimators_` attribute (which, although not mentioned in the [docs](http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputRegressor.html), it exists indeed - see the docs for [MultiOutputClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputClassifier.html)). Here is a reproducible example: ```python from sklearn.multioutput import MultiOutputRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import ElasticNet # dummy data X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) W = np.array([[1, 1], [1, 1], [2, 2], [2, 2]]) regr_multi_RF=MultiOutputRegressor(RandomForestRegressor()) regr_multi_RF.fit(X,W) # how many estimators? len(regr_multi_RF.estimators_) # 2 regr_multi_RF.estimators_[0].feature_importances_ # array([ 0.4, 0.6]) regr_multi_RF.estimators_[1].feature_importances_ # array([ 0.4, 0.4]) regr_Enet = ElasticNet() regr_multi_Enet= MultiOutputRegressor(regr_Enet) regr_multi_Enet.fit(X, W) regr_multi_Enet.estimators_[0].coef_ # array([ 0.08333333, 0. ]) regr_multi_Enet.estimators_[1].coef_ # array([ 0.08333333, 0. ]) ```
``` regr_multi_Enet.estimators_[0].coef_ ``` To get the coefficients of the first estimator etc.
26,292,909
this is my first post here! My goal is to duplicate the payload of a unidirectional TCP stream and send this payload to multiple endpoints concurrently. I have a working prototype written in Python, however I am new to Python, and to Socket programming. Ideally the solution is capable of running in both Windows and \*nix environments. This prototype works, however it creates a new send TCP connection for each Buffer length (currently set to 4096 bytes). The main problem with this is I will eventually run out of local ports to send from, and ideally I would like the data to pass from each single incoming TCP stream to one single TCP stream out (for each endpoint). The incoming data can vary from less than 1024 bytes to hundreds of megabytes. At the moment a new outgoing TCP stream is initiated for every 4096 bytes. I am not sure if the problem is in my implementation of threading, or if I have missed something else really obvious. In my research I have found that select() could help, however I am not sure if it would be appropriate because I may need to process some of the incoming data and respond to the sending client for certain cases in the future. Here is the code I have so far (some of the code variations I have tried are commented out): ``` #!/usr/bin/python #One way TCP payload duplication import sys import threading from socket import * bufsize = 4096 host= '' # Methods: #handles sending the data to the endpoints def send(endpoint,port,data): sendSocket = socket(AF_INET, SOCK_STREAM) #sendSocket.setblocking(1) sendSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) #sendport = sendSocket.getsockname #print sendport try: sendSocket.connect((endpoint, port)) sendSocket.sendall(data) except IOError as msg: print "Send Failed. Error Code: " + str(msg[0]) + ' Message: ' + msg[1] sys.exit() #handles threading for sending data to endpoints def forward(service, ENDPOINT_LIST, port, data): #for each endpoint in the endpoint list start a new send thread for endpoint in ENDPOINT_LIST: print "Forwarding data for %s from %s:%s to %s:%s" % (service,host,port,endpoint,port) #send(endpoint,port,data) ethread = threading.Thread(target=send, args=(endpoint,port,data)) ethread.start() #handles threading for incoming clients def clientthread(conn,service,ENDPOINT_LIST,port): while True: #receive data form client data = conn.recv(bufsize) if not data: break cthread = threading.Thread(target=forward, args=(service, ENDPOINT_LIST, port, data)) cthread.start() #no data? then close the connection conn.close() #handles listening to sockets for incoming connections def listen(service, ENDPOINT_LIST, port): #create the socket listenSocket = socket(AF_INET, SOCK_STREAM) #Allow reusing addresses - I think this is important to stop local ports getting eaten up by never-ending tcp streams that don't close listenSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) #try to bind the socket to host and port try: listenSocket.bind((host, port)) #display an error message if you can't except IOError as msg: print "Bind Failed. Error Code: " + str(msg[0]) + ' Message: ' + msg[1] sys.exit() #start listening on the socket listenSocket.listen(10) print "Service %s on port %s is listening" %(service,port) while True: #wait to accept a connection conn, addr = listenSocket.accept() print 'Connected to ' + addr[0] + ':' + str(addr[1]) + ' on port ' + str(port) #start new thread for each connection lthread = threading.Thread(target=clientthread , args=(conn,service,ENDPOINT_LIST,port)) lthread.start() #If no data close the connection listenSocket.close() service = "Dumb-one-way-tcp-service-name1" ENDPOINT_LIST = ["192.168.1.100","192.168.1.200"] port = 55551 listen(service,ENDPOINT_LIST,port) ``` I have looked into other libraries to try to achieve my goal, including using: * Twisted * Asyncore * Scapy However I found them quite complicated for my modest needs and programming skill level. If anyone has any suggestions on how I could refine the approach I have, or any other ways this goal could be achieved, please let me know!
2014/10/10
[ "https://Stackoverflow.com/questions/26292909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4128004/" ]
The problem is caused by missing or conflicting dependencies: 1. Add hadoop-auth to your classpath 2. If the problem still arises, remove hadoop-core from your classpath. It is conflicting with hadoop-auth. This will solve the problem.
Finally i found an answer for this. 1. Copy the PlatformName class from hadoop-auth and custom compile it locally. package org.apache.hadoop.util; public class PlatformName { ``` private static final String platformName = System.getProperty("os.name") + "-" + System.getProperty("os.arch") + "-" + System.getProperty("sun.arch.data.model"); public static final String JAVA_VENDOR_NAME = System.getProperty("java.vendor"); public static final boolean IBM_JAVA = JAVA_VENDOR_NAME.contains("IBM"); public static String getPlatformName() { return platformName; } public static void main(String[] args) { System.out.println(platformName); } } ``` 2. Copy paste the class file in your hadoop-core. You should be up and running. thanks to all
4,178,440
Any Java tutorial that resembles Mark Pilgrim's approach for [DiveIntoPython](http://www.diveintopython.net/)?
2010/11/14
[ "https://Stackoverflow.com/questions/4178440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/313127/" ]
What about the official Java Tutorial? I found it pretty helpful to get started with the language.
I haven't read Dive Into Python but I do know that Bruce Eckels Thinking In Java is an excellent book and well worth a look. Be warned though - it's monster size and not easy to carry around!
4,178,440
Any Java tutorial that resembles Mark Pilgrim's approach for [DiveIntoPython](http://www.diveintopython.net/)?
2010/11/14
[ "https://Stackoverflow.com/questions/4178440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/313127/" ]
I haven't read Dive Into Python but I do know that Bruce Eckels Thinking In Java is an excellent book and well worth a look. Be warned though - it's monster size and not easy to carry around!
I don't think there is anything like *Dive into Python* in the Java world. The Java language doesn't lend itself to the model of 'Check out what we can do with these 15 lines of code!' Best approach would be to dive in yourself, pick a project, and use the tutorial and the docs. Many people will recommend Eckel's *Thinking in Java* but know that it is the polar opposite of *Dive into Python* -- it is slow, methodical, and thorough.
4,178,440
Any Java tutorial that resembles Mark Pilgrim's approach for [DiveIntoPython](http://www.diveintopython.net/)?
2010/11/14
[ "https://Stackoverflow.com/questions/4178440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/313127/" ]
What about the official Java Tutorial? I found it pretty helpful to get started with the language.
I don't think there is anything like *Dive into Python* in the Java world. The Java language doesn't lend itself to the model of 'Check out what we can do with these 15 lines of code!' Best approach would be to dive in yourself, pick a project, and use the tutorial and the docs. Many people will recommend Eckel's *Thinking in Java* but know that it is the polar opposite of *Dive into Python* -- it is slow, methodical, and thorough.
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really debug: just informative behavior of the application. A first, easy solution is to put prints ``` def doStuff(): print "starting doing stuff" print "I am starting to do step 1" doStep1() print "I did step 1" print "I am starting to do step 2" doStep2() print "I did step 2" print "I am starting to do step 3" doStep3() print "I did step 3" ``` In general, this is quite bad. Suppose that this code is going to end up in a library. I would not expect my library to print stuff out. I would expect it to do the job silently. Still, sometimes I would like to provide information, not only in debug situations, but also to keep the user informed that something is actually in the process of being done. Print is also bad because you don't have control of the handling of your messages. it just goes to stdout, and there's nothing you can do about it, except redirection. Another solution is to have a module for logging. ``` def doStuff(): Logging.log("starting doing stuff") Logging.log("I am starting to do step 1") doStep1() Logging.log("I did step 1") Logging.log("I am starting to do step 2") doStep2() Logging.log("I did step 2") Logging.log("I am starting to do step 3") doStep3() Logging.log("I did step 3") ``` This has the advantage that you sort of know a unique place for your logging service, and you can tinker this service as much as you want. You can silence it, redirect it onto a file, to stdout, or even to a network. Disadvantage is that you get a very strong coupling with the Logging module. Basically every part of your code depends on it, and you have calls to logging everywhere. The third option is to have a report object with a clear interface, and you pass it around ``` def doStuff(reporter=NullReporter()): reporter.log("starting doing stuff") reporter.log("I am starting to do step 1") doStep1() reporter.log("I did step 1") reporter.log("I am starting to do step 2") doStep2() reporter.log("I did step 2") reporter.log("I am starting to do step 3") doStep3() reporter.log("I did step 3") ``` Eventually, you can also pass the reporter object to doStepX() if they have more to say. Advantage: it reduces coupling with a module, but it introduces coupling with the instantiation of the NullReporter object. This can be solved by using None as default and checking before calling log, which is clumsy, because in python you have to write a conditional every time (in C you could define a macro) ``` def doStuff(reporter=None): if reporter is not None: reporter.log("starting doing stuff") # etc... ``` Edit: Another option is to work Qt-like, and have an emit() signal strategy. As your code executes, it emits information with proper status codes, and anyone interested can subscribe to the signals and provide info. Nice and clean, very decoupled, but requires a little of coding, as I don't think this can quickly be done with the python battery included. Finally, you can raise exceptions with a meaningful error message, but this of course can be used only if you are exiting from an error condition. it does not work for occasional reporting. Edit: I'd like to clarify the fact that the situation is more general, and not limited just to a sequence of invoked steps. it could also involve control structures: ``` if disconnected: print "Trying to connect" connect() else: print "obtaining list of files from remote host" getRemoteList() ``` The report could also be into the actual routines, so you would have a "print" in the connect() and getRemoteList() routines as a first statement. The question therefore are: * What do you think is the best design for some code (notably in the case of a library) to be at the same time silent when noise could be disruptive for the client, but verbose when useful? * How to handle a balanced intermix between logic code and reporting code ? * Intermixing between code and error checking has been solved with exceptions. What could be done to partition the "noise" of reporting from the code logic ? --- Edit: more thoughts for the mind I think it's not only a matter of decoupling the Logging code from the logic code. I think it's also a matter of decoupling the information production from the information consumption. Similar techniques already exist, in particular to handle UI events, but I don't really see the same patterns applied to the logging problem. --- Edit: I accepted the answer from Marcelo because he points out at the factual evidence that a compromise is the best solution in this case, and there's no silver bullet. However, all the others were interesting answers as well, and I was really pleased to upvote all of them. Thanks for the help!
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I found [this](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) while searching for Aspect Oriented Programming for python. I agree with other posters that such concerns shouldn't be mixed with core logic. In essence,points where you want to put logging might not always be arbitary, may be concepts like "all the points before error" could be identified by a pointcut. Other totally arbitary points can be captured using simple logging techniques.
I would use the standard [`logging`](http://docs.python.org/library/logging.html) module that's been part of the standard library since Python 2.3. That way, there is a good chance that people looking at your code will already know how the `logging` module works. And if they have to learn then at least it's well-documented, and their knowledge is transferable to other libraries that also use `logging`. Is there any feature that you want but can't find in the standard `logging` module?
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really debug: just informative behavior of the application. A first, easy solution is to put prints ``` def doStuff(): print "starting doing stuff" print "I am starting to do step 1" doStep1() print "I did step 1" print "I am starting to do step 2" doStep2() print "I did step 2" print "I am starting to do step 3" doStep3() print "I did step 3" ``` In general, this is quite bad. Suppose that this code is going to end up in a library. I would not expect my library to print stuff out. I would expect it to do the job silently. Still, sometimes I would like to provide information, not only in debug situations, but also to keep the user informed that something is actually in the process of being done. Print is also bad because you don't have control of the handling of your messages. it just goes to stdout, and there's nothing you can do about it, except redirection. Another solution is to have a module for logging. ``` def doStuff(): Logging.log("starting doing stuff") Logging.log("I am starting to do step 1") doStep1() Logging.log("I did step 1") Logging.log("I am starting to do step 2") doStep2() Logging.log("I did step 2") Logging.log("I am starting to do step 3") doStep3() Logging.log("I did step 3") ``` This has the advantage that you sort of know a unique place for your logging service, and you can tinker this service as much as you want. You can silence it, redirect it onto a file, to stdout, or even to a network. Disadvantage is that you get a very strong coupling with the Logging module. Basically every part of your code depends on it, and you have calls to logging everywhere. The third option is to have a report object with a clear interface, and you pass it around ``` def doStuff(reporter=NullReporter()): reporter.log("starting doing stuff") reporter.log("I am starting to do step 1") doStep1() reporter.log("I did step 1") reporter.log("I am starting to do step 2") doStep2() reporter.log("I did step 2") reporter.log("I am starting to do step 3") doStep3() reporter.log("I did step 3") ``` Eventually, you can also pass the reporter object to doStepX() if they have more to say. Advantage: it reduces coupling with a module, but it introduces coupling with the instantiation of the NullReporter object. This can be solved by using None as default and checking before calling log, which is clumsy, because in python you have to write a conditional every time (in C you could define a macro) ``` def doStuff(reporter=None): if reporter is not None: reporter.log("starting doing stuff") # etc... ``` Edit: Another option is to work Qt-like, and have an emit() signal strategy. As your code executes, it emits information with proper status codes, and anyone interested can subscribe to the signals and provide info. Nice and clean, very decoupled, but requires a little of coding, as I don't think this can quickly be done with the python battery included. Finally, you can raise exceptions with a meaningful error message, but this of course can be used only if you are exiting from an error condition. it does not work for occasional reporting. Edit: I'd like to clarify the fact that the situation is more general, and not limited just to a sequence of invoked steps. it could also involve control structures: ``` if disconnected: print "Trying to connect" connect() else: print "obtaining list of files from remote host" getRemoteList() ``` The report could also be into the actual routines, so you would have a "print" in the connect() and getRemoteList() routines as a first statement. The question therefore are: * What do you think is the best design for some code (notably in the case of a library) to be at the same time silent when noise could be disruptive for the client, but verbose when useful? * How to handle a balanced intermix between logic code and reporting code ? * Intermixing between code and error checking has been solved with exceptions. What could be done to partition the "noise" of reporting from the code logic ? --- Edit: more thoughts for the mind I think it's not only a matter of decoupling the Logging code from the logic code. I think it's also a matter of decoupling the information production from the information consumption. Similar techniques already exist, in particular to handle UI events, but I don't really see the same patterns applied to the logging problem. --- Edit: I accepted the answer from Marcelo because he points out at the factual evidence that a compromise is the best solution in this case, and there's no silver bullet. However, all the others were interesting answers as well, and I was really pleased to upvote all of them. Thanks for the help!
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I think there is a point where you must draw a line and make a compromise. I see no way to completely decouple logging from the system because you have to send those messages somewhere and in a way that someone understands. I would go with the default logging module, because... it's the default module. It's well documented and comes with the default library, so no dependency issues here. Also, you save yourself from reinventing the wheel. That said, if you are really into doing something new, you could make a global reporter object. You can instantiate and configure it at the beginning of your process (logging, no logging, redirecting streams, etc. Even in a per process/function/step basis) and call it from everywhere, no need to pass it around (maybe in a multi threaded environment, but that would be minimal). You can also put it inside another thread and catch log events a la Qt.
I would use the standard [`logging`](http://docs.python.org/library/logging.html) module that's been part of the standard library since Python 2.3. That way, there is a good chance that people looking at your code will already know how the `logging` module works. And if they have to learn then at least it's well-documented, and their knowledge is transferable to other libraries that also use `logging`. Is there any feature that you want but can't find in the standard `logging` module?
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really debug: just informative behavior of the application. A first, easy solution is to put prints ``` def doStuff(): print "starting doing stuff" print "I am starting to do step 1" doStep1() print "I did step 1" print "I am starting to do step 2" doStep2() print "I did step 2" print "I am starting to do step 3" doStep3() print "I did step 3" ``` In general, this is quite bad. Suppose that this code is going to end up in a library. I would not expect my library to print stuff out. I would expect it to do the job silently. Still, sometimes I would like to provide information, not only in debug situations, but also to keep the user informed that something is actually in the process of being done. Print is also bad because you don't have control of the handling of your messages. it just goes to stdout, and there's nothing you can do about it, except redirection. Another solution is to have a module for logging. ``` def doStuff(): Logging.log("starting doing stuff") Logging.log("I am starting to do step 1") doStep1() Logging.log("I did step 1") Logging.log("I am starting to do step 2") doStep2() Logging.log("I did step 2") Logging.log("I am starting to do step 3") doStep3() Logging.log("I did step 3") ``` This has the advantage that you sort of know a unique place for your logging service, and you can tinker this service as much as you want. You can silence it, redirect it onto a file, to stdout, or even to a network. Disadvantage is that you get a very strong coupling with the Logging module. Basically every part of your code depends on it, and you have calls to logging everywhere. The third option is to have a report object with a clear interface, and you pass it around ``` def doStuff(reporter=NullReporter()): reporter.log("starting doing stuff") reporter.log("I am starting to do step 1") doStep1() reporter.log("I did step 1") reporter.log("I am starting to do step 2") doStep2() reporter.log("I did step 2") reporter.log("I am starting to do step 3") doStep3() reporter.log("I did step 3") ``` Eventually, you can also pass the reporter object to doStepX() if they have more to say. Advantage: it reduces coupling with a module, but it introduces coupling with the instantiation of the NullReporter object. This can be solved by using None as default and checking before calling log, which is clumsy, because in python you have to write a conditional every time (in C you could define a macro) ``` def doStuff(reporter=None): if reporter is not None: reporter.log("starting doing stuff") # etc... ``` Edit: Another option is to work Qt-like, and have an emit() signal strategy. As your code executes, it emits information with proper status codes, and anyone interested can subscribe to the signals and provide info. Nice and clean, very decoupled, but requires a little of coding, as I don't think this can quickly be done with the python battery included. Finally, you can raise exceptions with a meaningful error message, but this of course can be used only if you are exiting from an error condition. it does not work for occasional reporting. Edit: I'd like to clarify the fact that the situation is more general, and not limited just to a sequence of invoked steps. it could also involve control structures: ``` if disconnected: print "Trying to connect" connect() else: print "obtaining list of files from remote host" getRemoteList() ``` The report could also be into the actual routines, so you would have a "print" in the connect() and getRemoteList() routines as a first statement. The question therefore are: * What do you think is the best design for some code (notably in the case of a library) to be at the same time silent when noise could be disruptive for the client, but verbose when useful? * How to handle a balanced intermix between logic code and reporting code ? * Intermixing between code and error checking has been solved with exceptions. What could be done to partition the "noise" of reporting from the code logic ? --- Edit: more thoughts for the mind I think it's not only a matter of decoupling the Logging code from the logic code. I think it's also a matter of decoupling the information production from the information consumption. Similar techniques already exist, in particular to handle UI events, but I don't really see the same patterns applied to the logging problem. --- Edit: I accepted the answer from Marcelo because he points out at the factual evidence that a compromise is the best solution in this case, and there's no silver bullet. However, all the others were interesting answers as well, and I was really pleased to upvote all of them. Thanks for the help!
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I often use DTrace for this. On OS X, python and ruby are both already set up with DTrace hooks. On other platforms, you'd probably have to do this yourself. But being able to attach debug traces to a running process is, well, awesome. However, for library code (let's say you're writing an http client library), the best option is to pass in an optional logger as a parameter, as you mentioned. DTrace is good for adding logging to something that's gone wrong in production (and sometimes elsewhere), but if other people might conceivably need access to logs to debug their code that subsequently calls into yours, then an optional logger as a parameter is absolutely the way to go.
I think the simplest solution is the best here. This depends on language, but just use a very short, globally accessible identifier - in PHP I use a custom function `trace($msg)` - and then just implement and re-implement that code as you see fit for the particular project or phase. The automatic, in-compiler version of this is the standard debugger. If you want to see meaningful labels, you need to write those labels yourself, unfortunately :) Or you could try temporarily transforming inline comments into function calls, but I'm not sure that would work.
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really debug: just informative behavior of the application. A first, easy solution is to put prints ``` def doStuff(): print "starting doing stuff" print "I am starting to do step 1" doStep1() print "I did step 1" print "I am starting to do step 2" doStep2() print "I did step 2" print "I am starting to do step 3" doStep3() print "I did step 3" ``` In general, this is quite bad. Suppose that this code is going to end up in a library. I would not expect my library to print stuff out. I would expect it to do the job silently. Still, sometimes I would like to provide information, not only in debug situations, but also to keep the user informed that something is actually in the process of being done. Print is also bad because you don't have control of the handling of your messages. it just goes to stdout, and there's nothing you can do about it, except redirection. Another solution is to have a module for logging. ``` def doStuff(): Logging.log("starting doing stuff") Logging.log("I am starting to do step 1") doStep1() Logging.log("I did step 1") Logging.log("I am starting to do step 2") doStep2() Logging.log("I did step 2") Logging.log("I am starting to do step 3") doStep3() Logging.log("I did step 3") ``` This has the advantage that you sort of know a unique place for your logging service, and you can tinker this service as much as you want. You can silence it, redirect it onto a file, to stdout, or even to a network. Disadvantage is that you get a very strong coupling with the Logging module. Basically every part of your code depends on it, and you have calls to logging everywhere. The third option is to have a report object with a clear interface, and you pass it around ``` def doStuff(reporter=NullReporter()): reporter.log("starting doing stuff") reporter.log("I am starting to do step 1") doStep1() reporter.log("I did step 1") reporter.log("I am starting to do step 2") doStep2() reporter.log("I did step 2") reporter.log("I am starting to do step 3") doStep3() reporter.log("I did step 3") ``` Eventually, you can also pass the reporter object to doStepX() if they have more to say. Advantage: it reduces coupling with a module, but it introduces coupling with the instantiation of the NullReporter object. This can be solved by using None as default and checking before calling log, which is clumsy, because in python you have to write a conditional every time (in C you could define a macro) ``` def doStuff(reporter=None): if reporter is not None: reporter.log("starting doing stuff") # etc... ``` Edit: Another option is to work Qt-like, and have an emit() signal strategy. As your code executes, it emits information with proper status codes, and anyone interested can subscribe to the signals and provide info. Nice and clean, very decoupled, but requires a little of coding, as I don't think this can quickly be done with the python battery included. Finally, you can raise exceptions with a meaningful error message, but this of course can be used only if you are exiting from an error condition. it does not work for occasional reporting. Edit: I'd like to clarify the fact that the situation is more general, and not limited just to a sequence of invoked steps. it could also involve control structures: ``` if disconnected: print "Trying to connect" connect() else: print "obtaining list of files from remote host" getRemoteList() ``` The report could also be into the actual routines, so you would have a "print" in the connect() and getRemoteList() routines as a first statement. The question therefore are: * What do you think is the best design for some code (notably in the case of a library) to be at the same time silent when noise could be disruptive for the client, but verbose when useful? * How to handle a balanced intermix between logic code and reporting code ? * Intermixing between code and error checking has been solved with exceptions. What could be done to partition the "noise" of reporting from the code logic ? --- Edit: more thoughts for the mind I think it's not only a matter of decoupling the Logging code from the logic code. I think it's also a matter of decoupling the information production from the information consumption. Similar techniques already exist, in particular to handle UI events, but I don't really see the same patterns applied to the logging problem. --- Edit: I accepted the answer from Marcelo because he points out at the factual evidence that a compromise is the best solution in this case, and there's no silver bullet. However, all the others were interesting answers as well, and I was really pleased to upvote all of them. Thanks for the help!
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
Another option would be to write the code without logging and then apply some transform to insert the appropriate logging statements before executing the code. The actual techniques to do this would be highly dependant on the language, but would be pretty similar to the process of writing a debugger. It probably isn't worth the added complexity though...
In response to your edit about information production/consumption: That's a valid concern for the general case, but logging is not the general case. In particular, you should not be relying on logging output from one part of your program to affect the execution of another part. That would indeed tightly couple the consumer to the implementation of the producer. Logging should be considered incidental to your main execution. Your systems should not know or care about the presence or contents of such log files (with the exception possibly of monitoring tools). That being the case, the notion of decoupling "consumption" of the logs from their production is inconsequential. Since you aren't using the logs to do anything meaningful, coupling is not an issue.
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really debug: just informative behavior of the application. A first, easy solution is to put prints ``` def doStuff(): print "starting doing stuff" print "I am starting to do step 1" doStep1() print "I did step 1" print "I am starting to do step 2" doStep2() print "I did step 2" print "I am starting to do step 3" doStep3() print "I did step 3" ``` In general, this is quite bad. Suppose that this code is going to end up in a library. I would not expect my library to print stuff out. I would expect it to do the job silently. Still, sometimes I would like to provide information, not only in debug situations, but also to keep the user informed that something is actually in the process of being done. Print is also bad because you don't have control of the handling of your messages. it just goes to stdout, and there's nothing you can do about it, except redirection. Another solution is to have a module for logging. ``` def doStuff(): Logging.log("starting doing stuff") Logging.log("I am starting to do step 1") doStep1() Logging.log("I did step 1") Logging.log("I am starting to do step 2") doStep2() Logging.log("I did step 2") Logging.log("I am starting to do step 3") doStep3() Logging.log("I did step 3") ``` This has the advantage that you sort of know a unique place for your logging service, and you can tinker this service as much as you want. You can silence it, redirect it onto a file, to stdout, or even to a network. Disadvantage is that you get a very strong coupling with the Logging module. Basically every part of your code depends on it, and you have calls to logging everywhere. The third option is to have a report object with a clear interface, and you pass it around ``` def doStuff(reporter=NullReporter()): reporter.log("starting doing stuff") reporter.log("I am starting to do step 1") doStep1() reporter.log("I did step 1") reporter.log("I am starting to do step 2") doStep2() reporter.log("I did step 2") reporter.log("I am starting to do step 3") doStep3() reporter.log("I did step 3") ``` Eventually, you can also pass the reporter object to doStepX() if they have more to say. Advantage: it reduces coupling with a module, but it introduces coupling with the instantiation of the NullReporter object. This can be solved by using None as default and checking before calling log, which is clumsy, because in python you have to write a conditional every time (in C you could define a macro) ``` def doStuff(reporter=None): if reporter is not None: reporter.log("starting doing stuff") # etc... ``` Edit: Another option is to work Qt-like, and have an emit() signal strategy. As your code executes, it emits information with proper status codes, and anyone interested can subscribe to the signals and provide info. Nice and clean, very decoupled, but requires a little of coding, as I don't think this can quickly be done with the python battery included. Finally, you can raise exceptions with a meaningful error message, but this of course can be used only if you are exiting from an error condition. it does not work for occasional reporting. Edit: I'd like to clarify the fact that the situation is more general, and not limited just to a sequence of invoked steps. it could also involve control structures: ``` if disconnected: print "Trying to connect" connect() else: print "obtaining list of files from remote host" getRemoteList() ``` The report could also be into the actual routines, so you would have a "print" in the connect() and getRemoteList() routines as a first statement. The question therefore are: * What do you think is the best design for some code (notably in the case of a library) to be at the same time silent when noise could be disruptive for the client, but verbose when useful? * How to handle a balanced intermix between logic code and reporting code ? * Intermixing between code and error checking has been solved with exceptions. What could be done to partition the "noise" of reporting from the code logic ? --- Edit: more thoughts for the mind I think it's not only a matter of decoupling the Logging code from the logic code. I think it's also a matter of decoupling the information production from the information consumption. Similar techniques already exist, in particular to handle UI events, but I don't really see the same patterns applied to the logging problem. --- Edit: I accepted the answer from Marcelo because he points out at the factual evidence that a compromise is the best solution in this case, and there's no silver bullet. However, all the others were interesting answers as well, and I was really pleased to upvote all of them. Thanks for the help!
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I found [this](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) while searching for Aspect Oriented Programming for python. I agree with other posters that such concerns shouldn't be mixed with core logic. In essence,points where you want to put logging might not always be arbitary, may be concepts like "all the points before error" could be identified by a pointcut. Other totally arbitary points can be captured using simple logging techniques.
I think the simplest solution is the best here. This depends on language, but just use a very short, globally accessible identifier - in PHP I use a custom function `trace($msg)` - and then just implement and re-implement that code as you see fit for the particular project or phase. The automatic, in-compiler version of this is the standard debugger. If you want to see meaningful labels, you need to write those labels yourself, unfortunately :) Or you could try temporarily transforming inline comments into function calls, but I'm not sure that would work.
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really debug: just informative behavior of the application. A first, easy solution is to put prints ``` def doStuff(): print "starting doing stuff" print "I am starting to do step 1" doStep1() print "I did step 1" print "I am starting to do step 2" doStep2() print "I did step 2" print "I am starting to do step 3" doStep3() print "I did step 3" ``` In general, this is quite bad. Suppose that this code is going to end up in a library. I would not expect my library to print stuff out. I would expect it to do the job silently. Still, sometimes I would like to provide information, not only in debug situations, but also to keep the user informed that something is actually in the process of being done. Print is also bad because you don't have control of the handling of your messages. it just goes to stdout, and there's nothing you can do about it, except redirection. Another solution is to have a module for logging. ``` def doStuff(): Logging.log("starting doing stuff") Logging.log("I am starting to do step 1") doStep1() Logging.log("I did step 1") Logging.log("I am starting to do step 2") doStep2() Logging.log("I did step 2") Logging.log("I am starting to do step 3") doStep3() Logging.log("I did step 3") ``` This has the advantage that you sort of know a unique place for your logging service, and you can tinker this service as much as you want. You can silence it, redirect it onto a file, to stdout, or even to a network. Disadvantage is that you get a very strong coupling with the Logging module. Basically every part of your code depends on it, and you have calls to logging everywhere. The third option is to have a report object with a clear interface, and you pass it around ``` def doStuff(reporter=NullReporter()): reporter.log("starting doing stuff") reporter.log("I am starting to do step 1") doStep1() reporter.log("I did step 1") reporter.log("I am starting to do step 2") doStep2() reporter.log("I did step 2") reporter.log("I am starting to do step 3") doStep3() reporter.log("I did step 3") ``` Eventually, you can also pass the reporter object to doStepX() if they have more to say. Advantage: it reduces coupling with a module, but it introduces coupling with the instantiation of the NullReporter object. This can be solved by using None as default and checking before calling log, which is clumsy, because in python you have to write a conditional every time (in C you could define a macro) ``` def doStuff(reporter=None): if reporter is not None: reporter.log("starting doing stuff") # etc... ``` Edit: Another option is to work Qt-like, and have an emit() signal strategy. As your code executes, it emits information with proper status codes, and anyone interested can subscribe to the signals and provide info. Nice and clean, very decoupled, but requires a little of coding, as I don't think this can quickly be done with the python battery included. Finally, you can raise exceptions with a meaningful error message, but this of course can be used only if you are exiting from an error condition. it does not work for occasional reporting. Edit: I'd like to clarify the fact that the situation is more general, and not limited just to a sequence of invoked steps. it could also involve control structures: ``` if disconnected: print "Trying to connect" connect() else: print "obtaining list of files from remote host" getRemoteList() ``` The report could also be into the actual routines, so you would have a "print" in the connect() and getRemoteList() routines as a first statement. The question therefore are: * What do you think is the best design for some code (notably in the case of a library) to be at the same time silent when noise could be disruptive for the client, but verbose when useful? * How to handle a balanced intermix between logic code and reporting code ? * Intermixing between code and error checking has been solved with exceptions. What could be done to partition the "noise" of reporting from the code logic ? --- Edit: more thoughts for the mind I think it's not only a matter of decoupling the Logging code from the logic code. I think it's also a matter of decoupling the information production from the information consumption. Similar techniques already exist, in particular to handle UI events, but I don't really see the same patterns applied to the logging problem. --- Edit: I accepted the answer from Marcelo because he points out at the factual evidence that a compromise is the best solution in this case, and there's no silver bullet. However, all the others were interesting answers as well, and I was really pleased to upvote all of them. Thanks for the help!
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I think there is a point where you must draw a line and make a compromise. I see no way to completely decouple logging from the system because you have to send those messages somewhere and in a way that someone understands. I would go with the default logging module, because... it's the default module. It's well documented and comes with the default library, so no dependency issues here. Also, you save yourself from reinventing the wheel. That said, if you are really into doing something new, you could make a global reporter object. You can instantiate and configure it at the beginning of your process (logging, no logging, redirecting streams, etc. Even in a per process/function/step basis) and call it from everywhere, no need to pass it around (maybe in a multi threaded environment, but that would be minimal). You can also put it inside another thread and catch log events a la Qt.
There should be tooling to allow boilerplate log messages a la "entering method A with parameters (1,2,3)", "returning from method B with value X, took 10 ms" to be automatically (and selectively) generated (controlled at run or deploy time). Writing that stuff by hand is just too boring/repetitive/error-prone. Not sure if there is, though. If you are going to write manual log messages, be sure to include some useful contextual information (user id, URL that is being looked at, search query, or such), so that if something does go wrong you get more information than just the method name.
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really debug: just informative behavior of the application. A first, easy solution is to put prints ``` def doStuff(): print "starting doing stuff" print "I am starting to do step 1" doStep1() print "I did step 1" print "I am starting to do step 2" doStep2() print "I did step 2" print "I am starting to do step 3" doStep3() print "I did step 3" ``` In general, this is quite bad. Suppose that this code is going to end up in a library. I would not expect my library to print stuff out. I would expect it to do the job silently. Still, sometimes I would like to provide information, not only in debug situations, but also to keep the user informed that something is actually in the process of being done. Print is also bad because you don't have control of the handling of your messages. it just goes to stdout, and there's nothing you can do about it, except redirection. Another solution is to have a module for logging. ``` def doStuff(): Logging.log("starting doing stuff") Logging.log("I am starting to do step 1") doStep1() Logging.log("I did step 1") Logging.log("I am starting to do step 2") doStep2() Logging.log("I did step 2") Logging.log("I am starting to do step 3") doStep3() Logging.log("I did step 3") ``` This has the advantage that you sort of know a unique place for your logging service, and you can tinker this service as much as you want. You can silence it, redirect it onto a file, to stdout, or even to a network. Disadvantage is that you get a very strong coupling with the Logging module. Basically every part of your code depends on it, and you have calls to logging everywhere. The third option is to have a report object with a clear interface, and you pass it around ``` def doStuff(reporter=NullReporter()): reporter.log("starting doing stuff") reporter.log("I am starting to do step 1") doStep1() reporter.log("I did step 1") reporter.log("I am starting to do step 2") doStep2() reporter.log("I did step 2") reporter.log("I am starting to do step 3") doStep3() reporter.log("I did step 3") ``` Eventually, you can also pass the reporter object to doStepX() if they have more to say. Advantage: it reduces coupling with a module, but it introduces coupling with the instantiation of the NullReporter object. This can be solved by using None as default and checking before calling log, which is clumsy, because in python you have to write a conditional every time (in C you could define a macro) ``` def doStuff(reporter=None): if reporter is not None: reporter.log("starting doing stuff") # etc... ``` Edit: Another option is to work Qt-like, and have an emit() signal strategy. As your code executes, it emits information with proper status codes, and anyone interested can subscribe to the signals and provide info. Nice and clean, very decoupled, but requires a little of coding, as I don't think this can quickly be done with the python battery included. Finally, you can raise exceptions with a meaningful error message, but this of course can be used only if you are exiting from an error condition. it does not work for occasional reporting. Edit: I'd like to clarify the fact that the situation is more general, and not limited just to a sequence of invoked steps. it could also involve control structures: ``` if disconnected: print "Trying to connect" connect() else: print "obtaining list of files from remote host" getRemoteList() ``` The report could also be into the actual routines, so you would have a "print" in the connect() and getRemoteList() routines as a first statement. The question therefore are: * What do you think is the best design for some code (notably in the case of a library) to be at the same time silent when noise could be disruptive for the client, but verbose when useful? * How to handle a balanced intermix between logic code and reporting code ? * Intermixing between code and error checking has been solved with exceptions. What could be done to partition the "noise" of reporting from the code logic ? --- Edit: more thoughts for the mind I think it's not only a matter of decoupling the Logging code from the logic code. I think it's also a matter of decoupling the information production from the information consumption. Similar techniques already exist, in particular to handle UI events, but I don't really see the same patterns applied to the logging problem. --- Edit: I accepted the answer from Marcelo because he points out at the factual evidence that a compromise is the best solution in this case, and there's no silver bullet. However, all the others were interesting answers as well, and I was really pleased to upvote all of them. Thanks for the help!
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I found [this](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) while searching for Aspect Oriented Programming for python. I agree with other posters that such concerns shouldn't be mixed with core logic. In essence,points where you want to put logging might not always be arbitary, may be concepts like "all the points before error" could be identified by a pointcut. Other totally arbitary points can be captured using simple logging techniques.
There should be tooling to allow boilerplate log messages a la "entering method A with parameters (1,2,3)", "returning from method B with value X, took 10 ms" to be automatically (and selectively) generated (controlled at run or deploy time). Writing that stuff by hand is just too boring/repetitive/error-prone. Not sure if there is, though. If you are going to write manual log messages, be sure to include some useful contextual information (user id, URL that is being looked at, search query, or such), so that if something does go wrong you get more information than just the method name.
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really debug: just informative behavior of the application. A first, easy solution is to put prints ``` def doStuff(): print "starting doing stuff" print "I am starting to do step 1" doStep1() print "I did step 1" print "I am starting to do step 2" doStep2() print "I did step 2" print "I am starting to do step 3" doStep3() print "I did step 3" ``` In general, this is quite bad. Suppose that this code is going to end up in a library. I would not expect my library to print stuff out. I would expect it to do the job silently. Still, sometimes I would like to provide information, not only in debug situations, but also to keep the user informed that something is actually in the process of being done. Print is also bad because you don't have control of the handling of your messages. it just goes to stdout, and there's nothing you can do about it, except redirection. Another solution is to have a module for logging. ``` def doStuff(): Logging.log("starting doing stuff") Logging.log("I am starting to do step 1") doStep1() Logging.log("I did step 1") Logging.log("I am starting to do step 2") doStep2() Logging.log("I did step 2") Logging.log("I am starting to do step 3") doStep3() Logging.log("I did step 3") ``` This has the advantage that you sort of know a unique place for your logging service, and you can tinker this service as much as you want. You can silence it, redirect it onto a file, to stdout, or even to a network. Disadvantage is that you get a very strong coupling with the Logging module. Basically every part of your code depends on it, and you have calls to logging everywhere. The third option is to have a report object with a clear interface, and you pass it around ``` def doStuff(reporter=NullReporter()): reporter.log("starting doing stuff") reporter.log("I am starting to do step 1") doStep1() reporter.log("I did step 1") reporter.log("I am starting to do step 2") doStep2() reporter.log("I did step 2") reporter.log("I am starting to do step 3") doStep3() reporter.log("I did step 3") ``` Eventually, you can also pass the reporter object to doStepX() if they have more to say. Advantage: it reduces coupling with a module, but it introduces coupling with the instantiation of the NullReporter object. This can be solved by using None as default and checking before calling log, which is clumsy, because in python you have to write a conditional every time (in C you could define a macro) ``` def doStuff(reporter=None): if reporter is not None: reporter.log("starting doing stuff") # etc... ``` Edit: Another option is to work Qt-like, and have an emit() signal strategy. As your code executes, it emits information with proper status codes, and anyone interested can subscribe to the signals and provide info. Nice and clean, very decoupled, but requires a little of coding, as I don't think this can quickly be done with the python battery included. Finally, you can raise exceptions with a meaningful error message, but this of course can be used only if you are exiting from an error condition. it does not work for occasional reporting. Edit: I'd like to clarify the fact that the situation is more general, and not limited just to a sequence of invoked steps. it could also involve control structures: ``` if disconnected: print "Trying to connect" connect() else: print "obtaining list of files from remote host" getRemoteList() ``` The report could also be into the actual routines, so you would have a "print" in the connect() and getRemoteList() routines as a first statement. The question therefore are: * What do you think is the best design for some code (notably in the case of a library) to be at the same time silent when noise could be disruptive for the client, but verbose when useful? * How to handle a balanced intermix between logic code and reporting code ? * Intermixing between code and error checking has been solved with exceptions. What could be done to partition the "noise" of reporting from the code logic ? --- Edit: more thoughts for the mind I think it's not only a matter of decoupling the Logging code from the logic code. I think it's also a matter of decoupling the information production from the information consumption. Similar techniques already exist, in particular to handle UI events, but I don't really see the same patterns applied to the logging problem. --- Edit: I accepted the answer from Marcelo because he points out at the factual evidence that a compromise is the best solution in this case, and there's no silver bullet. However, all the others were interesting answers as well, and I was really pleased to upvote all of them. Thanks for the help!
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I think there is a point where you must draw a line and make a compromise. I see no way to completely decouple logging from the system because you have to send those messages somewhere and in a way that someone understands. I would go with the default logging module, because... it's the default module. It's well documented and comes with the default library, so no dependency issues here. Also, you save yourself from reinventing the wheel. That said, if you are really into doing something new, you could make a global reporter object. You can instantiate and configure it at the beginning of your process (logging, no logging, redirecting streams, etc. Even in a per process/function/step basis) and call it from everywhere, no need to pass it around (maybe in a multi threaded environment, but that would be minimal). You can also put it inside another thread and catch log events a la Qt.
I think the simplest solution is the best here. This depends on language, but just use a very short, globally accessible identifier - in PHP I use a custom function `trace($msg)` - and then just implement and re-implement that code as you see fit for the particular project or phase. The automatic, in-compiler version of this is the standard debugger. If you want to see meaningful labels, you need to write those labels yourself, unfortunately :) Or you could try temporarily transforming inline comments into function calls, but I'm not sure that would work.
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really debug: just informative behavior of the application. A first, easy solution is to put prints ``` def doStuff(): print "starting doing stuff" print "I am starting to do step 1" doStep1() print "I did step 1" print "I am starting to do step 2" doStep2() print "I did step 2" print "I am starting to do step 3" doStep3() print "I did step 3" ``` In general, this is quite bad. Suppose that this code is going to end up in a library. I would not expect my library to print stuff out. I would expect it to do the job silently. Still, sometimes I would like to provide information, not only in debug situations, but also to keep the user informed that something is actually in the process of being done. Print is also bad because you don't have control of the handling of your messages. it just goes to stdout, and there's nothing you can do about it, except redirection. Another solution is to have a module for logging. ``` def doStuff(): Logging.log("starting doing stuff") Logging.log("I am starting to do step 1") doStep1() Logging.log("I did step 1") Logging.log("I am starting to do step 2") doStep2() Logging.log("I did step 2") Logging.log("I am starting to do step 3") doStep3() Logging.log("I did step 3") ``` This has the advantage that you sort of know a unique place for your logging service, and you can tinker this service as much as you want. You can silence it, redirect it onto a file, to stdout, or even to a network. Disadvantage is that you get a very strong coupling with the Logging module. Basically every part of your code depends on it, and you have calls to logging everywhere. The third option is to have a report object with a clear interface, and you pass it around ``` def doStuff(reporter=NullReporter()): reporter.log("starting doing stuff") reporter.log("I am starting to do step 1") doStep1() reporter.log("I did step 1") reporter.log("I am starting to do step 2") doStep2() reporter.log("I did step 2") reporter.log("I am starting to do step 3") doStep3() reporter.log("I did step 3") ``` Eventually, you can also pass the reporter object to doStepX() if they have more to say. Advantage: it reduces coupling with a module, but it introduces coupling with the instantiation of the NullReporter object. This can be solved by using None as default and checking before calling log, which is clumsy, because in python you have to write a conditional every time (in C you could define a macro) ``` def doStuff(reporter=None): if reporter is not None: reporter.log("starting doing stuff") # etc... ``` Edit: Another option is to work Qt-like, and have an emit() signal strategy. As your code executes, it emits information with proper status codes, and anyone interested can subscribe to the signals and provide info. Nice and clean, very decoupled, but requires a little of coding, as I don't think this can quickly be done with the python battery included. Finally, you can raise exceptions with a meaningful error message, but this of course can be used only if you are exiting from an error condition. it does not work for occasional reporting. Edit: I'd like to clarify the fact that the situation is more general, and not limited just to a sequence of invoked steps. it could also involve control structures: ``` if disconnected: print "Trying to connect" connect() else: print "obtaining list of files from remote host" getRemoteList() ``` The report could also be into the actual routines, so you would have a "print" in the connect() and getRemoteList() routines as a first statement. The question therefore are: * What do you think is the best design for some code (notably in the case of a library) to be at the same time silent when noise could be disruptive for the client, but verbose when useful? * How to handle a balanced intermix between logic code and reporting code ? * Intermixing between code and error checking has been solved with exceptions. What could be done to partition the "noise" of reporting from the code logic ? --- Edit: more thoughts for the mind I think it's not only a matter of decoupling the Logging code from the logic code. I think it's also a matter of decoupling the information production from the information consumption. Similar techniques already exist, in particular to handle UI events, but I don't really see the same patterns applied to the logging problem. --- Edit: I accepted the answer from Marcelo because he points out at the factual evidence that a compromise is the best solution in this case, and there's no silver bullet. However, all the others were interesting answers as well, and I was really pleased to upvote all of them. Thanks for the help!
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I found [this](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) while searching for Aspect Oriented Programming for python. I agree with other posters that such concerns shouldn't be mixed with core logic. In essence,points where you want to put logging might not always be arbitary, may be concepts like "all the points before error" could be identified by a pointcut. Other totally arbitary points can be captured using simple logging techniques.
In response to your edit about information production/consumption: That's a valid concern for the general case, but logging is not the general case. In particular, you should not be relying on logging output from one part of your program to affect the execution of another part. That would indeed tightly couple the consumer to the implementation of the producer. Logging should be considered incidental to your main execution. Your systems should not know or care about the presence or contents of such log files (with the exception possibly of monitoring tools). That being the case, the notion of decoupling "consumption" of the logs from their production is inconsequential. Since you aren't using the logs to do anything meaningful, coupling is not an issue.
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really debug: just informative behavior of the application. A first, easy solution is to put prints ``` def doStuff(): print "starting doing stuff" print "I am starting to do step 1" doStep1() print "I did step 1" print "I am starting to do step 2" doStep2() print "I did step 2" print "I am starting to do step 3" doStep3() print "I did step 3" ``` In general, this is quite bad. Suppose that this code is going to end up in a library. I would not expect my library to print stuff out. I would expect it to do the job silently. Still, sometimes I would like to provide information, not only in debug situations, but also to keep the user informed that something is actually in the process of being done. Print is also bad because you don't have control of the handling of your messages. it just goes to stdout, and there's nothing you can do about it, except redirection. Another solution is to have a module for logging. ``` def doStuff(): Logging.log("starting doing stuff") Logging.log("I am starting to do step 1") doStep1() Logging.log("I did step 1") Logging.log("I am starting to do step 2") doStep2() Logging.log("I did step 2") Logging.log("I am starting to do step 3") doStep3() Logging.log("I did step 3") ``` This has the advantage that you sort of know a unique place for your logging service, and you can tinker this service as much as you want. You can silence it, redirect it onto a file, to stdout, or even to a network. Disadvantage is that you get a very strong coupling with the Logging module. Basically every part of your code depends on it, and you have calls to logging everywhere. The third option is to have a report object with a clear interface, and you pass it around ``` def doStuff(reporter=NullReporter()): reporter.log("starting doing stuff") reporter.log("I am starting to do step 1") doStep1() reporter.log("I did step 1") reporter.log("I am starting to do step 2") doStep2() reporter.log("I did step 2") reporter.log("I am starting to do step 3") doStep3() reporter.log("I did step 3") ``` Eventually, you can also pass the reporter object to doStepX() if they have more to say. Advantage: it reduces coupling with a module, but it introduces coupling with the instantiation of the NullReporter object. This can be solved by using None as default and checking before calling log, which is clumsy, because in python you have to write a conditional every time (in C you could define a macro) ``` def doStuff(reporter=None): if reporter is not None: reporter.log("starting doing stuff") # etc... ``` Edit: Another option is to work Qt-like, and have an emit() signal strategy. As your code executes, it emits information with proper status codes, and anyone interested can subscribe to the signals and provide info. Nice and clean, very decoupled, but requires a little of coding, as I don't think this can quickly be done with the python battery included. Finally, you can raise exceptions with a meaningful error message, but this of course can be used only if you are exiting from an error condition. it does not work for occasional reporting. Edit: I'd like to clarify the fact that the situation is more general, and not limited just to a sequence of invoked steps. it could also involve control structures: ``` if disconnected: print "Trying to connect" connect() else: print "obtaining list of files from remote host" getRemoteList() ``` The report could also be into the actual routines, so you would have a "print" in the connect() and getRemoteList() routines as a first statement. The question therefore are: * What do you think is the best design for some code (notably in the case of a library) to be at the same time silent when noise could be disruptive for the client, but verbose when useful? * How to handle a balanced intermix between logic code and reporting code ? * Intermixing between code and error checking has been solved with exceptions. What could be done to partition the "noise" of reporting from the code logic ? --- Edit: more thoughts for the mind I think it's not only a matter of decoupling the Logging code from the logic code. I think it's also a matter of decoupling the information production from the information consumption. Similar techniques already exist, in particular to handle UI events, but I don't really see the same patterns applied to the logging problem. --- Edit: I accepted the answer from Marcelo because he points out at the factual evidence that a compromise is the best solution in this case, and there's no silver bullet. However, all the others were interesting answers as well, and I was really pleased to upvote all of them. Thanks for the help!
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I think the best solution for a library is one along the lines of adding e.g. ``` Log.Write(...) ``` where the behavior of Log is picked up from the ambient environment (e.g. app.config or an environment variable). (I also think this is a problem that's been approached and solved many times, and while there are a few 'sweet spots' in the design space, the answer above is best IMO for the situation you describe.) I don't see any good way to 'decouple' the 'normal' part of your code from the 'logging' part. Logging tends to be relatively non-intrusive; I do not find the occasional Log.Write(...) to be a distraction to real-world code.
I would use the standard [`logging`](http://docs.python.org/library/logging.html) module that's been part of the standard library since Python 2.3. That way, there is a good chance that people looking at your code will already know how the `logging` module works. And if they have to learn then at least it's well-documented, and their knowledge is transferable to other libraries that also use `logging`. Is there any feature that you want but can't find in the standard `logging` module?
44,274,464
I've got a program that reads strings with special characters (used in spanish) from a file. I then use chdir to change to a directory which its name is the string. For example in a file called "names.txt" I got the following ``` Tableta Música . . etc ``` That file is encoded in utf-8 so that I read it from python as follows ``` f=open("names.txt","r",encoding="utf-8") names=f.readlines() f.close() ``` And it does read all successfully ``` print(names) ``` output: ``` ['Tableta\n','Música\n', ...etc] ``` Problem arises when I want to change to the first directory (the first name 'Tableta',without the newline character) ``` chdir(names[0][:-1]) ``` I get the following error > > FileNotFoundError: [WinError 2] The system cannot find the file specified: "\ufeffTableta" > > > And it does only happen with the first name, which was very odd to me. With other names it is able to change directories whether they have special characters or not I supposed it had to do something with the encoding, because of that '\ufeff' extra added character. So I changed the "names.txt" file to ANSI coding and deleted all the special characters so that I could read it with python, and it worked. But thing is that I need to have that file in utf-8 coding so that I can read special characters. Is there any way I can fix this? Why is python adding that '\ufeff' character to the string and only with the first name?
2017/05/31
[ "https://Stackoverflow.com/questions/44274464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7586576/" ]
Your file "names.txt" has a Byte-Order Mask (BOM). To remove it, open the file with the following decoder: ``` f = open("names.txt", encoding="utf-8-sig") ``` As a side note, it is safer to strip a file name: `names[0].strip()` instead of `names[0][:-1]`.
The beginning of your file has the unicode BOM. Skip first character when reading your file or open it with `utf-8-sig` encoding.
66,801,663
I have several database tables that I use in Django. Now I want to design everything around the database not in the Django ORM but in the rational style of my MySQL database. This includes multiple tables for different information. I have made a drawing of what I mean. I want the `createsuperuser` command to query once for the `user` table and once for the `residence` table. This could then look like this: ``` C:\Users\Project>python manage.py createsuperuser username: input firstname: input lastname: input password: ***** country: input city: input street: input ``` [![enter image description here](https://i.stack.imgur.com/iDyX8.png)](https://i.stack.imgur.com/iDyX8.png) Edit ==== Is there maybe a way to change the command?
2021/03/25
[ "https://Stackoverflow.com/questions/66801663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375016/" ]
<https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/#module-django.core.management> You can create django custom commands which will looks like: python manage.py createsuperuser2 (or similar name) ``` class Command(BaseCommand): def handle(self, *args, **options): username = input("username") .... (next params) user = User.objects.get_or_create(username=username, defaults={"blabla"} Residence.objects.create(user=user, next params....) ```
Just setup `REQUIRED_FIELDS` inside your User class. If you don't have custom user class, create `class User(AbstractUser)` but dont forget to set `AUTH_USER_MODEL = "users.User"` in `settings.py` ``` REQUIRED_FIELDS = ["country","city","street"] ```
1,738,494
I'm having a tough time getting the logging on Appengine working. the statement ``` import logging ``` is flagged as an unrecognized import in my PyDev Appengine project. I suspected that this was just an Eclipse issue, so I tried calling ``` logging.debug("My debug statement") ``` which does not print anything out on the dev\_appserver. I haven't seen anything here <http://code.google.com/appengine/docs/python/runtime.html#Logging> that is very helpful on the matter. Any advice is much appreciated.
2009/11/15
[ "https://Stackoverflow.com/questions/1738494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211584/" ]
The problem is most likely with the setup of the dev\_appserver. Try running it with the -d flag to turn on debugging.
I have experience only with the Java App Engine, but there they set things up to only log WARN and ERROR. Try using one of those and see if you start getting output! I'm sure there are ways to loosen the filter, but I wouldn't know how to do it in Python.
1,738,494
I'm having a tough time getting the logging on Appengine working. the statement ``` import logging ``` is flagged as an unrecognized import in my PyDev Appengine project. I suspected that this was just an Eclipse issue, so I tried calling ``` logging.debug("My debug statement") ``` which does not print anything out on the dev\_appserver. I haven't seen anything here <http://code.google.com/appengine/docs/python/runtime.html#Logging> that is very helpful on the matter. Any advice is much appreciated.
2009/11/15
[ "https://Stackoverflow.com/questions/1738494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211584/" ]
I have experience only with the Java App Engine, but there they set things up to only log WARN and ERROR. Try using one of those and see if you start getting output! I'm sure there are ways to loosen the filter, but I wouldn't know how to do it in Python.
Use the command option `--log_level` ``` $ dev_appserver.py --host 127.0.0.1 --log_level=debug . ```
1,738,494
I'm having a tough time getting the logging on Appengine working. the statement ``` import logging ``` is flagged as an unrecognized import in my PyDev Appengine project. I suspected that this was just an Eclipse issue, so I tried calling ``` logging.debug("My debug statement") ``` which does not print anything out on the dev\_appserver. I haven't seen anything here <http://code.google.com/appengine/docs/python/runtime.html#Logging> that is very helpful on the matter. Any advice is much appreciated.
2009/11/15
[ "https://Stackoverflow.com/questions/1738494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211584/" ]
The problem is most likely with the setup of the dev\_appserver. Try running it with the -d flag to turn on debugging.
Use the command option `--log_level` ``` $ dev_appserver.py --host 127.0.0.1 --log_level=debug . ```
50,546,740
I am using python 3.6.4 and pandas 0.23.0. I have referenced pandas 0.23.0 documentation for constructor and append. It does not mention anything about non-existent values. I didn't find any similar example. Consider following code: ``` import pandas as pd months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] index_yrs = [2016, 2017, 2018] r2016 = [26, 27, 25, 22, 20, 23, 22, 20, 20, 18, 18, 19] r2017 = [20, 21, 18, 16, 15, 15, 15, 15, 13, 13, 14, 15] r2018 = [16, 18, 18, 18, 17] df = pd.DataFrame([r2016], columns = months, index = [index_yrs[0]]) df = df.append(pd.DataFrame([r2017], columns = months, index = [index_yrs[1]])) ``` Now how to add r2018 which has data only till Month of May?
2018/05/26
[ "https://Stackoverflow.com/questions/50546740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4446712/" ]
I agree with RafaelC that padding your list for 2018 data with NaNs for missing values is the best way to do this. You can use `np.nan` from Numpy (which you will already have installed since you have Pandas) to generate NaNs. ``` import pandas as pd import numpy as np months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] index_yrs = [2016, 2017, 2018] ``` As a small change to your code I've put data for all three years into a `years` list which we can pass as the `data` parameter for pd.DataFrame. This eliminates the need to append each row to the previous ones. ``` r2016 = [26, 27, 25, 22, 20, 23, 22, 20, 20, 18, 18, 19] r2017 = [20, 21, 18, 16, 15, 15, 15, 15, 13, 13, 14, 15] r2018 = [16, 18, 18, 18, 17] years = [r2016] + [r2017] + [r2018] ``` This is what years looks like: [[26, 27, 25, 22, 20, 23, 22, 20, 20, 18, 18, 19], [20, 21, 18, 16, 15, 15, 15, 15, 13, 13, 14, 15], [16, 18, 18, 18, 17]]. As for padding your year 2018 with NaNs something like this might do the trick. We are just ensuring that if a year only has values for the first n months that the remaining months will be filled out with NaNs. ``` for year in years: if len(year) < 12: year.extend([np.nan] * (12 - len(year))) ``` Finally we can create your dataframe using the one liner below instead of appending row by row. ``` df = pd.DataFrame(years, columns=months, index=index_yrs).astype(float) ``` Output: ``` Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2016 26.0 27.0 25.0 22.0 20.0 23.0 22.0 20.0 20.0 18.0 18.0 19.0 2017 20.0 21.0 18.0 16.0 15.0 15.0 15.0 15.0 13.0 13.0 14.0 15.0 2018 16.0 18.0 18.0 18.0 17.0 NaN NaN NaN NaN NaN NaN NaN ``` You may notice that I converted the dtype of the values in the dataframe to float using `.astype(float)`. I did this to make all of your columns as the same dtype. If we don't call `.astype(float)` then Jan-May will be dtype `int` and Jun-Dec will be dtype `float64`.
You can add a row using `pd.DataFrame.loc` via a series. So you only need to convert your array into a `pd.Series` object before adding a row: ``` df.loc[index_yrs[2]] = pd.Series(r2018, index=df.columns[:len(r2018)]) print(df) Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2016 26.0 27.0 25.0 22.0 20.0 23.0 22.0 20.0 20.0 18.0 18.0 19.0 2017 20.0 21.0 18.0 16.0 15.0 15.0 15.0 15.0 13.0 13.0 14.0 15.0 2018 16.0 18.0 18.0 18.0 17.0 NaN NaN NaN NaN NaN NaN NaN ``` However, I strongly recommend you form a list of lists (with padding) before a single append. This is because `list.append`, or construction via a list comprehension, is cheap relative to repeated `pd.DataFrame.append` or `pd.DataFrame.loc`. The above solution is recommended if you absolutely must add one row at a time.
67,407,000
I have the below `string` as input: ``` 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' ``` I wrote function which convert it to `dictionary` using `python`: ``` def str_2_json(string): str_arr = string.split(',') #str_arr{0} = name SP2 #str_arr{1} = status Online json_data = {} for i in str_arr: #remove whitespaces stripped_str = " ".join(i.split()) # i.strip() subarray = stripped_str.split(' ') #subarray{0}=name #subarray{1}=SP2 key = subarray[0] #key: 'name' value = subarray[1] #value: 'SP2' json_data[key] = value #{dict 0}='name': SP2' #{dict 1}='status': online' return json_data ``` The `return` turns the `dictionary` into `json` (it has `jsonfiy`). Is there a simple/elegant way to do it better?
2021/05/05
[ "https://Stackoverflow.com/questions/67407000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14976099/" ]
Your approach is good, except for a couple weird things: * You aren't creating a *JSON* anything, so to avoid any confusion I suggest you don't name your returned dictionary `json_data` or your function `str_2_json`. JSON, or **J**ava**S**cript **O**bject **N**otation is just that -- a standard of denoting an object as text. The objects themselves have nothing to do with JSON. * You can use `i.strip()` instead of joining the splitted string (not sure why you did it this way, since you commented out `i.strip()`) * Some of your values contain multiple spaces (e.g. `"size 4764771 MB"` or `"disks /dev/sde /dev/sdf /dev/sdg"`). By your code, you end up everything after the second space in such strings. To avoid this, do `stripped_str.split(' ', 1)` which limits how many times you want to split the string. Other than that, you could create a dictionary in one line using the `dict()` constructor and a generator expression: ``` def str_2_dict(string): data = dict(item.strip().split(' ', 1) for item in string.split(',')) return data print(str_2_dict('name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0')) ``` Outputs: ``` { 'name': 'SP2', 'status': 'Online', 'size': '4764771 MB', 'free': '2576353 MB', 'path': '/dev/sde', 'log': '210 MB', 'port': '5660', 'guid': '7478a0141b7b9b0d005b30b0e60f3c4d', 'clusterUuid': '-8650609094877646407--116798096584060989', 'disks': '/dev/sde /dev/sdf /dev/sdg', 'dare': '0' } ``` This is probably the same (practically, in terms of efficiency / time) as writing out the full loop: ``` def str_2_dict(string): data = dict() for item in string.split(','): key, value = item.strip().split(' ', 1) data[key] = value return data ```
``` import json json_data = json.loads(string) ```
67,407,000
I have the below `string` as input: ``` 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' ``` I wrote function which convert it to `dictionary` using `python`: ``` def str_2_json(string): str_arr = string.split(',') #str_arr{0} = name SP2 #str_arr{1} = status Online json_data = {} for i in str_arr: #remove whitespaces stripped_str = " ".join(i.split()) # i.strip() subarray = stripped_str.split(' ') #subarray{0}=name #subarray{1}=SP2 key = subarray[0] #key: 'name' value = subarray[1] #value: 'SP2' json_data[key] = value #{dict 0}='name': SP2' #{dict 1}='status': online' return json_data ``` The `return` turns the `dictionary` into `json` (it has `jsonfiy`). Is there a simple/elegant way to do it better?
2021/05/05
[ "https://Stackoverflow.com/questions/67407000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14976099/" ]
Assuming these fields cannot contain internal commas, you can use `re.split` to both split and remove surrounding whitespace. It looks like you have different types of fields that should be handled differently. I've added a guess at a schema handler based on field names that can serve as a template for converting the various fields as needed. And as noted elsewhere, there is no json so don't use that name. ``` import re test = 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' def decode_data(string): str_arr = re.split(r"\s*,\s*", string) data = {} for entry in str_arr: values = re.split(r"\s+", entry) key = values.pop(0) # schema processing if key in ("disks"): # multivalue keys data[key] = values elif key in ("size", "free"): # convert to int bytes on 2nd value multiplier = {"MB":10**6, "MiB":2**20} # todo: expand as needed data[key] = int(values[0]) * multiplier[values[1]] else: data[key] = " ".join(values) return data decoded = decode_data(test) for kv in sorted(decoded.items()): print(kv) ```
``` import json json_data = json.loads(string) ```
67,407,000
I have the below `string` as input: ``` 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' ``` I wrote function which convert it to `dictionary` using `python`: ``` def str_2_json(string): str_arr = string.split(',') #str_arr{0} = name SP2 #str_arr{1} = status Online json_data = {} for i in str_arr: #remove whitespaces stripped_str = " ".join(i.split()) # i.strip() subarray = stripped_str.split(' ') #subarray{0}=name #subarray{1}=SP2 key = subarray[0] #key: 'name' value = subarray[1] #value: 'SP2' json_data[key] = value #{dict 0}='name': SP2' #{dict 1}='status': online' return json_data ``` The `return` turns the `dictionary` into `json` (it has `jsonfiy`). Is there a simple/elegant way to do it better?
2021/05/05
[ "https://Stackoverflow.com/questions/67407000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14976099/" ]
You can do this with regex ``` import re def parseString(s): dict(re.findall('(?:(\S+) ([^,]+)(?:, )?)', s)) sample = "name SP1, status Offline, size 4764771 MB, free 2406182 MB, path /dev/sdb, log 230 MB, port 5660, guid a48134c00cda2c37005b30b0e40e3ed6, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sdb /dev/sdc /dev/sdd, dare 0" parseString(sample) ``` Output: ``` {'name': 'SP1', 'status': 'Offline', 'size': '4764771 MB', 'free': '2406182 MB', 'path': '/dev/sdb', 'log': '230 MB', 'port': '5660', 'guid': 'a48134c00cda2c37005b30b0e40e3ed6', 'clusterUuid': '-8650609094877646407--116798096584060989', 'disks': '/dev/sdb /dev/sdc /dev/sdd', 'dare': '0'} ```
``` import json json_data = json.loads(string) ```
67,407,000
I have the below `string` as input: ``` 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' ``` I wrote function which convert it to `dictionary` using `python`: ``` def str_2_json(string): str_arr = string.split(',') #str_arr{0} = name SP2 #str_arr{1} = status Online json_data = {} for i in str_arr: #remove whitespaces stripped_str = " ".join(i.split()) # i.strip() subarray = stripped_str.split(' ') #subarray{0}=name #subarray{1}=SP2 key = subarray[0] #key: 'name' value = subarray[1] #value: 'SP2' json_data[key] = value #{dict 0}='name': SP2' #{dict 1}='status': online' return json_data ``` The `return` turns the `dictionary` into `json` (it has `jsonfiy`). Is there a simple/elegant way to do it better?
2021/05/05
[ "https://Stackoverflow.com/questions/67407000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14976099/" ]
Your approach is good, except for a couple weird things: * You aren't creating a *JSON* anything, so to avoid any confusion I suggest you don't name your returned dictionary `json_data` or your function `str_2_json`. JSON, or **J**ava**S**cript **O**bject **N**otation is just that -- a standard of denoting an object as text. The objects themselves have nothing to do with JSON. * You can use `i.strip()` instead of joining the splitted string (not sure why you did it this way, since you commented out `i.strip()`) * Some of your values contain multiple spaces (e.g. `"size 4764771 MB"` or `"disks /dev/sde /dev/sdf /dev/sdg"`). By your code, you end up everything after the second space in such strings. To avoid this, do `stripped_str.split(' ', 1)` which limits how many times you want to split the string. Other than that, you could create a dictionary in one line using the `dict()` constructor and a generator expression: ``` def str_2_dict(string): data = dict(item.strip().split(' ', 1) for item in string.split(',')) return data print(str_2_dict('name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0')) ``` Outputs: ``` { 'name': 'SP2', 'status': 'Online', 'size': '4764771 MB', 'free': '2576353 MB', 'path': '/dev/sde', 'log': '210 MB', 'port': '5660', 'guid': '7478a0141b7b9b0d005b30b0e60f3c4d', 'clusterUuid': '-8650609094877646407--116798096584060989', 'disks': '/dev/sde /dev/sdf /dev/sdg', 'dare': '0' } ``` This is probably the same (practically, in terms of efficiency / time) as writing out the full loop: ``` def str_2_dict(string): data = dict() for item in string.split(','): key, value = item.strip().split(' ', 1) data[key] = value return data ```
Assuming these fields cannot contain internal commas, you can use `re.split` to both split and remove surrounding whitespace. It looks like you have different types of fields that should be handled differently. I've added a guess at a schema handler based on field names that can serve as a template for converting the various fields as needed. And as noted elsewhere, there is no json so don't use that name. ``` import re test = 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' def decode_data(string): str_arr = re.split(r"\s*,\s*", string) data = {} for entry in str_arr: values = re.split(r"\s+", entry) key = values.pop(0) # schema processing if key in ("disks"): # multivalue keys data[key] = values elif key in ("size", "free"): # convert to int bytes on 2nd value multiplier = {"MB":10**6, "MiB":2**20} # todo: expand as needed data[key] = int(values[0]) * multiplier[values[1]] else: data[key] = " ".join(values) return data decoded = decode_data(test) for kv in sorted(decoded.items()): print(kv) ```
67,407,000
I have the below `string` as input: ``` 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' ``` I wrote function which convert it to `dictionary` using `python`: ``` def str_2_json(string): str_arr = string.split(',') #str_arr{0} = name SP2 #str_arr{1} = status Online json_data = {} for i in str_arr: #remove whitespaces stripped_str = " ".join(i.split()) # i.strip() subarray = stripped_str.split(' ') #subarray{0}=name #subarray{1}=SP2 key = subarray[0] #key: 'name' value = subarray[1] #value: 'SP2' json_data[key] = value #{dict 0}='name': SP2' #{dict 1}='status': online' return json_data ``` The `return` turns the `dictionary` into `json` (it has `jsonfiy`). Is there a simple/elegant way to do it better?
2021/05/05
[ "https://Stackoverflow.com/questions/67407000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14976099/" ]
You can do this with regex ``` import re def parseString(s): dict(re.findall('(?:(\S+) ([^,]+)(?:, )?)', s)) sample = "name SP1, status Offline, size 4764771 MB, free 2406182 MB, path /dev/sdb, log 230 MB, port 5660, guid a48134c00cda2c37005b30b0e40e3ed6, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sdb /dev/sdc /dev/sdd, dare 0" parseString(sample) ``` Output: ``` {'name': 'SP1', 'status': 'Offline', 'size': '4764771 MB', 'free': '2406182 MB', 'path': '/dev/sdb', 'log': '230 MB', 'port': '5660', 'guid': 'a48134c00cda2c37005b30b0e40e3ed6', 'clusterUuid': '-8650609094877646407--116798096584060989', 'disks': '/dev/sdb /dev/sdc /dev/sdd', 'dare': '0'} ```
Assuming these fields cannot contain internal commas, you can use `re.split` to both split and remove surrounding whitespace. It looks like you have different types of fields that should be handled differently. I've added a guess at a schema handler based on field names that can serve as a template for converting the various fields as needed. And as noted elsewhere, there is no json so don't use that name. ``` import re test = 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' def decode_data(string): str_arr = re.split(r"\s*,\s*", string) data = {} for entry in str_arr: values = re.split(r"\s+", entry) key = values.pop(0) # schema processing if key in ("disks"): # multivalue keys data[key] = values elif key in ("size", "free"): # convert to int bytes on 2nd value multiplier = {"MB":10**6, "MiB":2**20} # todo: expand as needed data[key] = int(values[0]) * multiplier[values[1]] else: data[key] = " ".join(values) return data decoded = decode_data(test) for kv in sorted(decoded.items()): print(kv) ```
55,120,078
Is there any way to add new records in the file with each field occupying specific size using python? As shown in below picture, there are together 8 columns `[column number:column bytes] ->[1:20,2:10,3:10,4:39, 6:2, 7:7,8:7]` each of different size. For example if first column value is of 20 bytes "ABBSBABBSBT ", this can contain either 10,5 or can occupy entire 20 bytes depending upon user input. In C language, we can specify the byte size during the variable initialization. How one can add new record with proper fixed spacing for each column? [![enter image description here](https://i.stack.imgur.com/2i9Ia.png)](https://i.stack.imgur.com/2i9Ia.png) Thank you in advance!
2019/03/12
[ "https://Stackoverflow.com/questions/55120078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11056039/" ]
When you use `ParseExact`, your string and format should match *exactly*. The proper format is: `ddd, d MMM yyyy hh:mm:ss zzz` (or `HH` which depends on your hour format) After you parse it, you need to use `ToString` to format it with `yyyy-MM-dd'T'hh:mm:ss` format (or `HH` which depends you want [12-hour clock](https://en.wikipedia.org/wiki/12-hour_clock) or [24-hour clock](https://en.wikipedia.org/wiki/24-hour_clock) format) I think I have to add little bit more explanation that a lot of people confuse (specially who are beginner about programming). A [`DateTime`](https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.7.2) instance does *not* have any format. It just have date and time values which is basicly a numeric value called [`Ticks`](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=netframework-4.7.2). When you talk about "format" concept, that points to *textual representation* which is `string`. Since you said "`Mon, 11 Mar 2019 09:13:16 +0100` to `2019-03-11T09:13:16`", I (and probably a lot of people also) assume that you have a string as `Mon, 11 Mar 2019 09:13:16 +0100` and you want to get `2019-03-11T09:13:16` as a string from it. For that, you need to parse your string to DateTime first. For that, as you do, `ParseExact` is one option. When you parse it to `DateTime`, you get it's *textual representation*, which is `string`, with `ToString` method. This method have a few overloads and you should use [`ToString(String, IFormatProvider)` overload](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=netframework-4.7.2#System_DateTime_ToString_System_String_System_IFormatProvider_). With that, you specify your output format as a first parameter, and your culture info as a second parameter which it *might* effect on your result string because of the `:` and `/` format specifiers since they can change based on the current culture or supplied culture. Further reading: [Custom Date and Time Format Strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings)
You need to specify the format that the input data has (the second parameter of `DateTime.ParseExact`). In your case, the data you provide has the format `ddd, d MMM yyyy hh:mm:ss zzz`. Also, in the last line, where you print the result you have to format it. So, this is how you have to do it: ``` string dataa = "Mon, 11 Mar 2019 09:13:16 +0100"; DateTime d = new DateTime(); d = DateTime.ParseExact(dataa, "ddd, d MMM yyyy hh:mm:ss zzz", System.Globalization.CultureInfo.InvariantCulture); Console.WriteLine("data: " + d.ToString("yyyy-MM-dd'T'hh:mm:ss")); ```
61,396,228
How can I convert small float values such as *1.942890293094024e-15* or *2.8665157186802404e-07* to binary values in Python? I tried [GeeksforGeek's solution](https://www.geeksforgeeks.org/python-program-to-convert-floating-to-binary/), however, it does not work for values this small (I get this error: **ValueError: invalid literal for int() with base 10: '1.942890293094024e-15'**). The code looks like this so far: ``` def float_bin(number, places = 3): # split() seperates whole number and decimal # part and stores it in two seperate variables whole, dec = str(number).split(".") # Convert both whole number and decimal # part from string type to integer type whole = int(whole) dec = int (dec) # Convert the whole number part to it's # respective binary form and remove the # "0b" from it. res = bin(whole).lstrip("0b") + "." # Iterate the number of times, we want # the number of decimal places to be for x in range(places): # Multiply the decimal value by 2 # and seperate the whole number part # and decimal part whole, dec = str((decimal_converter(dec)) * 2).split(".") # Convert the decimal part # to integer again dec = int(dec) # Keep adding the integer parts # receive to the result variable res += whole return res # Function converts the value passed as # parameter to it's decimal representation def decimal_converter(num): while num > 1: num /= 10 return num ```
2020/04/23
[ "https://Stackoverflow.com/questions/61396228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281273/" ]
After some consultation, I found a good [piece of code](https://trinket.io/python3/8934ea47a2) that solves my problem. I just had to apply some little tweaks on it (making it a function, removing automatic input requests etc.). Huge thanks to @kartoon!
One problem I see is with `str(number).split(".")`. I've added a simple hack before that: `number = "{:30f}".format(number)` so that there is no `e` in number. Though, I'm not sure if the result is correct.
14,582,773
my problem is how to best release memory the response of an asynchrones url fetch needs on appengine. Here is what I basically do in python: ``` rpcs = [] for event in event_list: url = 'http://someurl.com' rpc = urlfetch.create_rpc() rpc.callback = create_callback(rpc) urlfetch.make_fetch_call(rpc, url) rpcs.append(rpc) for rpc in rpcs: rpc.wait() ``` In my test scenario it does that for 1500 request. But I need an architecture to handle even much more within a short amount of time. Then there is a callback function, which adds a task to a queue to process the results: ``` def event_callback(rpc): result = rpc.get_result() data = json.loads(result.content) taskqueue.add(queue_name='name', url='url', params={'data': data}) ``` My problem is, that I do so many concurrent RPC calls, that the memory of my instance crashes: **"Exceeded soft private memory limit with 159.234 MB after servicing 975 requests total"** I already tried three things: ``` del result del data ``` and ``` result = None data = None ``` and I ran the garbage collector manually after the callback function. ``` gc.collect() ``` But nothing seem to release the memory directly after a callback functions has added the task to a queue - and therefore the instance crashes. Is there any other way to do it?
2013/01/29
[ "https://Stackoverflow.com/questions/14582773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471612/" ]
Wrong approach: Put these urls into a (put)-queue, increase its rate to the desired value (defaut: 5/sec), and let each task handle one url-fetch (or a group hereof). Please note that theres a safety limit of 3000 url-fetch-api-calls / minute (and one url-fetch might use more than one api-call)
Use the task queue for urlfetch as well, fan out and avoid exhausting memory, register named tasks and provide the event\_list cursor to next task. You might want to fetch+process in such a scenario instead of registering new task for every process, especially if process also includes datastore writes. I also find ndb to make these async solutions more elegant. Check out Brett Slatkins talk on [scalable apps](http://www.google.com/events/io/2009/sessions/BuildingScalableComplexApps.html) and perhaps [pipelines](http://www.youtube.com/watch?v=zSDC_TU7rtc).
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[::2]+1 ``` and also: ``` for x in list1: x=2 list2 = list1[::x] + 1 ```
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1, len(list1), 2): list1[i] +=1 print(list1) ``` using i%2 seems not very efficient
Try this: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1,len(list1),2): list1[i] += 1 ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[::2]+1 ``` and also: ``` for x in list1: x=2 list2 = list1[::x] + 1 ```
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
[`numpy`](http://www.numpy.org/) allows you to use `+=` operation with slices too: ``` In [15]: import numpy as np In [16]: l = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) In [17]: l[1::2] += 1 In [18]: l Out[18]: array([ 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]) ```
``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1, len(list1), 2): list1[i] +=1 print(list1) ``` using i%2 seems not very efficient
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[::2]+1 ``` and also: ``` for x in list1: x=2 list2 = list1[::x] + 1 ```
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
[`numpy`](http://www.numpy.org/) allows you to use `+=` operation with slices too: ``` In [15]: import numpy as np In [16]: l = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) In [17]: l[1::2] += 1 In [18]: l Out[18]: array([ 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]) ```
``` a = [i for i in range(1,11)] #a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = [a[i]+1 if i%2==1 else a[i] for i in range(len(a))] #b = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[::2]+1 ``` and also: ``` for x in list1: x=2 list2 = list1[::x] + 1 ```
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1, len(list1), 2): list1[i] +=1 print(list1) ``` using i%2 seems not very efficient
``` a = [i for i in range(1,11)] #a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = [a[i]+1 if i%2==1 else a[i] for i in range(len(a))] #b = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[::2]+1 ``` and also: ``` for x in list1: x=2 list2 = list1[::x] + 1 ```
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
Use [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) and a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) ``` >>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [v+1 if i%2!=0 else v for i,v in enumerate(list1)] [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ```
``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1, len(list1), 2): list1[i] +=1 print(list1) ``` using i%2 seems not very efficient
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[::2]+1 ``` and also: ``` for x in list1: x=2 list2 = list1[::x] + 1 ```
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1, len(list1), 2): list1[i] +=1 print(list1) ``` using i%2 seems not very efficient
You can create an iterator representing the delta (`itertools.cycle([0, 1])` and then add its elements to your existing list. ``` >>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [a + b for a,b in zip(list1, itertools.cycle([0,1]))] [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] >>> ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[::2]+1 ``` and also: ``` for x in list1: x=2 list2 = list1[::x] + 1 ```
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
You could use `slicing` with a list comprehension as follows: ``` In [26]: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [27]: list1[1::2] = [x+1 for x in list1[1::2]] In [28]: list1 Out[28]: [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ```
[`numpy`](http://www.numpy.org/) allows you to use `+=` operation with slices too: ``` In [15]: import numpy as np In [16]: l = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) In [17]: l[1::2] += 1 In [18]: l Out[18]: array([ 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]) ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[::2]+1 ``` and also: ``` for x in list1: x=2 list2 = list1[::x] + 1 ```
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
Use [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) and a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) ``` >>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [v+1 if i%2!=0 else v for i,v in enumerate(list1)] [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ```
Try this: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1,len(list1),2): list1[i] += 1 ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[::2]+1 ``` and also: ``` for x in list1: x=2 list2 = list1[::x] + 1 ```
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
You could use `slicing` with a list comprehension as follows: ``` In [26]: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [27]: list1[1::2] = [x+1 for x in list1[1::2]] In [28]: list1 Out[28]: [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ```
You can create an iterator representing the delta (`itertools.cycle([0, 1])` and then add its elements to your existing list. ``` >>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [a + b for a,b in zip(list1, itertools.cycle([0,1]))] [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] >>> ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[::2]+1 ``` and also: ``` for x in list1: x=2 list2 = list1[::x] + 1 ```
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
[`numpy`](http://www.numpy.org/) allows you to use `+=` operation with slices too: ``` In [15]: import numpy as np In [16]: l = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) In [17]: l[1::2] += 1 In [18]: l Out[18]: array([ 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]) ```
Try this: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1,len(list1),2): list1[i] += 1 ```
19,378,869
``` Error occurred during initialization of VM. Could not reserve enough space for object heap. Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit. ``` The bat file has the following command: ``` java -cp stanford-corenlp-3.2.0.jar;stanford-corenlp-3.2.0-models.jar;xom.jar;joda-time.jar;jollyday.jar -Xmx3g edu.stanford.nlp.pipeline.StanfordCoreNLP -props props.properties -filelist filelist.txt ``` It works from the cmd window with no errors! I have the following python code: ``` import os import subprocess os.chdir('C:/Users/Christos/Documents/stanford-corenlp-full-2013-06-20/') p = subprocess.Popen(r'start cmd /c run_mouskos.bat', shell=True) p.wait() print 'done' ``` I have also tried various other ways for executing the bat file from python with no luck. How can i run it with no errors?
2013/10/15
[ "https://Stackoverflow.com/questions/19378869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2120596/" ]
I've recently had this issue. I'm running a Django application, which is served by uWSGI. I'm actually running uWSGI processes with as-limit argument set to 512MB. After digging around this, I've discovered that every process which the application runs using subprocess, will keep same OS limits as uWSGI processes. After increasing the value of as-limit to 1GB, i was not able to reproduce this issue. Maybe this could help you
Try setting the heap size explicitly: see [Could not reserve enough space for object heap](https://stackoverflow.com/questions/4401396/could-not-reserve-enough-space-for-object-heap) This setting can be also be affected by environment variables - you should print the variables in the batch file (I think the `set` command on Windows does this). This would allow you to see if the variables are the same in the two cases you've tried. Of course, you'll need to capture the output from the batch script (or make it otherwise visible) in order to perform the comparison.
71,586,428
I want to find a concise way to sample n consecutive elements with stride m from a numpy array. The simplest case is with sampling 1 element with stride 2, which means getting every other element in a list, which can be done like this: ``` >>> a = np.arange(10) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> a[::2] array([0, 2, 4, 6, 8]) ``` However, what if I wanted to slice n consecutive elements with a stride of m where n and m can be any integers? For example, if I wanted to slice 2 consecutive elements with a stride of 3 I would get something like this: ``` array([0, 1, 3, 4, 6, 7, 9]) ``` Is there a pythonic and concise way of doing this? Thank you!
2022/03/23
[ "https://Stackoverflow.com/questions/71586428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9079872/" ]
If `a` is long enough you could reshape, slice, and ravel ``` a.reshape(-1,3)[:,:2].ravel() ``` But `a` has to be (9,) or (12,). And the result will still be a copy. The suggested: ``` np.lib.stride_tricks.as_strided(a, (4,2), (8*3, 8)).ravel()[:-1] ``` is also a copy. The `as_strided` part is a view, but `ravel` will make a copy. And there is the ugliness of that extra element. `sliding_window_view` was added as a safer version: ``` In [81]: np.lib.stride_tricks.sliding_window_view(a,(3)) Out[81]: array([[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9]]) In [82]: np.lib.stride_tricks.sliding_window_view(a,(3))[::3,:2] Out[82]: array([[0, 1], [3, 4], [6, 7]]) ``` Again `ravel` will make a copy. This omits the "extra" `9`. `np.resize` does a `reshape` with padding (repeating `a` as needed): ``` In [83]: np.resize(a, (4,3)) Out[83]: array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 0, 1]]) In [84]: np.resize(a, (4,3))[:,:2] Out[84]: array([[0, 1], [3, 4], [6, 7], [9, 0]]) ```
This code might be useful, I tested it on the example in the question (n=2, m=3) ``` import numpy as np def get_slice(arr, n, m): b = np.array([]) for i in range(0, len(arr), m): b = np.concatenate((b, arr[i:i + n])) return b sliced_arr = get_slice(np.arange(10), n=2, m=3) print(sliced_arr) ``` Output ``` [0. 1. 3. 4. 6. 7. 9.] ```
63,348,785
I'm new and trying to follow this tutorial: <https://www.youtube.com/watch?v=_uQrJ0TkZlc> from 05:00:00 I follow him just like he doing, then at 05:05:04 when he run the server it's work fine for him, but for me is not. This is exactly my steps.... After Install django like this: ``` pip install django ``` I write this: ``` django-admin startproject pyshop . ``` so far all good, no error, then I try to run the server like this: ``` python manage.py runserver ``` But then I get a big error: ``` Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x000001D36DA79AF0> Traceback (most recent call last): File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\db\models\base.py", line 101, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\db\models\base.py", line 304, in add_to_class value.contribute_to_class(cls, name) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\db\models\options.py", line 203, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\db\__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\db\utils.py", line 202, in __getitem__ backend = load_backend(db['ENGINE']) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\db\utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "C:\Users\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 10, in <module> from sqlite3 import dbapi2 as Database File "C:\Users\anaconda3\lib\sqlite3\__init__.py", line 23, in <module> from sqlite3.dbapi2 import * File "C:\Users\anaconda3\lib\sqlite3\dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: DLL load failed while importing _sqlite3: The specified module could not be found. ``` Help :(
2020/08/10
[ "https://Stackoverflow.com/questions/63348785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14068193/" ]
The 2nd approach doesn't require you to have recording rules for every possible interval over which you'd like an average rate, saving resources.
The `avg_over_time(rate(metric_total[5m])[$__interval:])` calculates average of average rates. This isn't a good metric, since [average of averages doesn't equal to average](https://math.stackexchange.com/questions/95909/why-is-an-average-of-an-average-usually-incorrect). So the better approach would be to calculate `rate(metric_total[$__interval])` - it returns the real average per-second increase rate for `metric_total` over the given lookbehind window `$__interval`.
22,204,801
I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output). e.g. ``` ./program A # output FALSE ./program AA # output FALSE ./program AAA # output FALSE ./program AAAA # output FALSE ./program AAAAA # output FALSE ./program AAAAAA # output FALSE ./program AAAAAAA # output TRUE ``` in C I would simply use a **while** loop. I know in python there is the **while** loop as well. So the python program would be: ``` strlen = 0 while TRUE strlen++ <run ./**C program** "A"*strlen > if (<program_output> = TRUE) break ``` Given that I can make the .py script executable by writing ``` #! /usr/bin/env python ``` and ``` chmod +x file.py ``` What should I do to make this work? Thanks in advance
2014/03/05
[ "https://Stackoverflow.com/questions/22204801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219368/" ]
You could try something like this (see [docs](http://docs.python.org/2/library/subprocess.html#subprocess.call)): ``` import subprocess args = "" while True: args += "A" result = subprocess.call(["./program", "{args}".format(args=args)]) if result == 'TRUE': break ``` The `subprocess` module is preferred to the `os.popen` command, since it has been "deprecated since version 2.6." See the [os documentation](http://docs.python.org/2/library/os.html#os.popen).
**file.py** ``` import os count=10 input="A" for i in range(0, count): input_args=input_args+input_args os.popen("./program "+input_args) ``` running **file.py** would execute **./program** 10 times with increasing `A` input
22,204,801
I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output). e.g. ``` ./program A # output FALSE ./program AA # output FALSE ./program AAA # output FALSE ./program AAAA # output FALSE ./program AAAAA # output FALSE ./program AAAAAA # output FALSE ./program AAAAAAA # output TRUE ``` in C I would simply use a **while** loop. I know in python there is the **while** loop as well. So the python program would be: ``` strlen = 0 while TRUE strlen++ <run ./**C program** "A"*strlen > if (<program_output> = TRUE) break ``` Given that I can make the .py script executable by writing ``` #! /usr/bin/env python ``` and ``` chmod +x file.py ``` What should I do to make this work? Thanks in advance
2014/03/05
[ "https://Stackoverflow.com/questions/22204801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219368/" ]
You can use [subprocess.check\_output](http://docs.python.org/3/library/subprocess.html#subprocess.check_output): ``` import subprocess strlen = 0 while True: strlen += 1 if subprocess.check_output(['./program', 'A'*strlen]) == 'TRUE': break ```
**file.py** ``` import os count=10 input="A" for i in range(0, count): input_args=input_args+input_args os.popen("./program "+input_args) ``` running **file.py** would execute **./program** 10 times with increasing `A` input
22,204,801
I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output). e.g. ``` ./program A # output FALSE ./program AA # output FALSE ./program AAA # output FALSE ./program AAAA # output FALSE ./program AAAAA # output FALSE ./program AAAAAA # output FALSE ./program AAAAAAA # output TRUE ``` in C I would simply use a **while** loop. I know in python there is the **while** loop as well. So the python program would be: ``` strlen = 0 while TRUE strlen++ <run ./**C program** "A"*strlen > if (<program_output> = TRUE) break ``` Given that I can make the .py script executable by writing ``` #! /usr/bin/env python ``` and ``` chmod +x file.py ``` What should I do to make this work? Thanks in advance
2014/03/05
[ "https://Stackoverflow.com/questions/22204801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219368/" ]
You could try something like this (see [docs](http://docs.python.org/2/library/subprocess.html#subprocess.call)): ``` import subprocess args = "" while True: args += "A" result = subprocess.call(["./program", "{args}".format(args=args)]) if result == 'TRUE': break ``` The `subprocess` module is preferred to the `os.popen` command, since it has been "deprecated since version 2.6." See the [os documentation](http://docs.python.org/2/library/os.html#os.popen).
You can use [subprocess.check\_output](http://docs.python.org/3/library/subprocess.html#subprocess.check_output): ``` import subprocess strlen = 0 while True: strlen += 1 if subprocess.check_output(['./program', 'A'*strlen]) == 'TRUE': break ```
22,204,801
I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output). e.g. ``` ./program A # output FALSE ./program AA # output FALSE ./program AAA # output FALSE ./program AAAA # output FALSE ./program AAAAA # output FALSE ./program AAAAAA # output FALSE ./program AAAAAAA # output TRUE ``` in C I would simply use a **while** loop. I know in python there is the **while** loop as well. So the python program would be: ``` strlen = 0 while TRUE strlen++ <run ./**C program** "A"*strlen > if (<program_output> = TRUE) break ``` Given that I can make the .py script executable by writing ``` #! /usr/bin/env python ``` and ``` chmod +x file.py ``` What should I do to make this work? Thanks in advance
2014/03/05
[ "https://Stackoverflow.com/questions/22204801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219368/" ]
You could try something like this (see [docs](http://docs.python.org/2/library/subprocess.html#subprocess.call)): ``` import subprocess args = "" while True: args += "A" result = subprocess.call(["./program", "{args}".format(args=args)]) if result == 'TRUE': break ``` The `subprocess` module is preferred to the `os.popen` command, since it has been "deprecated since version 2.6." See the [os documentation](http://docs.python.org/2/library/os.html#os.popen).
Use `commands`. Here is the documentation `http://docs.python.org/2/library/commands.html` 1. `commands.getstatusoutput` returns a stdout output from your C program. So, if your program prints something, use that. (In fact, it returns a tuple (0, out) for stdout). 2. `commands.getstatus` returns boolean status from program which you can use as well. So, assuming you are using stdout to capture the `./program` output, the entire modified program looks like ``` import commands while TRUE: strlen += 1 output = commands.getstatusoutput("./program " + "A"*strlen) outstatus = output[1] if output == "true": break ``` I would experiment with `getstatus` to see if I can read values returned by `program`. **Edit:** Didn't notice that `commands` is deprecated since 2.6 Please use `subprocess` as shown in other response.
22,204,801
I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output). e.g. ``` ./program A # output FALSE ./program AA # output FALSE ./program AAA # output FALSE ./program AAAA # output FALSE ./program AAAAA # output FALSE ./program AAAAAA # output FALSE ./program AAAAAAA # output TRUE ``` in C I would simply use a **while** loop. I know in python there is the **while** loop as well. So the python program would be: ``` strlen = 0 while TRUE strlen++ <run ./**C program** "A"*strlen > if (<program_output> = TRUE) break ``` Given that I can make the .py script executable by writing ``` #! /usr/bin/env python ``` and ``` chmod +x file.py ``` What should I do to make this work? Thanks in advance
2014/03/05
[ "https://Stackoverflow.com/questions/22204801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219368/" ]
You can use [subprocess.check\_output](http://docs.python.org/3/library/subprocess.html#subprocess.check_output): ``` import subprocess strlen = 0 while True: strlen += 1 if subprocess.check_output(['./program', 'A'*strlen]) == 'TRUE': break ```
Use `commands`. Here is the documentation `http://docs.python.org/2/library/commands.html` 1. `commands.getstatusoutput` returns a stdout output from your C program. So, if your program prints something, use that. (In fact, it returns a tuple (0, out) for stdout). 2. `commands.getstatus` returns boolean status from program which you can use as well. So, assuming you are using stdout to capture the `./program` output, the entire modified program looks like ``` import commands while TRUE: strlen += 1 output = commands.getstatusoutput("./program " + "A"*strlen) outstatus = output[1] if output == "true": break ``` I would experiment with `getstatus` to see if I can read values returned by `program`. **Edit:** Didn't notice that `commands` is deprecated since 2.6 Please use `subprocess` as shown in other response.
48,783,650
I have a python list l.The first few elements of the list looks like below ``` [751883787] [751026090] [752575831] [751031278] [751032392] [751027358] [751052118] ``` I want to convert this list to pandas.core.series.Series with 2 leading 0.My final outcome will look like ``` 00751883787 00751026090 00752575831 00751031278 00751032392 00751027358 00751052118 ``` I'm working in Python 3.x in windows environment.Can you suggest me how to do this? Also my list contains around 2000000 elements
2018/02/14
[ "https://Stackoverflow.com/questions/48783650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9300211/" ]
you can try: ``` list=[121,123,125,145] series='00'+pd.Series(list).astype(str) print(series) ``` output: ``` 0 00121 1 00123 2 00125 3 00145 dtype: object ```
This is one way. ``` from itertools import chain; concat = chain.from_iterable import pandas as pd lst = [[751883787], [751026090], [752575831], [751031278]] pd.DataFrame({'a': pd.Series([str(i).zfill(11) for i in concat(lst)])}) a 0 00751883787 1 00751026090 2 00752575831 3 00751031278 ``` Some benchmarking, relevant since your dataframe is large: ``` from itertools import chain; concat = chain.from_iterable import pandas as pd lst = [[751883787], [751026090], [752575831], [751031278], [751032392], [751027358], [751052118]]*300000 %timeit pd.DataFrame(lst, columns=['a'])['a'].astype(str).str.zfill(11) # 1 loop, best of 3: 7.88 s per loop %timeit pd.DataFrame({'a': pd.Series([str(i).zfill(11) for i in concat(lst)])}) # 1 loop, best of 3: 2.06 s per loop ```
48,783,650
I have a python list l.The first few elements of the list looks like below ``` [751883787] [751026090] [752575831] [751031278] [751032392] [751027358] [751052118] ``` I want to convert this list to pandas.core.series.Series with 2 leading 0.My final outcome will look like ``` 00751883787 00751026090 00752575831 00751031278 00751032392 00751027358 00751052118 ``` I'm working in Python 3.x in windows environment.Can you suggest me how to do this? Also my list contains around 2000000 elements
2018/02/14
[ "https://Stackoverflow.com/questions/48783650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9300211/" ]
you can try: ``` list=[121,123,125,145] series='00'+pd.Series(list).astype(str) print(series) ``` output: ``` 0 00121 1 00123 2 00125 3 00145 dtype: object ```
First use `DataFrame` constructor with columns, then cast to `string` and last add `0` by [`Series.str.zfill`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.zfill.html) if nested `list`s: ``` lst = [[751883787], [751026090], [752575831], [751031278], [751032392], [751027358], [751052118]] s = pd.DataFrame(lst, columns=['a'])['a'].astype(str).str.zfill(11) print (s) 0 00751883787 1 00751026090 2 00752575831 3 00751031278 4 00751032392 5 00751027358 6 00751052118 Name: a, dtype: object ``` --- If there is one `list` only: ``` lst = [751883787, 751026090, 752575831, 751031278, 751032392, 751027358, 751052118] s = pd.Series(lst).astype(str).str.zfill(11) print (s) 0 00751883787 1 00751026090 2 00752575831 3 00751031278 4 00751032392 5 00751027358 6 00751052118 dtype: object ```