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
6,091,688
I have a Tkinter program and running it like: `python myWindow.py` starts it all right, but the window is behind the terminal that I use to start it. Is there a way to make it grab the focus and be the foreground application? Does it depend on the platform?
2011/05/23
[ "https://Stackoverflow.com/questions/6091688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175461/" ]
This might be a feature of your particular window manager. One thing to try is for your app to call `focus_force` at startup, after all the widgets have been created.
Have you tried this at the end of your script ? ``` root.iconify() root.update() root.deiconify() root.mainloop() ```
6,091,688
I have a Tkinter program and running it like: `python myWindow.py` starts it all right, but the window is behind the terminal that I use to start it. Is there a way to make it grab the focus and be the foreground application? Does it depend on the platform?
2011/05/23
[ "https://Stackoverflow.com/questions/6091688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175461/" ]
This might be a feature of your particular window manager. One thing to try is for your app to call `focus_force` at startup, after all the widgets have been created.
Somewhat of a combination of various other methods found online, this works on OS X 10.11, and Python 3.5.1 running in a venv, and should work on other platforms too. On OS X, it also targets the app by process id rather than app name. ``` from tkinter import Tk import os import subprocess import platform def raise_a...
68,230,917
this is what I did. The code is down bellow. I have the music.csv dataset. The error is Found input variables with inconsistent numbers of samples: [4, 1]. The error details is after the code. ```py # importing Data import pandas as pd music_data = pd.read_csv('music.csv') music_data # split into training and testin...
2021/07/02
[ "https://Stackoverflow.com/questions/68230917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14672478/" ]
I don't have your tables so I'll demonstrate it on Scott's EMP. ``` SQL> select empno, ename, to_char(hiredate, 'dd.mm.yyyy, dy') hiredate 2 from emp 3 where to_char(hiredate, 'dy', 'nls_date_language = english') in ('sat', 'sun'); EMPNO ENAME HIREDATE ---------- ---------- ------------------------ ...
You may use ISO week as a starting point, which is culture independent: ``` select * from your_table where trunc(created_date) - trunc(created_date, 'IW') in (5,6) ``` ISO week starts on Monday.
68,230,917
this is what I did. The code is down bellow. I have the music.csv dataset. The error is Found input variables with inconsistent numbers of samples: [4, 1]. The error details is after the code. ```py # importing Data import pandas as pd music_data = pd.read_csv('music.csv') music_data # split into training and testin...
2021/07/02
[ "https://Stackoverflow.com/questions/68230917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14672478/" ]
I don't have your tables so I'll demonstrate it on Scott's EMP. ``` SQL> select empno, ename, to_char(hiredate, 'dd.mm.yyyy, dy') hiredate 2 from emp 3 where to_char(hiredate, 'dy', 'nls_date_language = english') in ('sat', 'sun'); EMPNO ENAME HIREDATE ---------- ---------- ------------------------ ...
``` select to_char(sysdate, 'DAY') full_name, to_char(sysdate, 'DY') abbreviation, to_char(sysdate, 'D') day_of_week from dual ```
68,230,917
this is what I did. The code is down bellow. I have the music.csv dataset. The error is Found input variables with inconsistent numbers of samples: [4, 1]. The error details is after the code. ```py # importing Data import pandas as pd music_data = pd.read_csv('music.csv') music_data # split into training and testin...
2021/07/02
[ "https://Stackoverflow.com/questions/68230917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14672478/" ]
You may use ISO week as a starting point, which is culture independent: ``` select * from your_table where trunc(created_date) - trunc(created_date, 'IW') in (5,6) ``` ISO week starts on Monday.
``` select to_char(sysdate, 'DAY') full_name, to_char(sysdate, 'DY') abbreviation, to_char(sysdate, 'D') day_of_week from dual ```
32,016,428
I'm getting following error while running the script and the script is to get the SPF records for a list of domains from a file and i'm not sure about the error,Can any one please help me on this issue ? ``` #!/usr/bin/python import sys import socket import dns.resolver import re def getspf (domain): answers = d...
2015/08/14
[ "https://Stackoverflow.com/questions/32016428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5093018/" ]
`domain` is a list, not a string. You want to pass *elements* of `domain` to `getspf`, not the entire list. ``` f=open('Input_Domains.txt','r') a=f.readlines() domain=a print domain x=0 while x<len(domain): # domain[x], not domain full_spf=getspf(domain[x]) print 'Initial SPF string : ', full_s...
When you run `getspf (domain)`, `domain` is the whole list of domains in your file. Instead of ``` f=open('Input_Domains.txt','r') a=f.readlines() domain=a print domain x=0 while x<len(domain): full_spf=getspf(domain) print 'Initial SPF string : ', full_spf x=x+1 f.close() ``` do ``` with open('Input_D...
56,026,352
I created a Django (v. 2.1.5) model called Metric that has itself as an embed model, as you can see below: ```py from djongo import models class Metric(models.Model): _id = models.ObjectIdField() ... dependencies = models.ArrayModelField( model_container='Metric', blank=True, ) def...
2019/05/07
[ "https://Stackoverflow.com/questions/56026352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11465606/" ]
You can create this filter: ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.http.HttpHeaders; import org.springframework.htt...
This [sample](https://github.com/spring-cloud-samples/sample-gateway-oauth2login) shows how to set up Spring Cloud Gateway with Spring Security OAuth2.
34,841,822
I have coded a Python Script for Twitter Automation using Tweepy. Now, when i run on my own Linux Machine as `python file.py` The file runs successfully and it keeps on running because i have specified repeated Tasks inside the Script and I also don't want to stop the script either. But as it is on my Local Machine, th...
2016/01/17
[ "https://Stackoverflow.com/questions/34841822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5676841/" ]
I have installed it from github with the command `bower install [email protected]:angular/angular.git`: ``` $ bower install [email protected]:angular/angular.git bower angular#* not-cached [email protected]:angular/angular.git#* bower angular#* resolve [email protected]:angular/angular.git#* bower angu...
I advise you not to use Bower. Bower is used to get your packages in your project folder, that's it. Try to look up JSPM (<http://jspm.io>). It does a lot more than getting packages in your project. It takes care of ES6 to ES5. And loads all your packages in one time using SystemJS in your browser with just a couple l...
34,841,822
I have coded a Python Script for Twitter Automation using Tweepy. Now, when i run on my own Linux Machine as `python file.py` The file runs successfully and it keeps on running because i have specified repeated Tasks inside the Script and I also don't want to stop the script either. But as it is on my Local Machine, th...
2016/01/17
[ "https://Stackoverflow.com/questions/34841822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5676841/" ]
I have installed it from github with the command `bower install [email protected]:angular/angular.git`: ``` $ bower install [email protected]:angular/angular.git bower angular#* not-cached [email protected]:angular/angular.git#* bower angular#* resolve [email protected]:angular/angular.git#* bower angu...
This worked for me, for Angular 2 `bower install angular2-build`
23,952,821
I am making a dabian binary package for local use. `dpkg-buildpackage -rfakeroot` is failed due to below error. ``` find /home/dwft78/project/CoreScanner/cscore-1.0/lib -name "libcs*" -type f -exec cp -f {} /home/dwft78/project/CoreScanner/cscore-1.0/debian/cscore/opt/motorola-scanner//bin \; find /home/dwft78/project...
2014/05/30
[ "https://Stackoverflow.com/questions/23952821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3458841/" ]
Something like that could just do the trick: ``` #!/usr/bin/make -f export DH_COMPAT=5 # though I don't know what for... %: dh $@ override_dh_shlibdeps: dh_shlibdeps -l$(shell pwd)/lib/Linux/$(DEB_BUILD_GNU_CPU) ``` **Edit** I just remembered there was an option to dh\_shlibdeps which even [got attention...
how about just exporting `LD_LIBRARY_PATH` in `debian/rules`? ``` #!/usr/bin/make -f export LD_LIBRARY_PATH=$(shell pwd)/lib/Linux/$(DEB_BUILD_GNU_CPU) %: dh $@ ``` note ---- i'm using `$(DEB_BUILD_GNU_CPU)` here to calculate the value of *x86\_64*. this might give the correct result (it will return *i38...
21,500,062
Hi I'm new in programming and in python and I have an assignment that I can't complete. I have to write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns. I have used this code so far: ``` num...
2014/02/01
[ "https://Stackoverflow.com/questions/21500062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3260697/" ]
``` col=0 #add this line while count < int(numprimes): if primetest(potentialprime) == True: print "%5d"%potentialprime, #and this line col += 1 #and this block if col==5: # print "\n" # col=0 # count += 1 potentialp...
Add a variable for the number of the current column `currentCol` initialized to 0 and change the line `print potentialprime` to the following 5 lines: ``` print str(potentialprime).ljust(5), currentCol += 1 if currentCol==5: print "" currentCol=0 ``` Take notice of the call to [`ljust`](http://docs.python.or...
21,500,062
Hi I'm new in programming and in python and I have an assignment that I can't complete. I have to write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns. I have used this code so far: ``` num...
2014/02/01
[ "https://Stackoverflow.com/questions/21500062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3260697/" ]
``` col=0 #add this line while count < int(numprimes): if primetest(potentialprime) == True: print "%5d"%potentialprime, #and this line col += 1 #and this block if col==5: # print "\n" # col=0 # count += 1 potentialp...
```py while count < int(numprimes): if primetest(potentialprime) == True: print "%5d" % potentialprime, #and this line col += 1 #and this block if col == 5: # print "\n" # col = 0 # count += 1 potentialprime += 1 else: ...
21,500,062
Hi I'm new in programming and in python and I have an assignment that I can't complete. I have to write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns. I have used this code so far: ``` num...
2014/02/01
[ "https://Stackoverflow.com/questions/21500062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3260697/" ]
``` col=0 #add this line while count < int(numprimes): if primetest(potentialprime) == True: print "%5d"%potentialprime, #and this line col += 1 #and this block if col==5: # print "\n" # col=0 # count += 1 potentialp...
``` # The below code will print 1 prime number or a range of prime numbers if passed # in the range. def primeNumber(num): for i in range(2,num): if num%i==0: return f"{num} - not a prime number" break else: return f"{num} - is a prime number" mylist = [i for i in range(1,100)] for i in mylis...
52,967,071
I'm trying to do django api. In models.py ``` class Receipt(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=100) created_at = models.DateTimeField(default=datetime.datetime.now(),null=True,blank=True) updated_at = models.DateTimeField(auto_now=True,editable=False)...
2018/10/24
[ "https://Stackoverflow.com/questions/52967071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10455023/" ]
The error as you could see in traceback is in you form `ReceiptForm`. `DateTimeField` with `auto_now` are `editable=False` and `blank=True` automatically, therefore could not be included in a form unless it's readonly. You could remove `auto_now` and use a custom save method to set `updated_at`. See these questions fo...
What you're trying to achieve? [`auto_now`](https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.DateField.auto_now) is to set field value for *every save*. You can't override this. [`auto_now_add`](https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.DateField.auto_now_add) ...
61,045,138
I have following test.bat file: ``` :begin @echo off python -c "from datetime import datetime;import sys;sys.stdout.write(datetime.strptime('20200220', '%Y%m%d').replace(day = 1).strftime('%Y%m%d'))" ``` When I run it from cmd, I get: ``` ValueError: time data '20200220' does not match format 'mYd' ``` Please ig...
2020/04/05
[ "https://Stackoverflow.com/questions/61045138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9005202/" ]
Not sure why but you need to escape the `%`. This works. ``` ... python -c "from datetime import datetime;import sys;sys.stdout.write(datetime.strptime('20200220', '%%Y%%m%%d').replace(day = 1).strftime('%%Y%%m%%d'))" ```
See the message of error: ``` ValueError: time data '20200220' does not match format 'mYd' ``` 2020 is a year 02 month and 20 the day and you try to parse with **mYd**, you need parse with **Ymd**. Set correctly position of the date format.
62,471,080
I am trying to rank a large dataset using python. I do not want duplicates and rather than using the 'first' method, I would instead like it to look at another column and rank it based on that value. It should only look at the second column if the rank in the first column has duplicates. ``` Name CountA CountB Al...
2020/06/19
[ "https://Stackoverflow.com/questions/62471080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1824972/" ]
Maybe use sort and pull out the index: ``` import pandas as pd df = pd.DataFrame({'Name':['A','B','C','D'],'CountA':[15,20,20,45],'CountB':[3,52,31,43]}) df['rank'] = df.sort_values(['CountA','CountB'],ascending=False).index + 1 Name CountA CountB rank 0 A 15 3 4 1 B 20 52 2 ...
You can take the counts of the values in CountA and then filter the DataFrame rows based on the count of CountA being greater than 1. Where the count is greater than 1, take CountB, otherwise CountA. ``` df = pd.DataFrame([[15,3],[20,52],[20,31],[45,43]],columns=['CountA','CountB']) colAcount = df['CountA'].value_cou...
61,385,291
I'm working on Express with NodeJS to build some custom APIs. I've successfully build some APIs. Using GET, i'm able to retrieve the data. Here's my index.js file with all the code. ``` const express = require('express'); const app = express(); //Create user data. const userData = [ { id : 673630, ...
2020/04/23
[ "https://Stackoverflow.com/questions/61385291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12785631/" ]
In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called [body-parser](https://www.npmjs.com/package/body-parser). Please read this to get an idea about how to configure this on your app. Then you have to add t...
It would be something like this assuming your passing json in the post request: Your request body would be like this: ``` { "id": "1", "firstName": "First Name", "lastName": "Last Name" } ``` ``` app.post('/api/employees', function(req, res) { if(req.body) { userData.push(req.body) } else { ...
61,385,291
I'm working on Express with NodeJS to build some custom APIs. I've successfully build some APIs. Using GET, i'm able to retrieve the data. Here's my index.js file with all the code. ``` const express = require('express'); const app = express(); //Create user data. const userData = [ { id : 673630, ...
2020/04/23
[ "https://Stackoverflow.com/questions/61385291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12785631/" ]
In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called [body-parser](https://www.npmjs.com/package/body-parser). Please read this to get an idea about how to configure this on your app. Then you have to add t...
``` const express = require('express'); const app = express(); //including the body-parser app.use(express.json()).use(express.urlencoded({ extended: false })); //Create user data. //your get routes //post route app.post('/api/employees',function(req,res) { //posted data is available in req.body //do a...
61,385,291
I'm working on Express with NodeJS to build some custom APIs. I've successfully build some APIs. Using GET, i'm able to retrieve the data. Here's my index.js file with all the code. ``` const express = require('express'); const app = express(); //Create user data. const userData = [ { id : 673630, ...
2020/04/23
[ "https://Stackoverflow.com/questions/61385291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12785631/" ]
In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called [body-parser](https://www.npmjs.com/package/body-parser). Please read this to get an idea about how to configure this on your app. Then you have to add t...
This is my full code snippet (index.js) As you can see, i have created a post call function which takes data from 'data' const and sends to the server. But still it doesn't work. ``` const express = require('express'); const app = express(); const bodyParser = require('body-parser'); //Here we are configuring express...
61,385,291
I'm working on Express with NodeJS to build some custom APIs. I've successfully build some APIs. Using GET, i'm able to retrieve the data. Here's my index.js file with all the code. ``` const express = require('express'); const app = express(); //Create user data. const userData = [ { id : 673630, ...
2020/04/23
[ "https://Stackoverflow.com/questions/61385291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12785631/" ]
In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called [body-parser](https://www.npmjs.com/package/body-parser). Please read this to get an idea about how to configure this on your app. Then you have to add t...
I am considering you will push this data from any UI Front-End or via Postman and you know how to use it. The below solution will store data in an array, but for production, you must use a database as a solution to persist data. Since you have not mentioned which Express version you are using, I recommend to firstly d...
61,385,291
I'm working on Express with NodeJS to build some custom APIs. I've successfully build some APIs. Using GET, i'm able to retrieve the data. Here's my index.js file with all the code. ``` const express = require('express'); const app = express(); //Create user data. const userData = [ { id : 673630, ...
2020/04/23
[ "https://Stackoverflow.com/questions/61385291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12785631/" ]
In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called [body-parser](https://www.npmjs.com/package/body-parser). Please read this to get an idea about how to configure this on your app. Then you have to add t...
**Sending POST data** You need to specify *Accept* and *Content-Type* headers and stringify the JSON object in the POST request. ``` var userData = { id : 42069, firstName : 'Bob', lastName : 'Ross', age : 69 } fetch('/api/employees', { method: 'POST', headers: { 'Accept': 'application/json',...
14,095,023
I created a custom paster command as described in <http://pythonpaste.org/script/developer.html#what-do-commands-look-like>. In my setup.py I have defined the entry point like this: ``` entry_points={ 'paste.global_paster_command' : [ 'xxx_new = xxxconf.main:NewXxx' ] } ``` I'm inside an activated virtualenv...
2012/12/30
[ "https://Stackoverflow.com/questions/14095023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110963/" ]
You are doing something wrong, it should work. This is the minimal working example, you can test it with your virtualenv: `blah/setup.py`: ``` from setuptools import setup, find_packages setup(name='blah', version='0.1', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_pac...
You should install your paster\_script in the active virtualenv. Then you can use it anywhere.
51,601,502
I'd like to create a TensorFlow's dataset out of my images using Dataset API. These images are organized in a complex hierarchy but at the end, there are always two directories "False" and "Genuine". I wrote this piece of code ``` import tensorflow as tf from tensorflow.data import Dataset import os def enumerate_all...
2018/07/30
[ "https://Stackoverflow.com/questions/51601502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4671908/" ]
Counterexample ============== Using the assumptions below about the statement of the problem (times are effectively given as values such as .06 for 60 milliseconds), if we convert .06 to `float` and add it 1800 times, the computed result is 107.99884796142578125. This differs from the mathematical result, 108.000, by ...
### As much as possible, reduce the errors caused by floating point calculations Since you've already described measuring your individual timings in milliseconds, it's far better if you accumulate those timings using integer values before you finally divide them: ``` std::milliseconds duration{}; for(Timing const& ti...
51,601,502
I'd like to create a TensorFlow's dataset out of my images using Dataset API. These images are organized in a complex hierarchy but at the end, there are always two directories "False" and "Genuine". I wrote this piece of code ``` import tensorflow as tf from tensorflow.data import Dataset import os def enumerate_all...
2018/07/30
[ "https://Stackoverflow.com/questions/51601502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4671908/" ]
Counterexample ============== Using the assumptions below about the statement of the problem (times are effectively given as values such as .06 for 60 milliseconds), if we convert .06 to `float` and add it 1800 times, the computed result is 107.99884796142578125. This differs from the mathematical result, 108.000, by ...
Just for what it's worth, here's some code to demonstrate that yes, after 1800 items, a simple accumulation can be incorrect by more than 1 millisecond, but Kahan summation maintains the required level of accuracy. ``` #include <iostream> #include <iterator> #include <iomanip> #include <vector> #include <numeric> tem...
51,601,502
I'd like to create a TensorFlow's dataset out of my images using Dataset API. These images are organized in a complex hierarchy but at the end, there are always two directories "False" and "Genuine". I wrote this piece of code ``` import tensorflow as tf from tensorflow.data import Dataset import os def enumerate_all...
2018/07/30
[ "https://Stackoverflow.com/questions/51601502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4671908/" ]
### As much as possible, reduce the errors caused by floating point calculations Since you've already described measuring your individual timings in milliseconds, it's far better if you accumulate those timings using integer values before you finally divide them: ``` std::milliseconds duration{}; for(Timing const& ti...
Just for what it's worth, here's some code to demonstrate that yes, after 1800 items, a simple accumulation can be incorrect by more than 1 millisecond, but Kahan summation maintains the required level of accuracy. ``` #include <iostream> #include <iterator> #include <iomanip> #include <vector> #include <numeric> tem...
58,088,175
This is similar to [this question](https://stackoverflow.com/questions/45221014/python-exif-cant-find-date-taken-information-but-exists-when-viewer-through-wi), except that the solution there doesn't work for me. Viewing a HEIC file in Windows Explorer, I can see several dates. The one that matches what I know is the ...
2019/09/24
[ "https://Stackoverflow.com/questions/58088175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123047/" ]
It's a HEIC file issue - it's not supported apparently, some difficulties around licensing I think.
While doing it with `mdls`, it's better (performance-wise) to give it a whole bunch of filenames separated by space at once. I tested with 1000 files: works fine, 20 times performance gain.
58,088,175
This is similar to [this question](https://stackoverflow.com/questions/45221014/python-exif-cant-find-date-taken-information-but-exists-when-viewer-through-wi), except that the solution there doesn't work for me. Viewing a HEIC file in Windows Explorer, I can see several dates. The one that matches what I know is the ...
2019/09/24
[ "https://Stackoverflow.com/questions/58088175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123047/" ]
On `macOS` you can use the native `mdls` (meta-data list, credit to [Ask Dave Taylor](https://www.askdavetaylor.com/can-i-analyze-exif-information-on-the-mac-os-x-command-line/)) through a shell to get the data from HEIC. Note that calling a shell like this is not good programming, so use with care. ```py import datet...
While doing it with `mdls`, it's better (performance-wise) to give it a whole bunch of filenames separated by space at once. I tested with 1000 files: works fine, 20 times performance gain.
24,456,735
I could successfully rum a simple program to check whether the number is prime or not in C. The code looks like this ``` void isPrime(int n) { int a=0,i; for(i=1;i<=n;i++) { if(n%i==0) a++; } if(a==2) { printf("\n%d is prime",n); } else { printf("\n%d is not ...
2014/06/27
[ "https://Stackoverflow.com/questions/24456735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2947110/" ]
Why don't you add some `print` statements so you can see where the code fails? Adding some prints should be your first reflex when debugging. ``` def isPrime(n): a=0 for x in range(1,n): print('x,a', x,a) if n%x==0: print('incrementing a...') a=a+1 print('a after loo...
The issue you have is that the last value produced `range(start, stop)` is `stop-1`; see [the docs](https://docs.python.org/2/library/functions.html#range). Thus, `isPrime` should have the following `for` loop: ``` for x in range(1, n+1): ``` This will faithfully replicate the C code, and produce the correct output....
24,456,735
I could successfully rum a simple program to check whether the number is prime or not in C. The code looks like this ``` void isPrime(int n) { int a=0,i; for(i=1;i<=n;i++) { if(n%i==0) a++; } if(a==2) { printf("\n%d is prime",n); } else { printf("\n%d is not ...
2014/06/27
[ "https://Stackoverflow.com/questions/24456735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2947110/" ]
Why don't you add some `print` statements so you can see where the code fails? Adding some prints should be your first reflex when debugging. ``` def isPrime(n): a=0 for x in range(1,n): print('x,a', x,a) if n%x==0: print('incrementing a...') a=a+1 print('a after loo...
I think the problem was with your range as mentioned above. Can I give you some short tips to make your code more "Pythonic"? :) Instead of `if n%x==0` you would simply write `if not n%x` and instead of `a=a+1` you could use the in-place operator, e.g., `a += 1` Here, it wouldn't make much of a difference,...
24,456,735
I could successfully rum a simple program to check whether the number is prime or not in C. The code looks like this ``` void isPrime(int n) { int a=0,i; for(i=1;i<=n;i++) { if(n%i==0) a++; } if(a==2) { printf("\n%d is prime",n); } else { printf("\n%d is not ...
2014/06/27
[ "https://Stackoverflow.com/questions/24456735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2947110/" ]
The issue you have is that the last value produced `range(start, stop)` is `stop-1`; see [the docs](https://docs.python.org/2/library/functions.html#range). Thus, `isPrime` should have the following `for` loop: ``` for x in range(1, n+1): ``` This will faithfully replicate the C code, and produce the correct output....
I think the problem was with your range as mentioned above. Can I give you some short tips to make your code more "Pythonic"? :) Instead of `if n%x==0` you would simply write `if not n%x` and instead of `a=a+1` you could use the in-place operator, e.g., `a += 1` Here, it wouldn't make much of a difference,...
1,459,590
if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine: ``` os.listdir("\\\\remotehost\\share") ``` However, if I attempt to list the network drives/directories available on the remot...
2009/09/22
[ "https://Stackoverflow.com/questions/1459590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300745/" ]
May be [pysmb](http://miketeo.net/wp/index.php/projects/pysmb) can help
Sorry. I'm not able to try this as I'm not in a PC. Have you tried: ``` os.listdir("\\\\remotehost\\") ```
1,459,590
if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine: ``` os.listdir("\\\\remotehost\\share") ``` However, if I attempt to list the network drives/directories available on the remot...
2009/09/22
[ "https://Stackoverflow.com/questions/1459590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300745/" ]
May be [pysmb](http://miketeo.net/wp/index.php/projects/pysmb) can help
Maybe the following script will help you. See <http://gallery.technet.microsoft.com/ScriptCenter/en-us/7338e3bd-1f88-4da9-a585-17877fa37e3b>
1,459,590
if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine: ``` os.listdir("\\\\remotehost\\share") ``` However, if I attempt to list the network drives/directories available on the remot...
2009/09/22
[ "https://Stackoverflow.com/questions/1459590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300745/" ]
May be [pysmb](http://miketeo.net/wp/index.php/projects/pysmb) can help
I'm sure the OP has forgotten about this question by now, but here's (maybe) an explanation: <http://www.python.org/doc/faq/windows/#why-does-os-path-isdir-fail-on-nt-shared-directories> In case anybody else happens along this problem, like I did.
1,459,590
if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine: ``` os.listdir("\\\\remotehost\\share") ``` However, if I attempt to list the network drives/directories available on the remot...
2009/09/22
[ "https://Stackoverflow.com/questions/1459590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300745/" ]
May be [pysmb](http://miketeo.net/wp/index.php/projects/pysmb) can help
For anyone still wondering how to list network shares at the top level on windows, you can use the win32net module: ``` import win32net shares, _, _ = win32net.NetShareEnum('remotehost',0) ``` The integer controls the type of information returned but if you just want a list of the shares then 0 will do. This works ...
1,459,590
if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine: ``` os.listdir("\\\\remotehost\\share") ``` However, if I attempt to list the network drives/directories available on the remot...
2009/09/22
[ "https://Stackoverflow.com/questions/1459590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300745/" ]
Maybe the following script will help you. See <http://gallery.technet.microsoft.com/ScriptCenter/en-us/7338e3bd-1f88-4da9-a585-17877fa37e3b>
Sorry. I'm not able to try this as I'm not in a PC. Have you tried: ``` os.listdir("\\\\remotehost\\") ```
1,459,590
if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine: ``` os.listdir("\\\\remotehost\\share") ``` However, if I attempt to list the network drives/directories available on the remot...
2009/09/22
[ "https://Stackoverflow.com/questions/1459590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300745/" ]
I'm sure the OP has forgotten about this question by now, but here's (maybe) an explanation: <http://www.python.org/doc/faq/windows/#why-does-os-path-isdir-fail-on-nt-shared-directories> In case anybody else happens along this problem, like I did.
Sorry. I'm not able to try this as I'm not in a PC. Have you tried: ``` os.listdir("\\\\remotehost\\") ```
1,459,590
if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine: ``` os.listdir("\\\\remotehost\\share") ``` However, if I attempt to list the network drives/directories available on the remot...
2009/09/22
[ "https://Stackoverflow.com/questions/1459590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300745/" ]
For anyone still wondering how to list network shares at the top level on windows, you can use the win32net module: ``` import win32net shares, _, _ = win32net.NetShareEnum('remotehost',0) ``` The integer controls the type of information returned but if you just want a list of the shares then 0 will do. This works ...
Sorry. I'm not able to try this as I'm not in a PC. Have you tried: ``` os.listdir("\\\\remotehost\\") ```
1,459,590
if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine: ``` os.listdir("\\\\remotehost\\share") ``` However, if I attempt to list the network drives/directories available on the remot...
2009/09/22
[ "https://Stackoverflow.com/questions/1459590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300745/" ]
For anyone still wondering how to list network shares at the top level on windows, you can use the win32net module: ``` import win32net shares, _, _ = win32net.NetShareEnum('remotehost',0) ``` The integer controls the type of information returned but if you just want a list of the shares then 0 will do. This works ...
Maybe the following script will help you. See <http://gallery.technet.microsoft.com/ScriptCenter/en-us/7338e3bd-1f88-4da9-a585-17877fa37e3b>
1,459,590
if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine: ``` os.listdir("\\\\remotehost\\share") ``` However, if I attempt to list the network drives/directories available on the remot...
2009/09/22
[ "https://Stackoverflow.com/questions/1459590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300745/" ]
For anyone still wondering how to list network shares at the top level on windows, you can use the win32net module: ``` import win32net shares, _, _ = win32net.NetShareEnum('remotehost',0) ``` The integer controls the type of information returned but if you just want a list of the shares then 0 will do. This works ...
I'm sure the OP has forgotten about this question by now, but here's (maybe) an explanation: <http://www.python.org/doc/faq/windows/#why-does-os-path-isdir-fail-on-nt-shared-directories> In case anybody else happens along this problem, like I did.
73,279,102
I have the following sentence: ``` text="The weather is extremely severe in England" ``` I want to perform a custom `Name Entity Recognition (NER)` procedure First a normal `NER` procedure will output `England` with a `GPE` label ``` pip install spacy !python -m spacy download en_core_web_lg import spacy nlp = s...
2022/08/08
[ "https://Stackoverflow.com/questions/73279102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465901/" ]
Indeed it looks like NER do not allow overlapping, and that is your problem, your second part of the code tries to create a ner containing another ner, hence, it fails. see in: <https://github.com/explosion/spaCy/discussions/10885> and therefore spacy has spans categorization. I did not find yet the way to character...
Why do you need the new hash in the string store? Due to the underscore? Thx
2,407,872
I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more...
2010/03/09
[ "https://Stackoverflow.com/questions/2407872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49628/" ]
You could use a global registry: ``` window.WidgetRegistry = {}; window.WidgetRegistry['foowidget'] = new Widget('#myID'); ``` and when AJAX calls return, they can get the widget like this: ``` var widgetID = data.widgetID; if (widgetID in window.WidgetRegistry) { var widget = window.WidgetRegistry[widgetID]; }...
I'm not sure I've fully understood your question, but I'll try to point some ideas. In my opinion, you should make base widget class, which contains common functionality for widgets. Let's use for example AppName.Widgets.base(). One of the instance variables is \_events, which is object that stores events as keys and...
2,407,872
I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more...
2010/03/09
[ "https://Stackoverflow.com/questions/2407872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49628/" ]
You could use a global registry: ``` window.WidgetRegistry = {}; window.WidgetRegistry['foowidget'] = new Widget('#myID'); ``` and when AJAX calls return, they can get the widget like this: ``` var widgetID = data.widgetID; if (widgetID in window.WidgetRegistry) { var widget = window.WidgetRegistry[widgetID]; }...
A lot of what you can or can't do will depend on how much control you have over the javascript. Personally I often have to use libraries built by others so I might only get a DOM node to work with, but I really need my object instead. In these cases I find using the data feature in jQuery is very handy. By using the da...
2,407,872
I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more...
2010/03/09
[ "https://Stackoverflow.com/questions/2407872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49628/" ]
For the four objects that need to be synchronized, you could have a single object and pass the reference around in a constructor, or as function arguments. The way I fix this problem is to never lose a reference to the wrapper object. Whenever a DOM object is needed (for example inserting into the page), this wrapper ...
I'm not sure I've fully understood your question, but I'll try to point some ideas. In my opinion, you should make base widget class, which contains common functionality for widgets. Let's use for example AppName.Widgets.base(). One of the instance variables is \_events, which is object that stores events as keys and...
2,407,872
I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more...
2010/03/09
[ "https://Stackoverflow.com/questions/2407872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49628/" ]
I'm not sure I've fully understood your question, but I'll try to point some ideas. In my opinion, you should make base widget class, which contains common functionality for widgets. Let's use for example AppName.Widgets.base(). One of the instance variables is \_events, which is object that stores events as keys and...
A lot of what you can or can't do will depend on how much control you have over the javascript. Personally I often have to use libraries built by others so I might only get a DOM node to work with, but I really need my object instead. In these cases I find using the data feature in jQuery is very handy. By using the da...
2,407,872
I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more...
2010/03/09
[ "https://Stackoverflow.com/questions/2407872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49628/" ]
For the four objects that need to be synchronized, you could have a single object and pass the reference around in a constructor, or as function arguments. The way I fix this problem is to never lose a reference to the wrapper object. Whenever a DOM object is needed (for example inserting into the page), this wrapper ...
A lot of what you can or can't do will depend on how much control you have over the javascript. Personally I often have to use libraries built by others so I might only get a DOM node to work with, but I really need my object instead. In these cases I find using the data feature in jQuery is very handy. By using the da...
38,302,028
Using pip from a (python 3.5) script, how can i upgrade a package i previously installed via the command line (using `pip install`)? Something like ``` import pip pip.install("mysuperawesomepackage", upgrade=True) ```
2016/07/11
[ "https://Stackoverflow.com/questions/38302028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113623/" ]
I think you should link in either 2 stylesheets, one for portrait and one for landscape OR define your styles with media queries using orientation In the following example i have included both, but either will do. e.g. ```html <html> <head> <meta charset="utf-8"> <link rel="stylesheet" media="all and (orientation...
Try to give every thing in percentage in some exceptional cases like font size etc you can use EM or PX.
57,596,488
I am trying to access JSON using urllib.request.urlopen. It works fine when I use urllib2 in python2, but not urllib.request.urlopen. ``` URL = 'https://api.exchangeratesapi.io/latest' f = urllib.request.urlopen(URL) ``` ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3....
2019/08/21
[ "https://Stackoverflow.com/questions/57596488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11958437/" ]
This is what I used and it worked: ``` from urllib.request import urlopen URL = 'https://api.exchangeratesapi.io/latest' f = urlopen(URL) ``` I hope this works for you!
you can try to disable the ssl verification ``` import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) ```
57,596,488
I am trying to access JSON using urllib.request.urlopen. It works fine when I use urllib2 in python2, but not urllib.request.urlopen. ``` URL = 'https://api.exchangeratesapi.io/latest' f = urllib.request.urlopen(URL) ``` ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3....
2019/08/21
[ "https://Stackoverflow.com/questions/57596488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11958437/" ]
This is what I used and it worked: ``` from urllib.request import urlopen URL = 'https://api.exchangeratesapi.io/latest' f = urlopen(URL) ``` I hope this works for you!
In my case there was an issue with error in *request.py*: **\_load\_windows\_store\_certs** caused *MemoryError* Fixed by updating python from version **3.7.4** to **3.8.1** Hope this help
54,685,134
I am using Keras to create a deep learning model. When I creating a VGG16 model, the model is created but I get the following warning. ``` vgg16_model = VGG16() ``` why this warning happens and how can I resolve this? ``` WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_...
2019/02/14
[ "https://Stackoverflow.com/questions/54685134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10594993/" ]
It looks like there's an open git issue to clean this up in the keras code: <https://github.com/tensorflow/minigo/issues/740> You should be safe to ignore the warning, I don't believe you can change it without modifying the TF repo. You can disable warnings as [mentioned here](https://stackoverflow.com/questions/486...
So , the method `colocate_with` is a context manager to make sure that the operation or tensor you're about to create will be placed on the same device the reference operation is on. But, your warning says that it will be deprecated and that this will from now on be handled automatically. From the next version of tenso...
54,685,134
I am using Keras to create a deep learning model. When I creating a VGG16 model, the model is created but I get the following warning. ``` vgg16_model = VGG16() ``` why this warning happens and how can I resolve this? ``` WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_...
2019/02/14
[ "https://Stackoverflow.com/questions/54685134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10594993/" ]
You can use the function below to avoid these warnings. First, you must make the appropriate imports: ``` import os os.environ['KERAS_BACKEND']='tensorflow' import tensorflow as tf def tf_no_warning(): """ Make Tensorflow less verbose """ try: tf.logging.set_verbosity(tf.logging.ERROR) ...
So , the method `colocate_with` is a context manager to make sure that the operation or tensor you're about to create will be placed on the same device the reference operation is on. But, your warning says that it will be deprecated and that this will from now on be handled automatically. From the next version of tenso...
54,685,134
I am using Keras to create a deep learning model. When I creating a VGG16 model, the model is created but I get the following warning. ``` vgg16_model = VGG16() ``` why this warning happens and how can I resolve this? ``` WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_...
2019/02/14
[ "https://Stackoverflow.com/questions/54685134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10594993/" ]
It looks like there's an open git issue to clean this up in the keras code: <https://github.com/tensorflow/minigo/issues/740> You should be safe to ignore the warning, I don't believe you can change it without modifying the TF repo. You can disable warnings as [mentioned here](https://stackoverflow.com/questions/486...
You can use the function below to avoid these warnings. First, you must make the appropriate imports: ``` import os os.environ['KERAS_BACKEND']='tensorflow' import tensorflow as tf def tf_no_warning(): """ Make Tensorflow less verbose """ try: tf.logging.set_verbosity(tf.logging.ERROR) ...
39,693,115
I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate: ``` From [email protected] Sat Jan 5 09:14:16 2008 ``` I need to extract the hours from each line (in this case 09) and then find the most common hours the emails ...
2016/09/26
[ "https://Stackoverflow.com/questions/39693115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6879638/" ]
Ok, first off, you should probably use a `with` `as` statement, it just simplifies things and makes sure you don't mess up. So `fh = open('poem.txt', 'r')` becomes `with open('poem.txt','r') as file:` and since you're just concerned with words, you might as well use a built-in from the start: ``` words = file....
What you need to do is to keep a list of all the longest words you've seen so far and keep the longest length. So for example, if the longest word so far has the length 5, you will have a list of all words with 5 characters in it. As soon as you see a word with 6 or more characters, you will clear that list and only pu...
39,693,115
I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate: ``` From [email protected] Sat Jan 5 09:14:16 2008 ``` I need to extract the hours from each line (in this case 09) and then find the most common hours the emails ...
2016/09/26
[ "https://Stackoverflow.com/questions/39693115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6879638/" ]
What you need to do is to keep a list of all the longest words you've seen so far and keep the longest length. So for example, if the longest word so far has the length 5, you will have a list of all words with 5 characters in it. As soon as you see a word with 6 or more characters, you will clear that list and only pu...
### TLDR Showing the results for a file named `poem.txt` whose contents are: `a dog is by a cat to go hi` ```py >>> with open('poem.txt', 'r') as file: ... words = file.read().split() ... >>> [this_word for this_word in words if len(this_word) == len(max(words,key=len))] ['dog', 'cat'] ``` ### Explanation You c...
39,693,115
I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate: ``` From [email protected] Sat Jan 5 09:14:16 2008 ``` I need to extract the hours from each line (in this case 09) and then find the most common hours the emails ...
2016/09/26
[ "https://Stackoverflow.com/questions/39693115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6879638/" ]
Ok, first off, you should probably use a `with` `as` statement, it just simplifies things and makes sure you don't mess up. So `fh = open('poem.txt', 'r')` becomes `with open('poem.txt','r') as file:` and since you're just concerned with words, you might as well use a built-in from the start: ``` words = file....
### TLDR Showing the results for a file named `poem.txt` whose contents are: `a dog is by a cat to go hi` ```py >>> with open('poem.txt', 'r') as file: ... words = file.read().split() ... >>> [this_word for this_word in words if len(this_word) == len(max(words,key=len))] ['dog', 'cat'] ``` ### Explanation You c...
13,228,939
Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging. is there any standard convention people follow or is it...
2012/11/05
[ "https://Stackoverflow.com/questions/13228939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1475962/" ]
Implement function [`__str__`](http://docs.python.org/3/reference/datamodel.html#object.__str__) in the class for the object you are printing. If you are printing objects for a class that you can't alter then it is fairly straightforward to provide your own `print` function, since you are using Python 3. Edit: Usual...
The standard way to print custom info about an object (class instance) is to use `__str__` method: ``` class A: var = 1 def __str__(self): return 'Accessing from print function, var = {0}'.format(self.var) ``` In this method you can display any info you want ``` a = A() print(a) >>> Accessing from ...
13,228,939
Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging. is there any standard convention people follow or is it...
2012/11/05
[ "https://Stackoverflow.com/questions/13228939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1475962/" ]
You can overwrite either the `__str__` or the `__repr__` method. There is no convention on how to implement the `__str__` method; it can just return any human-readable string representation you want. There is, however, a convention on how to implement the `__repr__` method: it should return a string representation of ...
Implement function [`__str__`](http://docs.python.org/3/reference/datamodel.html#object.__str__) in the class for the object you are printing. If you are printing objects for a class that you can't alter then it is fairly straightforward to provide your own `print` function, since you are using Python 3. Edit: Usual...
13,228,939
Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging. is there any standard convention people follow or is it...
2012/11/05
[ "https://Stackoverflow.com/questions/13228939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1475962/" ]
Implement function [`__str__`](http://docs.python.org/3/reference/datamodel.html#object.__str__) in the class for the object you are printing. If you are printing objects for a class that you can't alter then it is fairly straightforward to provide your own `print` function, since you are using Python 3. Edit: Usual...
If your object can be represented in a way that allows recreation, then override the `__repr__` function. For example, if you can create your object with the following code: ``` MyObject('foo', 45) ``` The the `__repr__` should return `"MyObject('foo', 45)"`. You then don't need to implement a `__str__`. But if the...
13,228,939
Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging. is there any standard convention people follow or is it...
2012/11/05
[ "https://Stackoverflow.com/questions/13228939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1475962/" ]
You can overwrite either the `__str__` or the `__repr__` method. There is no convention on how to implement the `__str__` method; it can just return any human-readable string representation you want. There is, however, a convention on how to implement the `__repr__` method: it should return a string representation of ...
The standard way to print custom info about an object (class instance) is to use `__str__` method: ``` class A: var = 1 def __str__(self): return 'Accessing from print function, var = {0}'.format(self.var) ``` In this method you can display any info you want ``` a = A() print(a) >>> Accessing from ...
13,228,939
Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging. is there any standard convention people follow or is it...
2012/11/05
[ "https://Stackoverflow.com/questions/13228939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1475962/" ]
If your object can be represented in a way that allows recreation, then override the `__repr__` function. For example, if you can create your object with the following code: ``` MyObject('foo', 45) ``` The the `__repr__` should return `"MyObject('foo', 45)"`. You then don't need to implement a `__str__`. But if the...
The standard way to print custom info about an object (class instance) is to use `__str__` method: ``` class A: var = 1 def __str__(self): return 'Accessing from print function, var = {0}'.format(self.var) ``` In this method you can display any info you want ``` a = A() print(a) >>> Accessing from ...
13,228,939
Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging. is there any standard convention people follow or is it...
2012/11/05
[ "https://Stackoverflow.com/questions/13228939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1475962/" ]
You can overwrite either the `__str__` or the `__repr__` method. There is no convention on how to implement the `__str__` method; it can just return any human-readable string representation you want. There is, however, a convention on how to implement the `__repr__` method: it should return a string representation of ...
If your object can be represented in a way that allows recreation, then override the `__repr__` function. For example, if you can create your object with the following code: ``` MyObject('foo', 45) ``` The the `__repr__` should return `"MyObject('foo', 45)"`. You then don't need to implement a `__str__`. But if the...
68,929,023
I have to do this in python so instead of writing these many lines - any other way ? ``` insert into table_a (col1,col2,col3) select col1,col2,col3 from temp; insert into table_b (col1,col2,col3) select col1,col2,col3 from temp; insert into table_c (col1,col2,col3) select col1,col2,col3 from temp; insert into table...
2021/08/25
[ "https://Stackoverflow.com/questions/68929023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16257885/" ]
If you only need it to go until a specific letter, you can just use a string with as many letters as you need and then loop through them. [Thanks to Michael for pointing it out] ``` letters = "abcdefgh" for letter in letters: print(f"insert into table_{letter} (col1,col2,col3) select col1,col2,col3 from temp;") ...
Put the table names in a `list`, then iterate on it and build the query with it ``` tables = ['table_a', 'table_b', 'table_c'] for table in tables: query = f"insert into {table} (col1,col2,col3) select col1,col2,col3 from temp;" ```
12,084,445
Is it possible to change the getter for a python property after it has been created? ``` class A: _lookup_str = 'hi' @property def thing(): value = some_dictionary[_lookup_str] # overwrite self.thing so that it is just value, not a special getter return value ``` The idea is that ...
2012/08/23
[ "https://Stackoverflow.com/questions/12084445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/257712/" ]
Werkzeug has a [`cached_property` decorator](http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property) that does exactly what you want. It just replaces the `__dict__` entry for the function after the first function call with the output of the first call. Here's the code (from [werkzeug.utils on github](ht...
The answer, as indicated by Jeff Tratner, is to overwrite the property object found in the `__dict__` of the python object. Werkzeug's cached\_property seems overcomplicated to me. The following (much simpler) code works for me: ``` def cached_property(f): @property def g(self, *args, **kwargs): print ...
12,084,445
Is it possible to change the getter for a python property after it has been created? ``` class A: _lookup_str = 'hi' @property def thing(): value = some_dictionary[_lookup_str] # overwrite self.thing so that it is just value, not a special getter return value ``` The idea is that ...
2012/08/23
[ "https://Stackoverflow.com/questions/12084445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/257712/" ]
Werkzeug has a [`cached_property` decorator](http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property) that does exactly what you want. It just replaces the `__dict__` entry for the function after the first function call with the output of the first call. Here's the code (from [werkzeug.utils on github](ht...
It is not recommended but it works for old-style classes: ``` >>> class A: ... @property ... def thing(self): ... print 'thing' ... self.thing = 42 ... return self.thing ... >>> a = A() >>> a.thing thing 42 >>> a.thing 42 >>> a.thing 42 ``` It doesn't work for new-style classes (subclasses of ...
12,084,445
Is it possible to change the getter for a python property after it has been created? ``` class A: _lookup_str = 'hi' @property def thing(): value = some_dictionary[_lookup_str] # overwrite self.thing so that it is just value, not a special getter return value ``` The idea is that ...
2012/08/23
[ "https://Stackoverflow.com/questions/12084445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/257712/" ]
Werkzeug has a [`cached_property` decorator](http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property) that does exactly what you want. It just replaces the `__dict__` entry for the function after the first function call with the output of the first call. Here's the code (from [werkzeug.utils on github](ht...
The answer by J.F. Sebastian and Isaac Sutherland do not work with new style classes. It will produce the result Jeff Tratner mentions; printing out trace on every access. For new style classes, you will need to override `__getattribute__` Simple fix: ``` def cached_property(f): @property def g(self, *args,...
17,300,638
I am trying to get Node.js to build on Windows. The process completes, seemingly okay, but does not generate node.lib. Checking what was output it seems there is an issue right at the start (I disappeared off to get a coffee why I didn't see it at first) when trying to build. ``` Project files generated. Setting env...
2013/06/25
[ "https://Stackoverflow.com/questions/17300638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ]
You can save the previous position of the marble like this: ``` CGRect previousPosition = marbleFrame.frame; ``` And in the next iteration, if the marble collides the wall, set its frame to that. Other solution would be checking from which side is colliding (top, left, right or down), that's easy comparing the inte...
First of all, collision detection is not a easy thing to get working correctly, so you may want to look into some external libraries, such as ObjectiveChipmunk or Box2d. That being said, there are a few things you could put into that else statement. The general way to go about it would be to "move the object back" so...
62,885,473
``` import numpy as np import pandas as pd df = pd.read_csv('Salaries.csv',engine='python') print( df[ df['JobTitle'].value_counts()==1 ] ) ``` I'm trying to get the row if the Job in JobTitle appears once. However, I keep getting this error: pandas.core.indexing.IndexingError: Unalignable boolean Series provided ...
2020/07/13
[ "https://Stackoverflow.com/questions/62885473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13758656/" ]
Another solution using `transform`: ``` df[df.groupby('JobTitle')['JobTitle'].transform('count').eq(1)] ```
You can do it in a single line of code combining the index values of `value_counts()` where the series is equal to 1: ``` df[df['A'].isin((df['A'].value_counts() == 1).replace({False:np.nan}).dropna().index)] ``` Perhaps a bit better and easier to understand, in two lines of code: ``` values = df['A'].value_counts(...
7,666,269
I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it: ``` People person = new People(); ``` Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object ...
2011/10/05
[ "https://Stackoverflow.com/questions/7666269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629599/" ]
In Java you only have primitives and references to objects as types for fields, parameters and local variables. A reference is a bit like an ID, except it can change as any moment without you needing to know when this has happened. A reference is closer to the concept of a pointer or object index. ie. it refers to a m...
constructor is not "normal" method. And you must use operator `new` with constructor and then you will have reference to the object, so this is pointer (id) to the place in memory. [here is some explanation](http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html) > > Constructor declarations look l...
7,666,269
I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it: ``` People person = new People(); ``` Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object ...
2011/10/05
[ "https://Stackoverflow.com/questions/7666269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629599/" ]
In Java you only have primitives and references to objects as types for fields, parameters and local variables. A reference is a bit like an ID, except it can change as any moment without you needing to know when this has happened. A reference is closer to the concept of a pointer or object index. ie. it refers to a m...
Short answer: no More answer: The thing that is "returning" something is the `new` operator. When you create a new instance of a class (via the `new` operator), you must provide two pieces of information to the JVM: the name of the class to be instantiated and any parameters that are required to construct the new obj...
7,666,269
I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it: ``` People person = new People(); ``` Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object ...
2011/10/05
[ "https://Stackoverflow.com/questions/7666269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629599/" ]
In Java you only have primitives and references to objects as types for fields, parameters and local variables. A reference is a bit like an ID, except it can change as any moment without you needing to know when this has happened. A reference is closer to the concept of a pointer or object index. ie. it refers to a m...
The return type of a constructor is the **Class** itself. You cannot consider them as void but its guaranteed to allocate memory on the heap and initialize the member fields , and finally returning the address of the newly allocated object which we use as reference variables.
7,666,269
I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it: ``` People person = new People(); ``` Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object ...
2011/10/05
[ "https://Stackoverflow.com/questions/7666269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629599/" ]
In Java you only have primitives and references to objects as types for fields, parameters and local variables. A reference is a bit like an ID, except it can change as any moment without you needing to know when this has happened. A reference is closer to the concept of a pointer or object index. ie. it refers to a m...
according to me, When the constructor used with 'new' keyword, it allocate the memory space for that object. For Example: in your code `People person = new People();` it automatically allocate the space required for the newly created object 'person' in the memory.
7,666,269
I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it: ``` People person = new People(); ``` Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object ...
2011/10/05
[ "https://Stackoverflow.com/questions/7666269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629599/" ]
constructor is not "normal" method. And you must use operator `new` with constructor and then you will have reference to the object, so this is pointer (id) to the place in memory. [here is some explanation](http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html) > > Constructor declarations look l...
Short answer: no More answer: The thing that is "returning" something is the `new` operator. When you create a new instance of a class (via the `new` operator), you must provide two pieces of information to the JVM: the name of the class to be instantiated and any parameters that are required to construct the new obj...
7,666,269
I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it: ``` People person = new People(); ``` Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object ...
2011/10/05
[ "https://Stackoverflow.com/questions/7666269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629599/" ]
constructor is not "normal" method. And you must use operator `new` with constructor and then you will have reference to the object, so this is pointer (id) to the place in memory. [here is some explanation](http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html) > > Constructor declarations look l...
The return type of a constructor is the **Class** itself. You cannot consider them as void but its guaranteed to allocate memory on the heap and initialize the member fields , and finally returning the address of the newly allocated object which we use as reference variables.
7,666,269
I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it: ``` People person = new People(); ``` Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object ...
2011/10/05
[ "https://Stackoverflow.com/questions/7666269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629599/" ]
constructor is not "normal" method. And you must use operator `new` with constructor and then you will have reference to the object, so this is pointer (id) to the place in memory. [here is some explanation](http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html) > > Constructor declarations look l...
according to me, When the constructor used with 'new' keyword, it allocate the memory space for that object. For Example: in your code `People person = new People();` it automatically allocate the space required for the newly created object 'person' in the memory.
7,666,269
I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it: ``` People person = new People(); ``` Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object ...
2011/10/05
[ "https://Stackoverflow.com/questions/7666269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629599/" ]
Short answer: no More answer: The thing that is "returning" something is the `new` operator. When you create a new instance of a class (via the `new` operator), you must provide two pieces of information to the JVM: the name of the class to be instantiated and any parameters that are required to construct the new obj...
according to me, When the constructor used with 'new' keyword, it allocate the memory space for that object. For Example: in your code `People person = new People();` it automatically allocate the space required for the newly created object 'person' in the memory.
7,666,269
I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it: ``` People person = new People(); ``` Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object ...
2011/10/05
[ "https://Stackoverflow.com/questions/7666269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629599/" ]
The return type of a constructor is the **Class** itself. You cannot consider them as void but its guaranteed to allocate memory on the heap and initialize the member fields , and finally returning the address of the newly allocated object which we use as reference variables.
according to me, When the constructor used with 'new' keyword, it allocate the memory space for that object. For Example: in your code `People person = new People();` it automatically allocate the space required for the newly created object 'person' in the memory.
20,435,615
I am trying to build a list with the following format: (t,dt,array) Where t is time -float-, dt is also a float an array is an array of ints that represents the state of my system. I want to have elements ordered in an array by the first element, that is t. So my take on it is to use the heap structure provided by Py...
2013/12/06
[ "https://Stackoverflow.com/questions/20435615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3053450/" ]
``` (0,0,np.random.randint(0,2,Nsize)) ``` The first two elements there aren't `t` or `dt`. They're both 0. As such, the tuple comparison tries to compare the arrays in the 3rd slot and finds that that doesn't produce a meaningful boolean result. Did you mean to have something meaningful in the first two slots?
As far as where the error comes from: ``` >>> a = (0, 0, np.random.randint(0, 2, 3)) >>> a (0, 0, array([0, 0, 1])) >>> b = (0, 0, np.random.randint(0, 2, 3)) >>> a (0, 0, array([0, 0, 1])) >>> a == b ``` The reason for this is that numpy overrides comparison operators in a non-standard way. Rather than returning a ...
20,435,615
I am trying to build a list with the following format: (t,dt,array) Where t is time -float-, dt is also a float an array is an array of ints that represents the state of my system. I want to have elements ordered in an array by the first element, that is t. So my take on it is to use the heap structure provided by Py...
2013/12/06
[ "https://Stackoverflow.com/questions/20435615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3053450/" ]
``` (0,0,np.random.randint(0,2,Nsize)) ``` The first two elements there aren't `t` or `dt`. They're both 0. As such, the tuple comparison tries to compare the arrays in the 3rd slot and finds that that doesn't produce a meaningful boolean result. Did you mean to have something meaningful in the first two slots?
So what I ended up doing was to add another element in the list to make the intial comparison possible: ``` populat = [ (0,0,i,np.random.randint(0,2,Nsize)) for i in range(popsize)] ``` As pointed above if the **two first elements are equal** the comparison goes to the third element (the array) which returns an er...
20,435,615
I am trying to build a list with the following format: (t,dt,array) Where t is time -float-, dt is also a float an array is an array of ints that represents the state of my system. I want to have elements ordered in an array by the first element, that is t. So my take on it is to use the heap structure provided by Py...
2013/12/06
[ "https://Stackoverflow.com/questions/20435615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3053450/" ]
As far as where the error comes from: ``` >>> a = (0, 0, np.random.randint(0, 2, 3)) >>> a (0, 0, array([0, 0, 1])) >>> b = (0, 0, np.random.randint(0, 2, 3)) >>> a (0, 0, array([0, 0, 1])) >>> a == b ``` The reason for this is that numpy overrides comparison operators in a non-standard way. Rather than returning a ...
So what I ended up doing was to add another element in the list to make the intial comparison possible: ``` populat = [ (0,0,i,np.random.randint(0,2,Nsize)) for i in range(popsize)] ``` As pointed above if the **two first elements are equal** the comparison goes to the third element (the array) which returns an er...
18,026,306
I am trying to create a python class based on this class. I am trying to have it return the person’s wages for the week (including time and a half for any overtime. I need to place this method following the def getPhoneNo(self): method and before the `def __str__(self):` method because I am trying to use this method in...
2013/08/02
[ "https://Stackoverflow.com/questions/18026306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2631037/" ]
Is the `__str__` function looking alright? I mean stringRep is changed several times and the last version is returned. I think the body of the function should look like this: ``` stringRep = "First Name: " + self.firstName + "\n" +\ "Last Name: " + self.lastName + "\n" +\ "Phone Number...
I see two issues in the example you posted: * The getWeeksPay function needs to be indented so that it is interpreted as a PersonWorker class method versus a normal function. * You have some funky characters at the end of the return statement in the **str** method. I updated your code snippet with an example of what ...
38,466,796
I just made a heap class in python and am still working in Tree traversal. When I invoked `inoder function`, I got error said `None is not in the list`. In my three traversal functions, they all need `left` and `right` function. I assume that the problem is in these two functions, but I don't know how to fix it. ``` c...
2016/07/19
[ "https://Stackoverflow.com/questions/38466796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6338377/" ]
You don't actually need to use the ID directly; you can just sample row numbers, and then directly index the data.frame with those: ``` # How many rows in the data.frame? n <- nrow(mtcars) # Sample them mtcars[sample(x = n, size = n, replace = TRUE), ] ``` If you pass in the same integer twice, you get that row tw...
I use the 'matches' function from the grr package for this. ``` Indices <- unlist(matches(b.idx, data_xy$ID, list=TRUE)) b.data <- data_xy[Indices, ] ```
65,284,837
I have this pyspark script in Azure databricks notebook: ``` import argparse from pyspark.sql.types import StructType from pyspark.sql.types import StringType spark.conf.set( "fs.azure.account.key.gcdmchndev01c.dfs.core.chinacloudapi.cn", "<storag account key>" ) inputfile = "abfss://...
2020/12/14
[ "https://Stackoverflow.com/questions/65284837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/759352/" ]
tl;dr ===== ```java java.time.Duration.ofMillis( m ).toDaysPart() ``` Avoid legacy date-time types ============================ You are using terrible date-time classes that were supplanted years ago by the modern *java.time* classes. Never use `Calendar`, `GregorianCalendar`, `java.util.Date`, and such. `java.tim...
Use java.time also when you need javax.xml.datatype.Duration ------------------------------------------------------------ > > I am explicitly asking for javax.xml.datatype. It is not in my hand to > choose another datatype. > > > The conversion from `java.time.Duration` to a `javax.xml.datatype.Duration` fulfilli...
43,770,008
I need to run a large build script (bash commands) on a python script. I receive it as a large string and each line is splitted by a \n. So, I need to execute each line separately. At first, I tried to use [subprocess.Popen()](https://docs.python.org/2.7/library/subprocess.html) to execute them. But the problem is: af...
2017/05/03
[ "https://Stackoverflow.com/questions/43770008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3061426/" ]
What you want is definitely a little weird, but it's possible using pipes. ``` from subprocess import PIPE, Popen p = Popen(['bash'], stdin=PIPE, stdout=PIPE) p.stdin.write('echo hello world\n') print(p.stdout.readline()) # Check a return code p.stdin.write('echo $?\n') if p.stdout.readline().strip() ⩵ '0': print...
when calling a shell, the os starts a new process unless you have a shell interpreter in python all the way. the only possibility to do it in the same process is simulating all steps with python directly. the better way is to accept the limit, call an external process yourself and wait for the script to terminate con...
66,399,560
I have encountered some value error when input txt file into python. the txt file called "htwt.txt", and contain the below data: ``` Ht Wt 169.6 71.2 166.8 58.2 157.1 56 181.1 64.5 158.4 53 165.6 52.4 166.7 56.8 156.5 49.2 168.1 55.6 165.3 77.8 ``` When I typed the below code, and value errors are occurre...
2021/02/27
[ "https://Stackoverflow.com/questions/66399560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14620006/" ]
Pandas `read_csv` is enough ``` import pandas as pd import os os.chdir("/Users/James/Desktop/data/") df1 = pd.read_csv("htwt.txt",sep=' ') ``` Output: ``` >>> df1 Ht Wt 0 169.6 71.2 1 166.8 58.2 2 157.1 56.0 3 181.1 64.5 4 158.4 53.0 5 165.6 52.4 6 166.7 56.8 7 156.5 49.2 8 168.1 55.6 9 ...
The first row in your text file has alphanumeric characters: "Ht Wt". These characters cannot be converted to a floating point number. Remove the first row and you should be fine.
66,399,560
I have encountered some value error when input txt file into python. the txt file called "htwt.txt", and contain the below data: ``` Ht Wt 169.6 71.2 166.8 58.2 157.1 56 181.1 64.5 158.4 53 165.6 52.4 166.7 56.8 156.5 49.2 168.1 55.6 165.3 77.8 ``` When I typed the below code, and value errors are occurre...
2021/02/27
[ "https://Stackoverflow.com/questions/66399560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14620006/" ]
Like mentioned above pandas `read_csv` works, but if you insist on using `np.loadtxt` you can skip the first row which can't be converted to a float. You can do: ```py data1 = np.loadtxt("htwt.txt", skiprows=1) ```
The first row in your text file has alphanumeric characters: "Ht Wt". These characters cannot be converted to a floating point number. Remove the first row and you should be fine.
66,399,560
I have encountered some value error when input txt file into python. the txt file called "htwt.txt", and contain the below data: ``` Ht Wt 169.6 71.2 166.8 58.2 157.1 56 181.1 64.5 158.4 53 165.6 52.4 166.7 56.8 156.5 49.2 168.1 55.6 165.3 77.8 ``` When I typed the below code, and value errors are occurre...
2021/02/27
[ "https://Stackoverflow.com/questions/66399560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14620006/" ]
Pandas `read_csv` is enough ``` import pandas as pd import os os.chdir("/Users/James/Desktop/data/") df1 = pd.read_csv("htwt.txt",sep=' ') ``` Output: ``` >>> df1 Ht Wt 0 169.6 71.2 1 166.8 58.2 2 157.1 56.0 3 181.1 64.5 4 158.4 53.0 5 165.6 52.4 6 166.7 56.8 7 156.5 49.2 8 168.1 55.6 9 ...
```py #for skipping of the first line file1 = open("hwwt.txt") lines = file1.readlines()[1:] for line in lines: print(line.rstrip()) OUTPUT #otherwise you can use read_csv which is enough ```
66,399,560
I have encountered some value error when input txt file into python. the txt file called "htwt.txt", and contain the below data: ``` Ht Wt 169.6 71.2 166.8 58.2 157.1 56 181.1 64.5 158.4 53 165.6 52.4 166.7 56.8 156.5 49.2 168.1 55.6 165.3 77.8 ``` When I typed the below code, and value errors are occurre...
2021/02/27
[ "https://Stackoverflow.com/questions/66399560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14620006/" ]
Like mentioned above pandas `read_csv` works, but if you insist on using `np.loadtxt` you can skip the first row which can't be converted to a float. You can do: ```py data1 = np.loadtxt("htwt.txt", skiprows=1) ```
```py #for skipping of the first line file1 = open("hwwt.txt") lines = file1.readlines()[1:] for line in lines: print(line.rstrip()) OUTPUT #otherwise you can use read_csv which is enough ```
45,138,223
i have some sort of processes : ``` subprocess.Popen(['python2.7 script1.py')],shell=True) subprocess.Popen(['python2.7 script2.py')],shell=True) subprocess.Popen(['python2.7 script3.py')],shell=True) subprocess.Popen(['python2.7 script4.py')],shell=True) ``` i want to each one starts after the previous process comp...
2017/07/17
[ "https://Stackoverflow.com/questions/45138223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5121002/" ]
In my app the issue was caused by the templateUrl path being relative-to-code instead of absolute (relative-to-project). I had added the `module.component(...)` part along with the UpgradeComponent in one go, since the ngJS component was originally routed to directly. When I did so, I used the ng4 usual way of writing...
I faced the same issue while upgrading from angularJs 1.7 to Angular 9. To fix the issue i changed **`template`** to **`templateUrl`** in the angularJS component file.
31,318,739
I try to install flask-bcrypt via pip, but it raisis me this error: ``` error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) ``` I am currently running `Visual Studio 2015 RC` with `Python 3` on `Windows 10`. Any ideas how to solve this error? **Edit:** I tried to follow diffrent solutions a...
2015/07/09
[ "https://Stackoverflow.com/questions/31318739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5023926/" ]
Apparently the problem can be solved by installing py-bcrypt first. A win32 installer is available from the first comment to this reddit post: <http://www.reddit.com/r/flask/comments/15q5xj/anyone_have_a_working_version_of_flaskbcrypt_for/>
Here is another option, you need to setup Wheel package before you can import bcrypt ``` pip install wheel ``` ``` pip install bcrypt ``` ``` from flask_bcrypt import Bcrypt ```
15,077,627
TL;DR: I want a locals() that looks in a containing scope. Hi, all. I'm teaching a course on Python programming to some chemist friends, and I want to be sure I really understand scope. Consider: ``` def a(): x = 1 def b(): print(locals()) print(globals()) b() ``` Locals prints an emp...
2013/02/25
[ "https://Stackoverflow.com/questions/15077627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1911697/" ]
What is happening in your code is that when python see's the `x=3` line in your `b()` method, it is recreating `x` with a scope within the `b` function instead of using the `x` with it's scope in the `a` function. because your code then goes: ``` a = x+2 x = 3 ``` it is saying that you need to define the in...
The statement `print(locals())` refers to nearest enclosing scope, that is the `def b():` function. When calling `b()`, you will print the locals to this b function, and definition of x is outside the scope. ``` def a(): x = 1 def b(): print(locals()) print(globals()) b() print(locals(...
15,077,627
TL;DR: I want a locals() that looks in a containing scope. Hi, all. I'm teaching a course on Python programming to some chemist friends, and I want to be sure I really understand scope. Consider: ``` def a(): x = 1 def b(): print(locals()) print(globals()) b() ``` Locals prints an emp...
2013/02/25
[ "https://Stackoverflow.com/questions/15077627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1911697/" ]
The statement `print(locals())` refers to nearest enclosing scope, that is the `def b():` function. When calling `b()`, you will print the locals to this b function, and definition of x is outside the scope. ``` def a(): x = 1 def b(): print(locals()) print(globals()) b() print(locals(...
`python3 -c "help(locals)"` says this about the `locals` function: ``` locals() Return a dictionary containing the current scope's local variables. ``` That means that calling `locals()` in `b()` will only show you which variables are local to `b()`. That doesn't mean that `b()` can't see variables outside its s...
15,077,627
TL;DR: I want a locals() that looks in a containing scope. Hi, all. I'm teaching a course on Python programming to some chemist friends, and I want to be sure I really understand scope. Consider: ``` def a(): x = 1 def b(): print(locals()) print(globals()) b() ``` Locals prints an emp...
2013/02/25
[ "https://Stackoverflow.com/questions/15077627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1911697/" ]
What is happening in your code is that when python see's the `x=3` line in your `b()` method, it is recreating `x` with a scope within the `b` function instead of using the `x` with it's scope in the `a` function. because your code then goes: ``` a = x+2 x = 3 ``` it is saying that you need to define the in...
`python3 -c "help(locals)"` says this about the `locals` function: ``` locals() Return a dictionary containing the current scope's local variables. ``` That means that calling `locals()` in `b()` will only show you which variables are local to `b()`. That doesn't mean that `b()` can't see variables outside its s...
52,736,009
I have improved [my first Python program](https://stackoverflow.com/questions/51300358/python-hiding-json-empty-key-values-in-the-print-statement/51302419?noredirect=1) using f-strings instead of print: ``` .... js = json.loads(data) # here is an excerpt of my code: def publi(type): if type == 'ART': ret...
2018/10/10
[ "https://Stackoverflow.com/questions/52736009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10069047/" ]
You can use a conditional expression in an f-string as well: ``` return f"{nom} {'(%s)' % dat if dat else ''}. {tit}. {jou}. {'Pubmed: ' + pbm if pbm else ''}" ``` or you can simply use the `and` operator: ``` return f"{nom} {dat and '(%s)' % dat}. {tit}. {jou}. {pbm and 'Pubmed: ' + pbm}" ```
An easy but slightly fugly workaround is to have the formatting decorations in the string. ``` try: pbm = ". Pubmed: " + art['pubmedId_s'] except (KeyError, NameError): pbm = "" ... print(f"{nom} ({dat}). {tit}. {jou}{pbm}") ```
11,188,619
I have a string built from a few segments, which are not separated, but not overlap. This looks like that: ``` <python><regex><split> ``` I would like to split in into: ``` <python>, <regex>, <split> ``` I'm looking for the most efficient way to do that, and in the same time with as little code as possible. I cou...
2012/06/25
[ "https://Stackoverflow.com/questions/11188619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/531954/" ]
Try [re.findall](http://docs.python.org/library/re.html#re.findall): ``` import re your_string = '<python><regex><split>' parts = re.findall(r'<.+?>', your_string) print parts # ['<python>', '<regex>', '<split>'] ```
If your input data is really that simple, you can just use the `.replace()` method that's built into strings. ``` >>> '<python><regex><split>'.replace('><', '>, <') '<python>, <regex>, <split>' ``` If it's more complex, you should give a better example of input/expected output.
11,188,619
I have a string built from a few segments, which are not separated, but not overlap. This looks like that: ``` <python><regex><split> ``` I would like to split in into: ``` <python>, <regex>, <split> ``` I'm looking for the most efficient way to do that, and in the same time with as little code as possible. I cou...
2012/06/25
[ "https://Stackoverflow.com/questions/11188619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/531954/" ]
``` >>> re.sub(r'<(.+?)>',r'<\1>,','<python><regex><split>')[:-1] '<python>,<regex>,<split>' ```
If your input data is really that simple, you can just use the `.replace()` method that's built into strings. ``` >>> '<python><regex><split>'.replace('><', '>, <') '<python>, <regex>, <split>' ``` If it's more complex, you should give a better example of input/expected output.
11,188,619
I have a string built from a few segments, which are not separated, but not overlap. This looks like that: ``` <python><regex><split> ``` I would like to split in into: ``` <python>, <regex>, <split> ``` I'm looking for the most efficient way to do that, and in the same time with as little code as possible. I cou...
2012/06/25
[ "https://Stackoverflow.com/questions/11188619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/531954/" ]
Try [re.findall](http://docs.python.org/library/re.html#re.findall): ``` import re your_string = '<python><regex><split>' parts = re.findall(r'<.+?>', your_string) print parts # ['<python>', '<regex>', '<split>'] ```
``` >>> re.sub(r'<(.+?)>',r'<\1>,','<python><regex><split>')[:-1] '<python>,<regex>,<split>' ```
58,257,125
I have a form with an `<input type="file">`, and I'm getting an error when I try to save the uploaded image. The image is uploaded via POST XMLHttpRequest. I have no idea why this is happening. views.py: ``` import datetime from django.shortcuts import render from .models import TemporaryImage def upload_file(requ...
2019/10/06
[ "https://Stackoverflow.com/questions/58257125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8629753/" ]
You're only uploading a single file; you shouldn't be iterating over the file key. ``` def upload_file(request): key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}' file = request.FILES.get('file') if file: img = TemporaryImage(image=file, key=key) img.save() ```
i guess you have too try to save your image this way: ``` from django.core.files.base import ContentFile ... def upload_file(request): key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}' file = request.FILES.get('file') if file : img = TemporaryImage.objects.create(key=key) ...
1,312,524
I'm attempting to build a webpage that loads depending on the input provided. I'm having some trouble wrapping my head around event handling in javascript, basically. Coming from python, if I wanted to wait for a specific keyboard input before moving on to the next object to display, I would create a *while* loop and p...
2009/08/21
[ "https://Stackoverflow.com/questions/1312524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160854/" ]
For easier implementation of event handling I recommend you to use a library such as [Prototype](http://www.prototypejs.org/api/event) or [Jquery](http://docs.jquery.com/Events) (Note that both links take you to their respective Event handling documentation. In order to use them you have to keep in mind 3 things: * W...
you could attach an event listener to the window object like this ``` window.captureEvents(Event.KEYPRESS); window.onkeypress = output; function output(event) { alert("you pressed" + event.which); } ```
1,312,524
I'm attempting to build a webpage that loads depending on the input provided. I'm having some trouble wrapping my head around event handling in javascript, basically. Coming from python, if I wanted to wait for a specific keyboard input before moving on to the next object to display, I would create a *while* loop and p...
2009/08/21
[ "https://Stackoverflow.com/questions/1312524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160854/" ]
For easier implementation of event handling I recommend you to use a library such as [Prototype](http://www.prototypejs.org/api/event) or [Jquery](http://docs.jquery.com/Events) (Note that both links take you to their respective Event handling documentation. In order to use them you have to keep in mind 3 things: * W...
``` document.onkeydown = function(e) { //do what you need to do } ``` That's all it takes in javascript. You don't need to loop to wait for the event to happen, whenever the event occurs that function will be called, which in turn can call other functions, do whatever needs to be be done. Think of it as that instea...
1,312,524
I'm attempting to build a webpage that loads depending on the input provided. I'm having some trouble wrapping my head around event handling in javascript, basically. Coming from python, if I wanted to wait for a specific keyboard input before moving on to the next object to display, I would create a *while* loop and p...
2009/08/21
[ "https://Stackoverflow.com/questions/1312524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160854/" ]
In JavaScript, you give up control of the main loop. The browser runs the main loop and calls back down into your code when an event or timeout/interval occurs. You have to handle the event and then return so that the browser can get on with doing other things, firing events, and so on. So you cannot have a ‘listening...
you should not use such loops in javascript. basically you do not want to block the browser from doing its job. Thus you work with events (onkeyup/down). also instead of a loop you should use setTimeout if you want to wait a little and continue if something happened you can do sth like that: ``` <html> <script> var ...
1,312,524
I'm attempting to build a webpage that loads depending on the input provided. I'm having some trouble wrapping my head around event handling in javascript, basically. Coming from python, if I wanted to wait for a specific keyboard input before moving on to the next object to display, I would create a *while* loop and p...
2009/08/21
[ "https://Stackoverflow.com/questions/1312524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160854/" ]
In JavaScript, you give up control of the main loop. The browser runs the main loop and calls back down into your code when an event or timeout/interval occurs. You have to handle the event and then return so that the browser can get on with doing other things, firing events, and so on. So you cannot have a ‘listening...
you could attach an event listener to the window object like this ``` window.captureEvents(Event.KEYPRESS); window.onkeypress = output; function output(event) { alert("you pressed" + event.which); } ```