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
57,476,304
am getting below exception while trying to use multiprocessing with flask sqlalchemy. ``` sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically. [12/Aug/2019 18:09:52] "GET /api/resources HTTP/1.1" 500 - Traceback (most recent call last): File "/usr/local/lib/...
2019/08/13
[ "https://Stackoverflow.com/questions/57476304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8085047/" ]
I had the same issue. Following Sam's link helped me solve it. Before I had (not working): ``` from multiprocessing import Pool with Pool() as pool: pool.map(f, [arg1, arg2, ...]) ``` This works for me: ``` from multiprocessing import get_context with get_context("spawn").Pool() as pool: pool.map(f, [arg1,...
The answer from dibrovsd@github was really useful for me. If you are using a PREFORKING server like uwsgi or gunicorn, this would also help you. Post his comment here for your reference. > > Found. This happens when uwsgi (or gunicorn) starts when multiple workers are forked from the first process. > > If there i...
59,010,815
This is my code: I have used the find element by id RESULT\_RadioButton-7\_0, but I am getting the following error: ``` from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome(executable_path="/home/real/Desktop/Selenium_with_python/SeleniumProjects/chromedriver_linux64/c...
2019/11/23
[ "https://Stackoverflow.com/questions/59010815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11132456/" ]
Based on the page link you provided, it looks like your locator strategy is correct here. If you are getting an error—most likely `NoSuchElementException`, I am assuming it might have something to do with waiting for the page to load before attempting to find the element. Let's use the `ExpectedConditions` class to wai...
Unless you need to wait on the element (which doesn't seem necessary), you should be able to do the following: ``` element_to_click_or_whatever = driver.find_element_by_id('RESULT_RadioButton-7_0') ``` If you look at the source for [`find_element_by_id`](https://github.com/SeleniumHQ/selenium/blob/master/py/selenium...
59,010,815
This is my code: I have used the find element by id RESULT\_RadioButton-7\_0, but I am getting the following error: ``` from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome(executable_path="/home/real/Desktop/Selenium_with_python/SeleniumProjects/chromedriver_linux64/c...
2019/11/23
[ "https://Stackoverflow.com/questions/59010815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11132456/" ]
Please find the below answer which will help you to click on the *"Male"* radio button from your link. ``` from selenium.webdriver.common.by import By from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.we...
Unless you need to wait on the element (which doesn't seem necessary), you should be able to do the following: ``` element_to_click_or_whatever = driver.find_element_by_id('RESULT_RadioButton-7_0') ``` If you look at the source for [`find_element_by_id`](https://github.com/SeleniumHQ/selenium/blob/master/py/selenium...
3,631,556
I have found several topics with this title, but none of their solutions worked for me. I have two Django sites running on my server, both through Apache using different virtualhosts on two ports fed by my Nginx frontend (using for static files). One site uses MySql and runs just fine. The other uses Sqlite3 and gets t...
2010/09/02
[ "https://Stackoverflow.com/questions/3631556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438289/" ]
It could be that the server uses a different working directory than the `manage.py` command. Since you provide a relative path to the sqlite database, it is created in the working directory. Try it with an absolute path, e.g.: ``` 'NAME': '/tmp/mysite.sqlite3', ``` Remember that you have to either run `./manage.py s...
You have unapplied migrations. your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. python manage.py migrate This one worked for me.
3,631,556
I have found several topics with this title, but none of their solutions worked for me. I have two Django sites running on my server, both through Apache using different virtualhosts on two ports fed by my Nginx frontend (using for static files). One site uses MySql and runs just fine. The other uses Sqlite3 and gets t...
2010/09/02
[ "https://Stackoverflow.com/questions/3631556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438289/" ]
I had made some changes in Model which was not migrated to db properly. Using the command ``` manage.py makemigrations ``` fixed my problem. I hope this will help someone.
Add `'django.contrib.sessions',` line in INSTALLED\_APPS Run below commands from django shell ``` python manage.py makemigrations #check for changes python manage.py migrate #apply changes in DbSQLite python manage.py syncdb #sync with database ``` django\_session will appear in database with `(session_key, sessio...
3,631,556
I have found several topics with this title, but none of their solutions worked for me. I have two Django sites running on my server, both through Apache using different virtualhosts on two ports fed by my Nginx frontend (using for static files). One site uses MySql and runs just fine. The other uses Sqlite3 and gets t...
2010/09/02
[ "https://Stackoverflow.com/questions/3631556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438289/" ]
run this in command shell: ``` python manage.py migrate ``` This fixed for me.
it's simple just run the following command ``` python ./manage.py migrate python ./manage.py makemigrations AppName ```
3,631,556
I have found several topics with this title, but none of their solutions worked for me. I have two Django sites running on my server, both through Apache using different virtualhosts on two ports fed by my Nginx frontend (using for static files). One site uses MySql and runs just fine. The other uses Sqlite3 and gets t...
2010/09/02
[ "https://Stackoverflow.com/questions/3631556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438289/" ]
create a schema and add its name under NAME in 'databases' run manage.py syncdb
I found that's it all about migratinge. ``` python manage.py makemigrations APPNAME ``` As the answer ticked brakes when changed to a different virtual host such as windows to linux and vice versa
3,631,556
I have found several topics with this title, but none of their solutions worked for me. I have two Django sites running on my server, both through Apache using different virtualhosts on two ports fed by my Nginx frontend (using for static files). One site uses MySql and runs just fine. The other uses Sqlite3 and gets t...
2010/09/02
[ "https://Stackoverflow.com/questions/3631556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438289/" ]
run this in command shell: ``` python manage.py migrate ``` This fixed for me.
had the same issue, my resolution was to simply add 'django.contrib.comments' to INSTALLED\_APPS and run `./manage.py syncdb` again.
3,631,556
I have found several topics with this title, but none of their solutions worked for me. I have two Django sites running on my server, both through Apache using different virtualhosts on two ports fed by my Nginx frontend (using for static files). One site uses MySql and runs just fine. The other uses Sqlite3 and gets t...
2010/09/02
[ "https://Stackoverflow.com/questions/3631556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438289/" ]
I found that's it all about migratinge. ``` python manage.py makemigrations APPNAME ``` As the answer ticked brakes when changed to a different virtual host such as windows to linux and vice versa
Django documentation says "Once you have configured your installation, run manage.py migrate to install the single database table that stores session data." One possibility that i have come across is if the migration is ran for app first time before running migrations for the new project so just run migrations for the...
3,631,556
I have found several topics with this title, but none of their solutions worked for me. I have two Django sites running on my server, both through Apache using different virtualhosts on two ports fed by my Nginx frontend (using for static files). One site uses MySql and runs just fine. The other uses Sqlite3 and gets t...
2010/09/02
[ "https://Stackoverflow.com/questions/3631556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438289/" ]
In case it helps anyone else: the problem for me was that I didn't have the `django.contrib.sessions` app uncommented in my `INSTALLED_APPS`. Uncommenting it, and rerunning a `syncdb` did the trick.
When I run "manage.py runserver". If I run when I my current path is not in project dir.(such as python /somefolder/somefolder2/currentprj/manage.py runserver) I'll got the problem like you. solve by cd to project directory before run command.
3,631,556
I have found several topics with this title, but none of their solutions worked for me. I have two Django sites running on my server, both through Apache using different virtualhosts on two ports fed by my Nginx frontend (using for static files). One site uses MySql and runs just fine. The other uses Sqlite3 and gets t...
2010/09/02
[ "https://Stackoverflow.com/questions/3631556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438289/" ]
After made any changes in code, run the following commands ``` manage.py makemigrations manage.py migrate ``` it worked for me.
When I run "manage.py runserver". If I run when I my current path is not in project dir.(such as python /somefolder/somefolder2/currentprj/manage.py runserver) I'll got the problem like you. solve by cd to project directory before run command.
3,631,556
I have found several topics with this title, but none of their solutions worked for me. I have two Django sites running on my server, both through Apache using different virtualhosts on two ports fed by my Nginx frontend (using for static files). One site uses MySql and runs just fine. The other uses Sqlite3 and gets t...
2010/09/02
[ "https://Stackoverflow.com/questions/3631556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438289/" ]
I had made some changes in Model which was not migrated to db properly. Using the command ``` manage.py makemigrations ``` fixed my problem. I hope this will help someone.
And it may be a case you are getting this error because you forget to run query python manage.py migrate before creating super user
3,631,556
I have found several topics with this title, but none of their solutions worked for me. I have two Django sites running on my server, both through Apache using different virtualhosts on two ports fed by my Nginx frontend (using for static files). One site uses MySql and runs just fine. The other uses Sqlite3 and gets t...
2010/09/02
[ "https://Stackoverflow.com/questions/3631556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438289/" ]
In case it helps anyone else: the problem for me was that I didn't have the `django.contrib.sessions` app uncommented in my `INSTALLED_APPS`. Uncommenting it, and rerunning a `syncdb` did the trick.
Run this command in cmd : ``` Python ./manage.py migrate --all ``` It should come on your **db**
47,249,474
I'm working on a python GUI application, using tkinter, which displays text in Hebrew. On Windows (10, python 3.6, tkinter 8.6) Hebrew strings are displayed fine. On Linux (Ubuntu 14, both python 3.4 and 3.6, tkinter 8.6) Hebrew strings are displayed incorrectly - with no BiDi awareness - **am I missing something?*...
2017/11/12
[ "https://Stackoverflow.com/questions/47249474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1499700/" ]
I searched a bit and it is a known issue that tk/tcl uses Windows bidi support since about 2011, but their is apparently nothing equivalent on linux. Example: <https://wiki.tcl.tk/3158>. One answer to [Python/Tkinter: Using Tkinter for RTL (right-to-left) languages like Arabic/Hebrew?](https://stackoverflow.com/questio...
As on of the main authors of FriBidi and a contributor to the bidi text support in Gtk, I strongly suggest that you don't use TkInter for anything Hebrew or any other text other than Latin, Greek, or Cyrillic scripts. In theory you can rearrange the text ordering with the stand alone fribidi executable on on Linux, or ...
24,872,243
I created and ImageField model for my blog app in my "test" django project on my local server using sqllite. I have in my settings.py `MEDIA_ROOT = '/Users/me/Sites/python/djangotut/media/' MEDIA_ROOT_URL = 'http://127.0.0.1:8000/media/images/photos/'` and my blog/models.py ``` photo = models.ImageField(upload_...
2014/07/21
[ "https://Stackoverflow.com/questions/24872243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3142105/" ]
Use weight sum technique for layouts, so that the controls in your each line consumes the assigned percentage of space ( there won't be any need to put them in Grid or other UI Controls)
Use a nested ViewGroup: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_hori...
47,074,966
I am trying to create a simple test-scorer that grades your test and gives you a response - but a simple if/else function isn't running - Python - ``` testScore = input("Please enter your test score") if testScore <= 50: print "You didn't pass... sorry!" elif testScore >=60 and <=71: print "You passed, but you...
2017/11/02
[ "https://Stackoverflow.com/questions/47074966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You missed testScore in elif statement ``` testScore = input("Please enter your test score") if testScore <= 50: print "You didn't pass... sorry!" elif testScore >=60 and testScore<=71: print "You passed, but you can do better!" ```
The below shown way would be the better way of solving it, you always need to make the type conversion to integer when you are comparing/checking with numbers. > > input() in python would generally take as string > > > ``` testScore = input("Please enter your test score") if int(testScore) <= 50: print("Yo...
47,074,966
I am trying to create a simple test-scorer that grades your test and gives you a response - but a simple if/else function isn't running - Python - ``` testScore = input("Please enter your test score") if testScore <= 50: print "You didn't pass... sorry!" elif testScore >=60 and <=71: print "You passed, but you...
2017/11/02
[ "https://Stackoverflow.com/questions/47074966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You missed testScore in elif statement ``` testScore = input("Please enter your test score") if testScore <= 50: print "You didn't pass... sorry!" elif testScore >=60 and testScore<=71: print "You passed, but you can do better!" ```
You made some mistakes here: * You are comparing a string with an Integer `if testScore <= 50:` * You have missed the variable here --> `elif testScore >=60 and <=71:` I think those should be like this ---> * `if int(testScore) <= 50:` * `elif testScore >=60 and testScore<=71:` And try this, it is working ---> ```...
47,074,966
I am trying to create a simple test-scorer that grades your test and gives you a response - but a simple if/else function isn't running - Python - ``` testScore = input("Please enter your test score") if testScore <= 50: print "You didn't pass... sorry!" elif testScore >=60 and <=71: print "You passed, but you...
2017/11/02
[ "https://Stackoverflow.com/questions/47074966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The below shown way would be the better way of solving it, you always need to make the type conversion to integer when you are comparing/checking with numbers. > > input() in python would generally take as string > > > ``` testScore = input("Please enter your test score") if int(testScore) <= 50: print("Yo...
You made some mistakes here: * You are comparing a string with an Integer `if testScore <= 50:` * You have missed the variable here --> `elif testScore >=60 and <=71:` I think those should be like this ---> * `if int(testScore) <= 50:` * `elif testScore >=60 and testScore<=71:` And try this, it is working ---> ```...
66,697,840
I guess once upon a time, I was able to find this information by Googling but not this time. I believe each script file (e.g. my.py, run.sh, etc) could have the path to an executable that is supposed to parse & run the script file. For example, a bash script file `run.sh` could start with: ``` #!/bin/bash ``` Then,...
2021/03/18
[ "https://Stackoverflow.com/questions/66697840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7254686/" ]
If you want to pass json data with axios,you need to set `Content-Type`,here is a demo: axios(I use 1 to replace `${rockId}` to test): ``` var payload = "this is a test"; const request = axios.put(`/api/rocks/1/rockText`, JSON.stringify(payload), { headers: { 'Content-Type': 'application/json' } }); `...
The issue is that the model binder cannot resolve the payload. The reason is that it's expecting a string, but you're actually passing a json object with a property `rockText`. I would create a class to represent the json you're sending: ``` public class Rock { public string RockText { get; set; } } [HttpPut("{i...
29,956,883
I am fairly new to python. I want to create a program that can generate random numbers and write them to a file, but I am curious to as whether it is possible to write the output to a `.txt` file, but in individual lists. (*every time the program executes the script, it creates a new list*) Here is my code so far: `...
2015/04/30
[ "https://Stackoverflow.com/questions/29956883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4848614/" ]
ABout append or `a` - > > Opens a file for appending. The file pointer is at the end of the file > if the file exists. That is, the file is in the append mode. If the > file does not exist, it creates a new file for writing. > > > ``` def main(): import random data = open("Random.txt", "a" ) #open file...
If you read through the documentation for [open()](https://docs.python.org/2/library/functions.html#open) you'll note: > > Modes 'r+', 'w+' and 'a+' open the file for updating (reading and > writing); note that 'w+' truncates the file. Append 'b' to the mode to > open the file in binary mode, on systems that differ...
29,956,883
I am fairly new to python. I want to create a program that can generate random numbers and write them to a file, but I am curious to as whether it is possible to write the output to a `.txt` file, but in individual lists. (*every time the program executes the script, it creates a new list*) Here is my code so far: `...
2015/04/30
[ "https://Stackoverflow.com/questions/29956883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4848614/" ]
ABout append or `a` - > > Opens a file for appending. The file pointer is at the end of the file > if the file exists. That is, the file is in the append mode. If the > file does not exist, it creates a new file for writing. > > > ``` def main(): import random data = open("Random.txt", "a" ) #open file...
Exactly same like `letsc` answer, but formatted to be more "pythonic" Python 3 example, as was used print() in OP syntax. ```py import random def main(): with open("Random.txt", "a") as data: print('New run', file=data) numbers_count = int(input('How many random numbers?: ')) for i in range(numbers...
70,141,901
I have get\_Time function working fine but I would like to take the result it produces and store it int the "t" variable inside the function simple\_Interest function. Here is the code I have now. ``` y = input("Enter value for year: ") m = input("Enter value for month: ") p = input("Enter value for principle: ") r = ...
2021/11/28
[ "https://Stackoverflow.com/questions/70141901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17529617/" ]
Try this. ``` static int indexOfLastNumber(String s) { int removedLength = s.replaceFirst("\\d+\\D*$", "").length(); return s.length() == removedLength ? 0 : removedLength; } static void test(String s) { System.out.println(s + " : " + indexOfLastNumber(s)); } public static void main(String[] args) { ...
Note: the '1' is at index 9 in your String. If you don't want, it not necessary to use RegEx for this. A method like this should do the job: ```java public static int findLastNumbersIndex(String s) { boolean numberFound = false; boolean charBeforeNumberFound = false; //start at the end of the String int ind...
70,141,901
I have get\_Time function working fine but I would like to take the result it produces and store it int the "t" variable inside the function simple\_Interest function. Here is the code I have now. ``` y = input("Enter value for year: ") m = input("Enter value for month: ") p = input("Enter value for principle: ") r = ...
2021/11/28
[ "https://Stackoverflow.com/questions/70141901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17529617/" ]
Try this. ``` static int indexOfLastNumber(String s) { int removedLength = s.replaceFirst("\\d+\\D*$", "").length(); return s.length() == removedLength ? 0 : removedLength; } static void test(String s) { System.out.println(s + " : " + indexOfLastNumber(s)); } public static void main(String[] args) { ...
You can get it using Regex named group ```java public static int indexOfLastNumber(String text) { Pattern pattern = Pattern.compile("(\\d+)(?!.*\\d)"); Matcher matcher = pattern.matcher(text); return matcher.find() ? matcher.start() : -1; } ``` and I used test cases from @csalmhof answer, thanks to him ...
70,141,901
I have get\_Time function working fine but I would like to take the result it produces and store it int the "t" variable inside the function simple\_Interest function. Here is the code I have now. ``` y = input("Enter value for year: ") m = input("Enter value for month: ") p = input("Enter value for principle: ") r = ...
2021/11/28
[ "https://Stackoverflow.com/questions/70141901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17529617/" ]
Try this. ``` static int indexOfLastNumber(String s) { int removedLength = s.replaceFirst("\\d+\\D*$", "").length(); return s.length() == removedLength ? 0 : removedLength; } static void test(String s) { System.out.println(s + " : " + indexOfLastNumber(s)); } public static void main(String[] args) { ...
You can use a pattern with a capture group, and if there is a match you can use [public int start(int group)](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#start-int-) to get the start index of the capture group of the Matcher. ``` (\d)\d*\D*$ ``` * `(\d)` Capture a single digit in **group 1...
38,593,309
How do get logging from custom authorizer lambda function in API Gateway? I do not want to enable logging for API. I need logging from authorizer lambda function. I use a python lambda function and have prints in the code. I want to view the prints in **Cloud Watch** logs. But logs are not seen in cloud watch. I do not...
2016/07/26
[ "https://Stackoverflow.com/questions/38593309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2184930/" ]
I deleted the lambda function, IAM role, custom authorizer from API Gateway. Recreated all the above with the same settings and published the API. It started working and logging as expected. I do not know what was preventing earlier to log to cloud watch logs. Weird!!
When I set up my authorizer, I set a Lambda Event payload for a custom header, and I had neglected to set that header in my browser session. According to the documentation at *<https://docs.aws.amazon.com/apigateway/latest/developerguide/configure-api-gateway-lambda-authorization-with-console.html>*, section 9b, the AP...
838,991
I'm using pycurl to upload a file via put and python cgi script to receive the file on the server side. Essentially, the code on the server side is: ``` while True: next = sys.stdin.read(4096) if not next: break #.... write the buffer ``` This seems to work with text, but not binary files (I'm on win...
2009/05/08
[ "https://Stackoverflow.com/questions/838991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You need to run Python in binary mode. Change your CGI script from: ``` #!C:/Python25/python.exe ``` or whatever it says to: ``` #!C:/Python25/python.exe -u ``` Or you can do it programmatically like this: ``` msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) ``` before starting to read from `stdin`.
Use [mod\_wsgi](http://code.google.com/p/modwsgi/) instead of cgi. It will provide you an input file for the upload that's correctly opened.
40,762,324
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a\_points (Think of it like Team A) and vice versa (add one point to b\_points if val2 is larger.) If the two values are even I won't add any points to a\_points or b\_points. My problem is **test\_val wil...
2016/11/23
[ "https://Stackoverflow.com/questions/40762324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7017454/" ]
Global variables are generally a **bad idea**. Don't use them unless you really have to. The proper way to implement such counter is to use a class. ``` class MyCounter(object): def __init__(self): self.a_points = 0 self.b_points = 0 def test_val(self, val1, val2): if val1 > val2: ...
``` a_points=0 b_points=0 def test_val(a_points,b_points,val1,val2): global a_points global b_points if val1 > val2: a_points+=1 return a_points elif val2 > val1: b_points+=1 return b_points elif val1==val2: # If you pass, it won't return a_points nor b_po...
40,762,324
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a\_points (Think of it like Team A) and vice versa (add one point to b\_points if val2 is larger.) If the two values are even I won't add any points to a\_points or b\_points. My problem is **test\_val wil...
2016/11/23
[ "https://Stackoverflow.com/questions/40762324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7017454/" ]
``` a_points=0 b_points=0 def test_val(a_points,b_points,val1,val2): global a_points global b_points if val1 > val2: a_points+=1 return a_points elif val2 > val1: b_points+=1 return b_points elif val1==val2: # If you pass, it won't return a_points nor b_po...
Note that `a_points` and `b_points` shadow your global variables, since they are also passed as parameters. Any way, you are not returning value in case of equality, instead of `pass`, return a value ``` def test_val(a_points,b_points,val1,val2): if val1 > val2: a_points+=1 return a_points eli...
40,762,324
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a\_points (Think of it like Team A) and vice versa (add one point to b\_points if val2 is larger.) If the two values are even I won't add any points to a\_points or b\_points. My problem is **test\_val wil...
2016/11/23
[ "https://Stackoverflow.com/questions/40762324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7017454/" ]
Consider this: ``` a0=5 a1=6 a2=7 b0=3 b1=6 b2=10 a_points=0 b_points=0 def test_val(a_points, b_points, val1, val2): if val1 > val2: a_points += 1 return (a_points, b_points) elif val2 > val1: b_points += 1 return (a_points, b_points) elif val1==val2: return (a_poi...
Note that `a_points` and `b_points` shadow your global variables, since they are also passed as parameters. Any way, you are not returning value in case of equality, instead of `pass`, return a value ``` def test_val(a_points,b_points,val1,val2): if val1 > val2: a_points+=1 return a_points eli...
40,762,324
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a\_points (Think of it like Team A) and vice versa (add one point to b\_points if val2 is larger.) If the two values are even I won't add any points to a\_points or b\_points. My problem is **test\_val wil...
2016/11/23
[ "https://Stackoverflow.com/questions/40762324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7017454/" ]
Global variables are generally a **bad idea**. Don't use them unless you really have to. The proper way to implement such counter is to use a class. ``` class MyCounter(object): def __init__(self): self.a_points = 0 self.b_points = 0 def test_val(self, val1, val2): if val1 > val2: ...
This will simplify your code and logic. And make it work ;-) ``` a0=5 a1=6 a2=7 b0=3 b1=6 b2=10 a_points=0 b_points=0 def test_val(a_points,b_points,val1,val2): if val1 > val2: a_points+=1 elif val2 > val1: b_points+=1 return a_points, b_points a_points, b_points = test_val(a_points,b_p...
40,762,324
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a\_points (Think of it like Team A) and vice versa (add one point to b\_points if val2 is larger.) If the two values are even I won't add any points to a\_points or b\_points. My problem is **test\_val wil...
2016/11/23
[ "https://Stackoverflow.com/questions/40762324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7017454/" ]
Your problem is the that Python integers are immutable which in general is good to read about. A few more details can be found [here](https://stackoverflow.com/a/15148557/3727050). Now, regarding solutions: 1. As suggested, you can use `global` variables. Keep in mind this is usually considered bad practice cause it ...
Note that `a_points` and `b_points` shadow your global variables, since they are also passed as parameters. Any way, you are not returning value in case of equality, instead of `pass`, return a value ``` def test_val(a_points,b_points,val1,val2): if val1 > val2: a_points+=1 return a_points eli...
40,762,324
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a\_points (Think of it like Team A) and vice versa (add one point to b\_points if val2 is larger.) If the two values are even I won't add any points to a\_points or b\_points. My problem is **test\_val wil...
2016/11/23
[ "https://Stackoverflow.com/questions/40762324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7017454/" ]
``` print (test_val(a_points,b_points,1,2)) print (test_val(a_points,b_points,2,1)) print (test_val(a_points,b_points,2,2)) ``` This will give you a result: ``` 1 1 None ``` Hence you should not look at the function to return values, rather it updates the values of variables a\_points and b\_points. That is why in...
Note that `a_points` and `b_points` shadow your global variables, since they are also passed as parameters. Any way, you are not returning value in case of equality, instead of `pass`, return a value ``` def test_val(a_points,b_points,val1,val2): if val1 > val2: a_points+=1 return a_points eli...
40,762,324
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a\_points (Think of it like Team A) and vice versa (add one point to b\_points if val2 is larger.) If the two values are even I won't add any points to a\_points or b\_points. My problem is **test\_val wil...
2016/11/23
[ "https://Stackoverflow.com/questions/40762324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7017454/" ]
Consider this: ``` a0=5 a1=6 a2=7 b0=3 b1=6 b2=10 a_points=0 b_points=0 def test_val(a_points, b_points, val1, val2): if val1 > val2: a_points += 1 return (a_points, b_points) elif val2 > val1: b_points += 1 return (a_points, b_points) elif val1==val2: return (a_poi...
Your problem is the that Python integers are immutable which in general is good to read about. A few more details can be found [here](https://stackoverflow.com/a/15148557/3727050). Now, regarding solutions: 1. As suggested, you can use `global` variables. Keep in mind this is usually considered bad practice cause it ...
40,762,324
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a\_points (Think of it like Team A) and vice versa (add one point to b\_points if val2 is larger.) If the two values are even I won't add any points to a\_points or b\_points. My problem is **test\_val wil...
2016/11/23
[ "https://Stackoverflow.com/questions/40762324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7017454/" ]
Consider this: ``` a0=5 a1=6 a2=7 b0=3 b1=6 b2=10 a_points=0 b_points=0 def test_val(a_points, b_points, val1, val2): if val1 > val2: a_points += 1 return (a_points, b_points) elif val2 > val1: b_points += 1 return (a_points, b_points) elif val1==val2: return (a_poi...
``` print (test_val(a_points,b_points,1,2)) print (test_val(a_points,b_points,2,1)) print (test_val(a_points,b_points,2,2)) ``` This will give you a result: ``` 1 1 None ``` Hence you should not look at the function to return values, rather it updates the values of variables a\_points and b\_points. That is why in...
40,762,324
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a\_points (Think of it like Team A) and vice versa (add one point to b\_points if val2 is larger.) If the two values are even I won't add any points to a\_points or b\_points. My problem is **test\_val wil...
2016/11/23
[ "https://Stackoverflow.com/questions/40762324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7017454/" ]
Global variables are generally a **bad idea**. Don't use them unless you really have to. The proper way to implement such counter is to use a class. ``` class MyCounter(object): def __init__(self): self.a_points = 0 self.b_points = 0 def test_val(self, val1, val2): if val1 > val2: ...
Note that `a_points` and `b_points` shadow your global variables, since they are also passed as parameters. Any way, you are not returning value in case of equality, instead of `pass`, return a value ``` def test_val(a_points,b_points,val1,val2): if val1 > val2: a_points+=1 return a_points eli...
40,762,324
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a\_points (Think of it like Team A) and vice versa (add one point to b\_points if val2 is larger.) If the two values are even I won't add any points to a\_points or b\_points. My problem is **test\_val wil...
2016/11/23
[ "https://Stackoverflow.com/questions/40762324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7017454/" ]
Consider this: ``` a0=5 a1=6 a2=7 b0=3 b1=6 b2=10 a_points=0 b_points=0 def test_val(a_points, b_points, val1, val2): if val1 > val2: a_points += 1 return (a_points, b_points) elif val2 > val1: b_points += 1 return (a_points, b_points) elif val1==val2: return (a_poi...
This will simplify your code and logic. And make it work ;-) ``` a0=5 a1=6 a2=7 b0=3 b1=6 b2=10 a_points=0 b_points=0 def test_val(a_points,b_points,val1,val2): if val1 > val2: a_points+=1 elif val2 > val1: b_points+=1 return a_points, b_points a_points, b_points = test_val(a_points,b_p...
38,044,264
``` import pandas as pd import numpy as np from datetime import datetime, time # history file and batch size for processing. historyFilePath = 'EURUSD.SAMPLE.csv' batch_size = 5000 # function for date parsing dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f') # load data into a pandas iterator wi...
2016/06/26
[ "https://Stackoverflow.com/questions/38044264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5310427/" ]
This snippet of code should be what you want ``` # Create some fake data, similar to yours import pandas as pd s = pd.Series(pd.date_range('2014-08-17 17:00:01.1230000', periods=4)) print(s) print(type(s[0])) # Create a new series using just the date portion of the original data. # This effectively truncates the tim...
Here's how I did it with my data: ``` import pandas as pd import numpy as np rng = pd.date_range('1/1/2011', periods=72, freq='H') df = pd.DataFrame({"Data": np.random.randn(len(rng))}, index=rng) df["Time_Since_Midnight"] = (df.index - pd.to_datetime(df.index.date)) / np.timedelta64(1, 'ms') ``` By converting the ...
32,778,316
I am a vim user and edited a large python file using vim, everything is OK and it could run properly. Now I want to build a huge projects and I want to edit this python file in Intellij, but the indentation in intellij is completely wrong, and it's hard for me to edit one line by one line. Do you know what happened? (i...
2015/09/25
[ "https://Stackoverflow.com/questions/32778316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3390810/" ]
Yes, use [perfect forwarding](https://stackoverflow.com/questions/3582001/advantages-of-using-forward): ``` template <typename P> bool VectorList::put (P &&p) { //can't forward p here as it could move p and we need it later if (not_good_for_insert(p)) return false; // ... Node node = create_node(...
The ideal solution is to accept a universal reference, as [TartanLlama](https://stackoverflow.com/a/32778379/412080) advises. The ideal solution works if you can afford having the function definition in the header file. If your function definition cannot be exposed in the header (e.g. you employ Pimpl idiom or interfa...
32,778,316
I am a vim user and edited a large python file using vim, everything is OK and it could run properly. Now I want to build a huge projects and I want to edit this python file in Intellij, but the indentation in intellij is completely wrong, and it's hard for me to edit one line by one line. Do you know what happened? (i...
2015/09/25
[ "https://Stackoverflow.com/questions/32778316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3390810/" ]
Yes, use [perfect forwarding](https://stackoverflow.com/questions/3582001/advantages-of-using-forward): ``` template <typename P> bool VectorList::put (P &&p) { //can't forward p here as it could move p and we need it later if (not_good_for_insert(p)) return false; // ... Node node = create_node(...
With help of TartanLlama, I made following test code: ``` #include <utility> #include <iostream> #include <string> class MyClass{ public: MyClass(int s2) : s(s2){ std::cout << "c-tor " << s << std::endl; } MyClass(MyClass &&other) : s(other.s){ other.s = -1; std::cout << "move c-...
32,778,316
I am a vim user and edited a large python file using vim, everything is OK and it could run properly. Now I want to build a huge projects and I want to edit this python file in Intellij, but the indentation in intellij is completely wrong, and it's hard for me to edit one line by one line. Do you know what happened? (i...
2015/09/25
[ "https://Stackoverflow.com/questions/32778316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3390810/" ]
The ideal solution is to accept a universal reference, as [TartanLlama](https://stackoverflow.com/a/32778379/412080) advises. The ideal solution works if you can afford having the function definition in the header file. If your function definition cannot be exposed in the header (e.g. you employ Pimpl idiom or interfa...
With help of TartanLlama, I made following test code: ``` #include <utility> #include <iostream> #include <string> class MyClass{ public: MyClass(int s2) : s(s2){ std::cout << "c-tor " << s << std::endl; } MyClass(MyClass &&other) : s(other.s){ other.s = -1; std::cout << "move c-...
13,096,339
> > **Possible Duplicate:** > > [Python Question: Year and Day of Year to date?](https://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date) > > > Is there a method in Python to figure out which month a certain day of the year is in, e.g. today is day 299 (October 26th). I would l...
2012/10/27
[ "https://Stackoverflow.com/questions/13096339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1198201/" ]
``` print (datetime.datetime(2012,1,1) + datetime.timedelta(days=299)).month ``` Here's a little more usable version that returns both the month and day: ``` def get_month_day(year, day, one_based=False): if one_based: # if Jan 1st is 1 instead of 0 day -= 1 dt = datetime.datetime(year, 1, 1) + date...
I know of no such method, but you can do it like this: ``` print datetime.datetime.strptime('2012 299', '%Y %j').month ``` The above prints `10`
18,897,631
Guys i'm a newbie to the socket programming Following program is a client program which request a file from the server,But i'm getting the error as show below.. My input is GET index.html and the code is Can anyone solve this error...? ``` #!/usr/bin/env python import httplib import sys http_server = sys.argv[0] co...
2013/09/19
[ "https://Stackoverflow.com/questions/18897631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2795866/" ]
sys.argv[0] is not what you think it is. sys.argv[0] is the name of the program or script. The script's first argument is sys.argv[1].
The problem is that the first item in `sys.argv` is the script name. So your script is actually using your filename as the hostname. Change the 5th line to: ``` http_server = sys.argv[1] ``` [More info here.](http://docs.python.org/2/library/sys.html#sys.argv)
35,869,561
For a task I am to use ConditionalProbDist using LidstoneProbDist as the estimator, adding +0.01 to the sample count for each bin. I thought the following line of code would achieve this, but it produces a value error ``` fd = nltk.ConditionalProbDist(fd,nltk.probability.LidstoneProbDist,0.01) ``` I'm not sure how ...
2016/03/08
[ "https://Stackoverflow.com/questions/35869561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3255571/" ]
I found [the probability tutorial](http://www.nltk.org/howto/probability.html) on the NLTK website quite helpful as a reference. As mentioned in the answer above, using a lambda expression is a good idea, since the `ConditionalProbDist` will generate a frequency distribution (`nltk.FreqDist`) on the fly that's passed ...
You probably don't need this anymore as the question is very old, but still, you can pass LidstoneProbDist arguments to ConditionalProbDist with the help of lambda: ``` estimator = lambda fdist, bins: nltk.LidstoneProbDist(fdist, 0.01, bins) cpd = nltk.ConditionalProbDist(fd, estimator, bins) ```
68,293,321
In Python/Pandas, I want to create a column in my dataframe that shows the average number of days between customer visits at a venue. That is, for each customer, what are the average number of days between that customer's visits? Data looks like [Image of My Data](https://i.stack.imgur.com/NPFMU.png) Sorry I'm reall...
2021/07/07
[ "https://Stackoverflow.com/questions/68293321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14814034/" ]
On windows linking DLLs goes through a trampoline library (.lib file) which generates the right bindings. The convention for these is to prefix the function names with `__imp__` ([there is a related C++ answer](https://stackoverflow.com/a/5159395/1818675)). There is an [open issue](https://github.com/rust-lang/referen...
This is not my ideal answer, but it is how I solve the problem. What I'm still looking for is a way to get the Microsoft Linker (I believe) to output full verbosity in the rust build as it can do when doing C++ builds. There are options to the build that might trigger this but I haven't found them yet. That plus this ...
68,293,321
In Python/Pandas, I want to create a column in my dataframe that shows the average number of days between customer visits at a venue. That is, for each customer, what are the average number of days between that customer's visits? Data looks like [Image of My Data](https://i.stack.imgur.com/NPFMU.png) Sorry I'm reall...
2021/07/07
[ "https://Stackoverflow.com/questions/68293321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14814034/" ]
Like your [previous question](https://stackoverflow.com/q/68289334/1889329) you continue to ignore how compilers and linkers work. The two concepts you need to wrap your head around are these: * `LPCTSTR` is not a type. It is a preprocessor macro that expands to `char const*`, `wchar_t const*`, or `__wchar_t const*` i...
This is not my ideal answer, but it is how I solve the problem. What I'm still looking for is a way to get the Microsoft Linker (I believe) to output full verbosity in the rust build as it can do when doing C++ builds. There are options to the build that might trigger this but I haven't found them yet. That plus this ...
13,217,434
I'm planning to insert data to bellow CF that has compound keys. ``` CREATE TABLE event_attend ( event_id int, event_type varchar, event_user_id int, PRIMARY KEY (event_id, event_type) #compound keys... ); ``` But I can't insert data to this CF from python using cql. (http://code.google.com/a/apac...
2012/11/04
[ "https://Stackoverflow.com/questions/13217434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797779/" ]
It looks like you are trying to follow the example in: <http://pypi.python.org/pypi/cql/1.4.0> ``` import cql con = cql.connect(host, port, keyspace) cursor = con.cursor() cursor.execute("CQL QUERY", dict(kw='Foo', kw2='Bar', kwn='etc...')) ``` However, if you only need to insert one row (like in your question), jus...
For python 2.7, 3.3, 3.4, 3.5, and 3.6 for installation you can use ``` $ pip install cassandra-driver ``` And in python: ``` import cassandra ``` Documentation can be found under <https://datastax.github.io/python-driver/getting_started.html#passing-parameters-to-cql-queries>
41,351,431
Suppose I have the following numpy structured array: ``` In [250]: x Out[250]: array([(22, 2, -1000000000, 2000), (22, 2, 400, 2000), (22, 2, 804846, 2000), (44, 2, 800, 4000), (55, 5, 900, 5000), (55, 5, 1000, 5000), (55, 5, 8900, 5000), (55, 5, 11400, 5000), (33, 3, 14500, 3000), (33, 3, 40550,...
2016/12/27
[ "https://Stackoverflow.com/questions/41351431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2407231/" ]
This answer is a bit long and rambling. I started with what I knew from previous work on taking array views, and then tried to relate that to your functions. ================ In your case, all fields are 4 bytes long, both floats and ints. I can then view it as all ints or all floats: ``` In [1431]: x Out[1431]: ar...
hpaulj was right in saying that the problem is that the subset of the structured array is not contiguous. Interestingly, I figured out a way to make the array subset contiguous with the following function: ``` def view_fields(a, fields): """ `a` must be a numpy structured array. `names` is th...
62,980,784
I'm importing skimage in a python code. ``` from skimage.feature import greycomatrix, greycoprops ``` and I get this error > > ***No module named 'skimage'*** > > > Although I've already installed the scikit-image. Can anyone help ? This is the output of pip freeze [![enter image description here](https://i....
2020/07/19
[ "https://Stackoverflow.com/questions/62980784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8151481/" ]
You can use `pip install scikit-image`. Also, see the [recommended procedure](http://scikit-image.org/docs/dev/install.html).
If you are using python3 you should install the package using `python3 -m pip install package_name` or `pip3 install package_name` Using the `pip` binary will install the package for `python2` on some systems.
62,980,784
I'm importing skimage in a python code. ``` from skimage.feature import greycomatrix, greycoprops ``` and I get this error > > ***No module named 'skimage'*** > > > Although I've already installed the scikit-image. Can anyone help ? This is the output of pip freeze [![enter image description here](https://i....
2020/07/19
[ "https://Stackoverflow.com/questions/62980784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8151481/" ]
Since pip freeze indeed shows scikit-image as installed, I presume that you are launching your script/session using a different *environment* from the one listed by pip. You should make sure that you are in the same environment. Try `python -m pip freeze` and `python my_script.py` from the same terminal to make sure th...
You can use `pip install scikit-image`. Also, see the [recommended procedure](http://scikit-image.org/docs/dev/install.html).
62,980,784
I'm importing skimage in a python code. ``` from skimage.feature import greycomatrix, greycoprops ``` and I get this error > > ***No module named 'skimage'*** > > > Although I've already installed the scikit-image. Can anyone help ? This is the output of pip freeze [![enter image description here](https://i....
2020/07/19
[ "https://Stackoverflow.com/questions/62980784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8151481/" ]
Since pip freeze indeed shows scikit-image as installed, I presume that you are launching your script/session using a different *environment* from the one listed by pip. You should make sure that you are in the same environment. Try `python -m pip freeze` and `python my_script.py` from the same terminal to make sure th...
If you are using python3 you should install the package using `python3 -m pip install package_name` or `pip3 install package_name` Using the `pip` binary will install the package for `python2` on some systems.
69,465,428
I have a dictionary that looks like this: d = {key1 : {(key2,key3) : value}, ...} so it is a dictionary of dictionaries and in the inside dict the keys are tuples. I would like to get a triple nested dict: {key1 : {key2 : {key3 : value}, ...} I know how to do it with 2 loops and a condition: ``` new_d = {} for key1,...
2021/10/06
[ "https://Stackoverflow.com/questions/69465428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11930768/" ]
You could use the common trick for nesting dicts arbitrarily, using `collections.defaultdict`: ``` from collections import defaultdict tree = lambda: defaultdict(tree) new_d = tree() for k1, dct in d.items(): for (k2, k3), val in dct.items(): new_d[k1][k2][k3] = val ```
If I understand the problem correctly, for this case you can wrap all the looping up in a dict comprehension. This assumes that your data is unique: ```py data = {"key1": {("key2", "key3"): "val"}} {k: {keys[0]: {keys[1]: val}} for k,v in data.items() for keys, val in v.items()} ```
52,029,026
i am developing a python script for my telegram right now. The problem is: How do I know when my bot is added to a group? Is there an Event or something else for that? I want the Bot to send a message to the group he´s beeing added to which says hi and the functions he can. I dont know if any kind of handler is abl...
2018/08/26
[ "https://Stackoverflow.com/questions/52029026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4847304/" ]
Very roughly, you would need to do something like this: register an handler that filters only service messages about new chat members. Then check if the bot is one of the new chat members. ``` from telegram.ext import Updater, MessageHandler, Filters def new_member(bot, update): for member in update.message.new_c...
With callbacks (preferred) ========================== As of version 12, the preferred way to handle updates is via callbacks. To use them prior to version 13 state `use_context=True` in your `Updater`. Version 13 will have this as default. ``` from telegram.ext import Updater, MessageHandler, Filters def new_member(...
58,491,838
I was setting up to use Numba along with my AMD GPU. I started out with the most basic example available on their website, to calculate the value of Pi using the Monte-Carlo simulation. I made some changes to the code so that it can run on GPU first and then on the CPU. By doing this, I just wanted to compare the tim...
2019/10/21
[ "https://Stackoverflow.com/questions/58491838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8726146/" ]
I've reorganized your code a bit: ``` import numpy from numba import jit import random from timeit import default_timer as timer @jit(nopython=True) def monte_carlo_pi(nsamples): random.seed(0) acc = 0 for i in range(nsamples): x = random.random() y = random.random() if (x ** 2 + ...
> > **Q** : *Can anyone explain as to **why** this difference comes up?* > > > The availability and almost pedantic care of systematic use of re-setting the same state via the PRNG-of-choice **`.seed( aRepeatableExperimentSeedNUMBER )`**-method is the root-cause of all these surprises. Proper seeding works **if...
43,810,256
In DOS or batch file on windows we can access multiple consecutive files fieldgen1.txt, fieldgen2.txt, etc. as follows: ``` for /L %%i in (1,1,250) do ( copy fieldgen%%i.txt hk.ref Process the file and go to next file. ``` I have 250 files name like fieldgen1.ref, fieldgen2.ref, etc. Now I want to access one...
2017/05/05
[ "https://Stackoverflow.com/questions/43810256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6210264/" ]
Yes, you can access and process consecutive files in python ``` for i in range(1, 251): with open('fieldgen%s.txt' % i, 'r') as fp: lines = fp.readlines() # Do all your processing here ``` The code will loop and read each file. You can then do your processing once you have read all the lines. You...
You could do something like ``` import os files = os.listdir(".") for f in files: print (str(f)) ``` This will print all files and directories in the current run directory. Once you have the file name you can use that to process the content.
43,810,256
In DOS or batch file on windows we can access multiple consecutive files fieldgen1.txt, fieldgen2.txt, etc. as follows: ``` for /L %%i in (1,1,250) do ( copy fieldgen%%i.txt hk.ref Process the file and go to next file. ``` I have 250 files name like fieldgen1.ref, fieldgen2.ref, etc. Now I want to access one...
2017/05/05
[ "https://Stackoverflow.com/questions/43810256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6210264/" ]
Yes, you can access and process consecutive files in python ``` for i in range(1, 251): with open('fieldgen%s.txt' % i, 'r') as fp: lines = fp.readlines() # Do all your processing here ``` The code will loop and read each file. You can then do your processing once you have read all the lines. You...
I will consider using a string template. ``` for i in range(1,251): with open('fieldgen'+str(i)+'.txt', 'r') as fp: #Parsing your file ``` or you can use a List Comprehension: ``` files = [open('fieldgen'+str(i)+'.txt', 'r') for i in range(1,251)] for file in files: #Parsing your file ```
52,621,859
I am a new python learner and I want to write a program which reads a text file, and save value of a line contains "width" and print it. The file looks like: ``` width: 10128 nlines: 7101 ``` I am trying something like: ``` filename = "text.txtr" # open the file for reading filehandle ...
2018/10/03
[ "https://Stackoverflow.com/questions/52621859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9084038/" ]
Your approach to opening the file is not good, try using with statement whenever opening a file. Afterwards you can iterate over each line from the file and check if it contains width, and if it does you need to extract the number, which can be done using regex. See the code below. ``` import re filename = "text.txtr...
It's not returning results because of the line `if " width " in line:`. As you can see from your file, there is not a line with `" width "` in there, maybe you want: ``` if "width:" in line: #Do things ``` Also note there are a few issues with the code, for example that your program will never finish becasu...
52,621,859
I am a new python learner and I want to write a program which reads a text file, and save value of a line contains "width" and print it. The file looks like: ``` width: 10128 nlines: 7101 ``` I am trying something like: ``` filename = "text.txtr" # open the file for reading filehandle ...
2018/10/03
[ "https://Stackoverflow.com/questions/52621859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9084038/" ]
This is a simplified way based on Muhamad's one. What you need is: * open a file * read lines until you find "width" in one * extract the number that follows a colon * close the file * print the number It Python it can give ``` num = None # "sentinel" value with open(file) as fd: # with ...
It's not returning results because of the line `if " width " in line:`. As you can see from your file, there is not a line with `" width "` in there, maybe you want: ``` if "width:" in line: #Do things ``` Also note there are a few issues with the code, for example that your program will never finish becasu...
52,621,859
I am a new python learner and I want to write a program which reads a text file, and save value of a line contains "width" and print it. The file looks like: ``` width: 10128 nlines: 7101 ``` I am trying something like: ``` filename = "text.txtr" # open the file for reading filehandle ...
2018/10/03
[ "https://Stackoverflow.com/questions/52621859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9084038/" ]
Your approach to opening the file is not good, try using with statement whenever opening a file. Afterwards you can iterate over each line from the file and check if it contains width, and if it does you need to extract the number, which can be done using regex. See the code below. ``` import re filename = "text.txtr...
Fist of all no need to hold the file in a variable better directly open the file with `with open` method it takes care of file closing once read/write operation are done on the `self_exit()` function. So, you can start & clean your code like below: ``` with open("text.txtr", "r") as fh: lines = fh.readlines() ...
52,621,859
I am a new python learner and I want to write a program which reads a text file, and save value of a line contains "width" and print it. The file looks like: ``` width: 10128 nlines: 7101 ``` I am trying something like: ``` filename = "text.txtr" # open the file for reading filehandle ...
2018/10/03
[ "https://Stackoverflow.com/questions/52621859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9084038/" ]
This is a simplified way based on Muhamad's one. What you need is: * open a file * read lines until you find "width" in one * extract the number that follows a colon * close the file * print the number It Python it can give ``` num = None # "sentinel" value with open(file) as fd: # with ...
Fist of all no need to hold the file in a variable better directly open the file with `with open` method it takes care of file closing once read/write operation are done on the `self_exit()` function. So, you can start & clean your code like below: ``` with open("text.txtr", "r") as fh: lines = fh.readlines() ...
56,561,072
I'm trying to upgrade pip, and also install pywinusb, but I'm getting the error: "**UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 8: ordinal not in range(128)**". Pip upgrade: ``` PS C:\Python27> pip --version pip 18.1 from c:\python27\lib\site-packages\pip (python 2.7) PS C:\Python27> python ...
2019/06/12
[ "https://Stackoverflow.com/questions/56561072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6078511/" ]
Seems to be a specific issue concerning `Button` when contained in a `List` row. **Workaround**: ```swift List { HStack { Text("One").onTapGesture { print("One") } Text("Two").onTapGesture { print("Two") } } } ``` This yields the desired output. You can also use a `Group` instead of `Text` to have a so...
One of the differences with SwiftUI is that you are not creating specific instances of, for example UIButton, because you might be in a Mac app. With SwiftUI, you are requesting a button type thing. In this case since you are in a list row, the system gives you a full size, tap anywhere to trigger the action, button. ...
56,561,072
I'm trying to upgrade pip, and also install pywinusb, but I'm getting the error: "**UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 8: ordinal not in range(128)**". Pip upgrade: ``` PS C:\Python27> pip --version pip 18.1 from c:\python27\lib\site-packages\pip (python 2.7) PS C:\Python27> python ...
2019/06/12
[ "https://Stackoverflow.com/questions/56561072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6078511/" ]
Seems to be a specific issue concerning `Button` when contained in a `List` row. **Workaround**: ```swift List { HStack { Text("One").onTapGesture { print("One") } Text("Two").onTapGesture { print("Two") } } } ``` This yields the desired output. You can also use a `Group` instead of `Text` to have a so...
You need to create your own ButtonStyle: ``` struct MyButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .foregroundColor(.accentColor) .opacity(configuration.isPressed ? 0.5 : 1.0) } } struct IdentifiableString: Identifiable {...
56,561,072
I'm trying to upgrade pip, and also install pywinusb, but I'm getting the error: "**UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 8: ordinal not in range(128)**". Pip upgrade: ``` PS C:\Python27> pip --version pip 18.1 from c:\python27\lib\site-packages\pip (python 2.7) PS C:\Python27> python ...
2019/06/12
[ "https://Stackoverflow.com/questions/56561072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6078511/" ]
You need to use **[BorderlessButtonStyle()](https://developer.apple.com/documentation/swiftui/borderlessbuttonstyle)** or **PlainButtonStyle()**. ```swift List([1, 2, 3], id: \.self) { row in HStack { Button(action: { print("Button at \(row)") }) { Text("Row: \(row) Name: A") ...
Seems to be a specific issue concerning `Button` when contained in a `List` row. **Workaround**: ```swift List { HStack { Text("One").onTapGesture { print("One") } Text("Two").onTapGesture { print("Two") } } } ``` This yields the desired output. You can also use a `Group` instead of `Text` to have a so...
56,561,072
I'm trying to upgrade pip, and also install pywinusb, but I'm getting the error: "**UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 8: ordinal not in range(128)**". Pip upgrade: ``` PS C:\Python27> pip --version pip 18.1 from c:\python27\lib\site-packages\pip (python 2.7) PS C:\Python27> python ...
2019/06/12
[ "https://Stackoverflow.com/questions/56561072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6078511/" ]
One of the differences with SwiftUI is that you are not creating specific instances of, for example UIButton, because you might be in a Mac app. With SwiftUI, you are requesting a button type thing. In this case since you are in a list row, the system gives you a full size, tap anywhere to trigger the action, button. ...
You need to create your own ButtonStyle: ``` struct MyButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .foregroundColor(.accentColor) .opacity(configuration.isPressed ? 0.5 : 1.0) } } struct IdentifiableString: Identifiable {...
56,561,072
I'm trying to upgrade pip, and also install pywinusb, but I'm getting the error: "**UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 8: ordinal not in range(128)**". Pip upgrade: ``` PS C:\Python27> pip --version pip 18.1 from c:\python27\lib\site-packages\pip (python 2.7) PS C:\Python27> python ...
2019/06/12
[ "https://Stackoverflow.com/questions/56561072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6078511/" ]
You need to use **[BorderlessButtonStyle()](https://developer.apple.com/documentation/swiftui/borderlessbuttonstyle)** or **PlainButtonStyle()**. ```swift List([1, 2, 3], id: \.self) { row in HStack { Button(action: { print("Button at \(row)") }) { Text("Row: \(row) Name: A") ...
One of the differences with SwiftUI is that you are not creating specific instances of, for example UIButton, because you might be in a Mac app. With SwiftUI, you are requesting a button type thing. In this case since you are in a list row, the system gives you a full size, tap anywhere to trigger the action, button. ...
56,561,072
I'm trying to upgrade pip, and also install pywinusb, but I'm getting the error: "**UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 8: ordinal not in range(128)**". Pip upgrade: ``` PS C:\Python27> pip --version pip 18.1 from c:\python27\lib\site-packages\pip (python 2.7) PS C:\Python27> python ...
2019/06/12
[ "https://Stackoverflow.com/questions/56561072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6078511/" ]
You need to use **[BorderlessButtonStyle()](https://developer.apple.com/documentation/swiftui/borderlessbuttonstyle)** or **PlainButtonStyle()**. ```swift List([1, 2, 3], id: \.self) { row in HStack { Button(action: { print("Button at \(row)") }) { Text("Row: \(row) Name: A") ...
You need to create your own ButtonStyle: ``` struct MyButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .foregroundColor(.accentColor) .opacity(configuration.isPressed ? 0.5 : 1.0) } } struct IdentifiableString: Identifiable {...
45,906,144
I was trying to open stackoverflow and search for a query and then click the search button. almost everything went fine except I was not able to click submit button I encountered error > > WebDriverException: unknown error: Element ... is not clickable at point (608, 31). Other element would > receive the click: (S...
2017/08/27
[ "https://Stackoverflow.com/questions/45906144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7698247/" ]
``` <button type="submit" class="btn js-search-submit"> <svg role="icon" class="svg-icon iconSearch" width="18" height="18" viewBox="0 0 18 18"> <path d="..."></path> </svg> </button> ``` You are trying to click on the `svg`. That icon is not clickable, but the button is. So change the button selecto...
Click the element with right locator, your button locator is wrong. Other code is looking good try this ``` browser=webdriver.Chrome() browser.get("https://stackoverflow.com/questions/19035186/how-to-select-element-with-selenium-python-xpath") z=browser.find_element_by_css_selector(".f-input.js-search-field")#use .f...
45,906,144
I was trying to open stackoverflow and search for a query and then click the search button. almost everything went fine except I was not able to click submit button I encountered error > > WebDriverException: unknown error: Element ... is not clickable at point (608, 31). Other element would > receive the click: (S...
2017/08/27
[ "https://Stackoverflow.com/questions/45906144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7698247/" ]
``` <button type="submit" class="btn js-search-submit"> <svg role="icon" class="svg-icon iconSearch" width="18" height="18" viewBox="0 0 18 18"> <path d="..."></path> </svg> </button> ``` You are trying to click on the `svg`. That icon is not clickable, but the button is. So change the button selecto...
Use below code to click on submit button: ``` browser.find_element_by_css_selector(".btn.js-search-submit").click() ```
45,906,144
I was trying to open stackoverflow and search for a query and then click the search button. almost everything went fine except I was not able to click submit button I encountered error > > WebDriverException: unknown error: Element ... is not clickable at point (608, 31). Other element would > receive the click: (S...
2017/08/27
[ "https://Stackoverflow.com/questions/45906144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7698247/" ]
Use below code to click on submit button: ``` browser.find_element_by_css_selector(".btn.js-search-submit").click() ```
Click the element with right locator, your button locator is wrong. Other code is looking good try this ``` browser=webdriver.Chrome() browser.get("https://stackoverflow.com/questions/19035186/how-to-select-element-with-selenium-python-xpath") z=browser.find_element_by_css_selector(".f-input.js-search-field")#use .f...
16,647,186
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](https://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](https://stackoverflow.com/q...
2013/05/20
[ "https://Stackoverflow.com/questions/16647186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
You should call C from Python by writing a **ctypes** wrapper. Cython is for making python-like code run faster, ctypes is for making C functions callable from python. What you need to do is the following: 1. Write the C functions you want to use. (You probably did this already) 2. Create a shared object (.so, for lin...
It'll be easier to call C from python. Your scenario sounds weird - normally people write most of the code in python except for the processor-intensive portion, which is written in C. Is the two-dimensional FFT the computationally-intensive part of your code?
16,647,186
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](https://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](https://stackoverflow.com/q...
2013/05/20
[ "https://Stackoverflow.com/questions/16647186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
If I understand well, you have no preference for dialoging as c => python or like python => c. In that case I would recommend `Cython`. It is quite open to many kinds of manipulation, specially, in your case, calling a function that has been written in Python from C. Here is how it works ([`public api`](http://docs.cy...
It'll be easier to call C from python. Your scenario sounds weird - normally people write most of the code in python except for the processor-intensive portion, which is written in C. Is the two-dimensional FFT the computationally-intensive part of your code?
16,647,186
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](https://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](https://stackoverflow.com/q...
2013/05/20
[ "https://Stackoverflow.com/questions/16647186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
Well, here you are referring to two below things. 1. How to call c function within from python (Extending python) 2. How to call python function/script from C program (Embedding Python) **For #2 that is *'Embedding Python'*** You may use below code segment: ``` #include "python.h" int main(int argc, char *argv[]) ...
It'll be easier to call C from python. Your scenario sounds weird - normally people write most of the code in python except for the processor-intensive portion, which is written in C. Is the two-dimensional FFT the computationally-intensive part of your code?
16,647,186
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](https://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](https://stackoverflow.com/q...
2013/05/20
[ "https://Stackoverflow.com/questions/16647186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
It'll be easier to call C from python. Your scenario sounds weird - normally people write most of the code in python except for the processor-intensive portion, which is written in C. Is the two-dimensional FFT the computationally-intensive part of your code?
There's a nice and brief tutorial on this from [Digital Ocean here](https://www.digitalocean.com/community/tutorials/calling-c-functions-from-python). Short version: **1. Write C Code** You've already done this, so super short example: ``` #include <stdio.h> int addFive(int i) { return i + 5; } ``` **2. Cre...
16,647,186
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](https://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](https://stackoverflow.com/q...
2013/05/20
[ "https://Stackoverflow.com/questions/16647186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
You should call C from Python by writing a **ctypes** wrapper. Cython is for making python-like code run faster, ctypes is for making C functions callable from python. What you need to do is the following: 1. Write the C functions you want to use. (You probably did this already) 2. Create a shared object (.so, for lin...
If I understand well, you have no preference for dialoging as c => python or like python => c. In that case I would recommend `Cython`. It is quite open to many kinds of manipulation, specially, in your case, calling a function that has been written in Python from C. Here is how it works ([`public api`](http://docs.cy...
16,647,186
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](https://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](https://stackoverflow.com/q...
2013/05/20
[ "https://Stackoverflow.com/questions/16647186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
You should call C from Python by writing a **ctypes** wrapper. Cython is for making python-like code run faster, ctypes is for making C functions callable from python. What you need to do is the following: 1. Write the C functions you want to use. (You probably did this already) 2. Create a shared object (.so, for lin...
Well, here you are referring to two below things. 1. How to call c function within from python (Extending python) 2. How to call python function/script from C program (Embedding Python) **For #2 that is *'Embedding Python'*** You may use below code segment: ``` #include "python.h" int main(int argc, char *argv[]) ...
16,647,186
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](https://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](https://stackoverflow.com/q...
2013/05/20
[ "https://Stackoverflow.com/questions/16647186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
You should call C from Python by writing a **ctypes** wrapper. Cython is for making python-like code run faster, ctypes is for making C functions callable from python. What you need to do is the following: 1. Write the C functions you want to use. (You probably did this already) 2. Create a shared object (.so, for lin...
There's a nice and brief tutorial on this from [Digital Ocean here](https://www.digitalocean.com/community/tutorials/calling-c-functions-from-python). Short version: **1. Write C Code** You've already done this, so super short example: ``` #include <stdio.h> int addFive(int i) { return i + 5; } ``` **2. Cre...
16,647,186
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](https://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](https://stackoverflow.com/q...
2013/05/20
[ "https://Stackoverflow.com/questions/16647186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
If I understand well, you have no preference for dialoging as c => python or like python => c. In that case I would recommend `Cython`. It is quite open to many kinds of manipulation, specially, in your case, calling a function that has been written in Python from C. Here is how it works ([`public api`](http://docs.cy...
Well, here you are referring to two below things. 1. How to call c function within from python (Extending python) 2. How to call python function/script from C program (Embedding Python) **For #2 that is *'Embedding Python'*** You may use below code segment: ``` #include "python.h" int main(int argc, char *argv[]) ...
16,647,186
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](https://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](https://stackoverflow.com/q...
2013/05/20
[ "https://Stackoverflow.com/questions/16647186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
If I understand well, you have no preference for dialoging as c => python or like python => c. In that case I would recommend `Cython`. It is quite open to many kinds of manipulation, specially, in your case, calling a function that has been written in Python from C. Here is how it works ([`public api`](http://docs.cy...
There's a nice and brief tutorial on this from [Digital Ocean here](https://www.digitalocean.com/community/tutorials/calling-c-functions-from-python). Short version: **1. Write C Code** You've already done this, so super short example: ``` #include <stdio.h> int addFive(int i) { return i + 5; } ``` **2. Cre...
16,647,186
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](https://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](https://stackoverflow.com/q...
2013/05/20
[ "https://Stackoverflow.com/questions/16647186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
Well, here you are referring to two below things. 1. How to call c function within from python (Extending python) 2. How to call python function/script from C program (Embedding Python) **For #2 that is *'Embedding Python'*** You may use below code segment: ``` #include "python.h" int main(int argc, char *argv[]) ...
There's a nice and brief tutorial on this from [Digital Ocean here](https://www.digitalocean.com/community/tutorials/calling-c-functions-from-python). Short version: **1. Write C Code** You've already done this, so super short example: ``` #include <stdio.h> int addFive(int i) { return i + 5; } ``` **2. Cre...
50,874,453
Hi I am both new to python and q/KDB. I am using qpython to get results from a kdb database doing the following: ``` q = qconnection.QConnection(host=self.host, port=self.port, username=self.username, password=self.password) results = q.sync(query) ``` The result is a qtable. I need to convert the qtable into a stri...
2018/06/15
[ "https://Stackoverflow.com/questions/50874453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9946190/" ]
You might just want to string the table on the way out from kdb rather than in python. It'll get you what you want but the data won't be easy or efficient to deal with on the python side ``` q)csv 0: select from t "col1,col2" "a,1" "b,2" "c,3" ``` Try issuing `q.sync("csv 0: select from t")`
Converting the numerical columns to `string` can achieve the results you are after. ``` results = q.sync('t:([] 2?.z.d;2?.z.t;2?`3;p:2?100.);update string d, string t, string p from t') for item in results: t = () for x in item: t = t + (x.decode(),) print(t) ('2017.05.31', '16:46:10.161...
51,434,538
I am looking for a way to understand [ioloop in tornado](http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop), since I read the official doc several times, but can't understand it. Specifically, why it exists. ``` from tornado.concurrent import Future from tornado.httpclient import AsyncHTTPClient f...
2018/07/20
[ "https://Stackoverflow.com/questions/51434538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/887103/" ]
Rather to say it is `IOLoop`, maybe `EventLoop` is clearer for you to understand. `IOLoop.current()` doesn't really return an IO device but just a pure python event loop which is basically the same as `asyncio.get_event_loop()` or the underlying event loop in `nodejs`. The reason why you need event loop to just do a ...
> > I never heard of IO loop in javascript nodejs. > > > In node.js, the equivalent concept is the [event loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/). The node event loop is mostly invisible because all programs use it - it's what's running in between your callbacks. In Python, most ...
68,472,830
Today I have tried to send email with python: ``` import smtplib EMAIL_HOST = 'smtp.google.com' EMAIL_PORT = 587 EMAIL_FROM_LOGIN = '[email protected]' EMAIL_FROM_PASSWORD = 'password' MESSAGE = 'Hi!' EMAIL_TO_LOGIN = '[email protected]' print('starting...') server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) server.s...
2021/07/21
[ "https://Stackoverflow.com/questions/68472830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10872199/" ]
Enable lower security in your gmail account and fix your smtp address: '**smtp.gmail.com**': My sample: ``` import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText mail_content = 'Sample text' sender_address = 'xxx@xxx' sender_pass = 'xxxx' receiver_address = 'xxx@xxx' me...
--- Have you checked your code? there is **smtp.google.com** instead of **smtp.gmail.com**. Before executing the script --- 1. First of all, ensure that you logged in by that mail you are going to use to send mail in your script. 2. The second thing and important you must have on your [Less Security App](https://my...
46,143,079
I have wriiten a code for linear search in python language. The code is working fine for single digit numbers but its not working for double digit numbers or for numbers more than that. Here is my code. ``` def linear_search(x,sort_lst): i = 0 c= 0 for i in range(len(sort_lst)): if sort_lst[i] == x...
2017/09/10
[ "https://Stackoverflow.com/questions/46143079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8279672/" ]
`redux-promise` will handle only a promise but ``` { pass : Promise, fail : Promise, exempt : Promise, } ``` is not a promise. You have to convert it to single promise so that `redux-promise` can handle it. I think you need `Promise.all` for this task. Try something like: ``` const payload = Promise.all...
**Edit**: the answer of [Raghavgarg](https://stackoverflow.com/users/3439731/raghavgarg) is probably better if you already have logic that depends on your final payload (the one in the reducer) having the same structure as before. The middle-ware you use for promises probably expects the payload to be a promise, not a...
73,513,397
I am having issues with emails address and with a small correction, they are can be converted to valid email addresses. For Ex: ``` %[email protected], --- Not valid '[email protected], --- Not valid ([email protected]), --- Not valid ([email protected]), --- Not valid :[email protected], --- Not valid //24adifrmaes@micro...
2022/08/27
[ "https://Stackoverflow.com/questions/73513397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17867413/" ]
You can do this (I basically check if the elements in the email are alpha characters or a point, and remove them if not so): ``` emails = [ '[email protected]', '([email protected])', '([email protected])', ':[email protected]', '//[email protected]', '[email protected]' ] def correct...
Data clean-up is messy but I found the approach of defining a set of rules to be an easy way to manage this (order of the rules matters): ``` rules = [ lambda s: s.replace('%20', ' '), lambda s: s.strip(" ,'"), ] addresses = [ '%[email protected],', '[email protected],' ] for a in addresses:...
73,513,397
I am having issues with emails address and with a small correction, they are can be converted to valid email addresses. For Ex: ``` %[email protected], --- Not valid '[email protected], --- Not valid ([email protected]), --- Not valid ([email protected]), --- Not valid :[email protected], --- Not valid //24adifrmaes@micro...
2022/08/27
[ "https://Stackoverflow.com/questions/73513397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17867413/" ]
Data clean-up is messy but I found the approach of defining a set of rules to be an easy way to manage this (order of the rules matters): ``` rules = [ lambda s: s.replace('%20', ' '), lambda s: s.strip(" ,'"), ] addresses = [ '%[email protected],', '[email protected],' ] for a in addresses:...
This is actually a complicated one if you have more different test cases, ie., `[email protected].`, `,,[email protected].@_)` or `[email protected]@@@`. Still, you can strip them but it cannot be limited to what is to be stripped at the end and beginning. **Note:** Email addresses with numbers and \_ are valid too. ``` ...
73,513,397
I am having issues with emails address and with a small correction, they are can be converted to valid email addresses. For Ex: ``` %[email protected], --- Not valid '[email protected], --- Not valid ([email protected]), --- Not valid ([email protected]), --- Not valid :[email protected], --- Not valid //24adifrmaes@micro...
2022/08/27
[ "https://Stackoverflow.com/questions/73513397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17867413/" ]
You can do this (I basically check if the elements in the email are alpha characters or a point, and remove them if not so): ``` emails = [ '[email protected]', '([email protected])', '([email protected])', ':[email protected]', '//[email protected]', '[email protected]' ] def correct...
This is actually a complicated one if you have more different test cases, ie., `[email protected].`, `,,[email protected].@_)` or `[email protected]@@@`. Still, you can strip them but it cannot be limited to what is to be stripped at the end and beginning. **Note:** Email addresses with numbers and \_ are valid too. ``` ...
20,262,552
I have an embedded system using a python interface. Currently the system is using a (system-local) XML-file to persist data in case the system gets turned off. But normally the system is running the entire time. When the system starts, the XML-file is read in and information is stored in python-objects. The information...
2013/11/28
[ "https://Stackoverflow.com/questions/20262552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2127432/" ]
You can use [FileVersionInfo](http://msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo%28v=vs.110%29.aspx) class to get the version of another program. ``` FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); Console.WriteLine("File: " + ...
If I'm not wrong, you are trying to fetch the version number of a file using c#. You can try the below example: ``` using System; using System.IO; using System.Diagnostics; class Class1 { public static void Main(string[] args) { // Get the file version for the notepad. // Use either of the two foll...
20,262,552
I have an embedded system using a python interface. Currently the system is using a (system-local) XML-file to persist data in case the system gets turned off. But normally the system is running the entire time. When the system starts, the XML-file is read in and information is stored in python-objects. The information...
2013/11/28
[ "https://Stackoverflow.com/questions/20262552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2127432/" ]
You can use [FileVersionInfo](http://msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo%28v=vs.110%29.aspx) class to get the version of another program. ``` FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); Console.WriteLine("File: " + ...
You can try exploring File, FileInfo and FileVersionInfo classes to get the required details.
9,598,739
I have two versions of python installed on Win7. (Python 2.5 and Python 2.7). These are located in 'C:/Python25' and 'C:/Python27' respectively. I am trying to run a file using Python 2.5 but by default Cygwin picks up 2.7. How do I change which version Cygwin uses?
2012/03/07
[ "https://Stackoverflow.com/questions/9598739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145456/" ]
The fast way is to reorder your $PATH so that 2.5 is picked up first. The correct way is to use virtualenv to create a jail environment that's specific to a python version.
As an addition to Bon's post, if you're not sand-boxing your not doing it right. Why would you want to put your global install of Python at risk of anything? With Virtualenv you can select which Python interpreter is used for that particular sand-box. Virtualenv and Virtualenvwrapper(or custom solution) are two of the ...
9,598,739
I have two versions of python installed on Win7. (Python 2.5 and Python 2.7). These are located in 'C:/Python25' and 'C:/Python27' respectively. I am trying to run a file using Python 2.5 but by default Cygwin picks up 2.7. How do I change which version Cygwin uses?
2012/03/07
[ "https://Stackoverflow.com/questions/9598739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145456/" ]
The fast way is to reorder your $PATH so that 2.5 is picked up first. The correct way is to use virtualenv to create a jail environment that's specific to a python version.
Open the Cygwin terminal ``` $cd /usr/bin $ls -l | grep "python ->" lrwxrwxrwx 1 XXXX Domain Users XXXXX python -> etc/alternatives/python $ python Python 3.8.10 (default, May 20 2021, 11:41:59) [GCC 10.2.0] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> ...
9,598,739
I have two versions of python installed on Win7. (Python 2.5 and Python 2.7). These are located in 'C:/Python25' and 'C:/Python27' respectively. I am trying to run a file using Python 2.5 but by default Cygwin picks up 2.7. How do I change which version Cygwin uses?
2012/03/07
[ "https://Stackoverflow.com/questions/9598739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145456/" ]
Open the Cygwin terminal ``` $cd /usr/bin $ls -l | grep "python ->" lrwxrwxrwx 1 XXXX Domain Users XXXXX python -> etc/alternatives/python $ python Python 3.8.10 (default, May 20 2021, 11:41:59) [GCC 10.2.0] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> ...
As an addition to Bon's post, if you're not sand-boxing your not doing it right. Why would you want to put your global install of Python at risk of anything? With Virtualenv you can select which Python interpreter is used for that particular sand-box. Virtualenv and Virtualenvwrapper(or custom solution) are two of the ...
38,967,402
I'm trying to multiply two pandas dataframes with each other. Specifically, I want to multiply every column with every column of the other df. The dataframes are one-hot encoded, so they look like this: ``` col_1, col_2, col_3, ... 0 1 0 1 0 0 0 0 1 ... ``` I could just iterat...
2016/08/16
[ "https://Stackoverflow.com/questions/38967402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3950550/" ]
``` # use numpy to get a pair of indices that map out every # combination of columns from df_1 and columns of df_2 pidx = np.indices((df_1.shape[1], df_2.shape[1])).reshape(2, -1) # use pandas MultiIndex to create a nice MultiIndex for # the final output lcol = pd.MultiIndex.from_product([df_1.columns, df_2.columns], ...
You can use numpy. Consider this example code, I did modify the variable names, but `Test1()` is essentially your code. I didn't bother create the correct column names in that function though: ``` import pandas as pd import numpy as np A = [[1,0,1,1],[0,1,1,0],[0,1,0,1]] B = [[0,0,1,0],[1,0,1,0],[1,1,0,0],[1,0,0,1],...
38,967,402
I'm trying to multiply two pandas dataframes with each other. Specifically, I want to multiply every column with every column of the other df. The dataframes are one-hot encoded, so they look like this: ``` col_1, col_2, col_3, ... 0 1 0 1 0 0 0 0 1 ... ``` I could just iterat...
2016/08/16
[ "https://Stackoverflow.com/questions/38967402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3950550/" ]
You can multiply along the `index` axis your first `df` with each column of the second `df`, this is the ***fastest method*** for big datasets (see below): ``` df = pd.concat([df_1.mul(col[1], axis="index") for col in df_2.iteritems()], axis=1) # Change the name of the columns df.columns = ["_".join([i, j]) for j in d...
You can use numpy. Consider this example code, I did modify the variable names, but `Test1()` is essentially your code. I didn't bother create the correct column names in that function though: ``` import pandas as pd import numpy as np A = [[1,0,1,1],[0,1,1,0],[0,1,0,1]] B = [[0,0,1,0],[1,0,1,0],[1,1,0,0],[1,0,0,1],...
38,967,402
I'm trying to multiply two pandas dataframes with each other. Specifically, I want to multiply every column with every column of the other df. The dataframes are one-hot encoded, so they look like this: ``` col_1, col_2, col_3, ... 0 1 0 1 0 0 0 0 1 ... ``` I could just iterat...
2016/08/16
[ "https://Stackoverflow.com/questions/38967402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3950550/" ]
``` # use numpy to get a pair of indices that map out every # combination of columns from df_1 and columns of df_2 pidx = np.indices((df_1.shape[1], df_2.shape[1])).reshape(2, -1) # use pandas MultiIndex to create a nice MultiIndex for # the final output lcol = pd.MultiIndex.from_product([df_1.columns, df_2.columns], ...
You can multiply along the `index` axis your first `df` with each column of the second `df`, this is the ***fastest method*** for big datasets (see below): ``` df = pd.concat([df_1.mul(col[1], axis="index") for col in df_2.iteritems()], axis=1) # Change the name of the columns df.columns = ["_".join([i, j]) for j in d...
23,237,692
I use PyDev in Eclipse and have a custom source path for my Python project: *src/main/python*/. The path is added to the PythonPath. Now, i want to use the library pyMIR: <https://github.com/jsawruk/pymir>, which doesn't has any install script. So I downloaded it and and included it direclty into my project as a Pydev...
2014/04/23
[ "https://Stackoverflow.com/questions/23237692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I tried to download and install the pymir package. There is one project structure that works for me: ``` project/music/ project/music/pymir/ project/music/pymir/AudioFile project/music/pymir/... project/music/audio_files/01.wav project/music/test.py ``` The test.py: ``` import numpy from pymir import AudioFile file...
add **"\_\_init\_\_.py"** empty file in base folder location and it works
23,237,692
I use PyDev in Eclipse and have a custom source path for my Python project: *src/main/python*/. The path is added to the PythonPath. Now, i want to use the library pyMIR: <https://github.com/jsawruk/pymir>, which doesn't has any install script. So I downloaded it and and included it direclty into my project as a Pydev...
2014/04/23
[ "https://Stackoverflow.com/questions/23237692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I tried to download and install the pymir package. There is one project structure that works for me: ``` project/music/ project/music/pymir/ project/music/pymir/AudioFile project/music/pymir/... project/music/audio_files/01.wav project/music/test.py ``` The test.py: ``` import numpy from pymir import AudioFile file...
1. unzip the folder `pymir` to `site-packages`, make sure the path like ``` site-packages\pymir site-packages\pymir\AudioFile.py site-packages\pymir\Frame.py site-packages\pymir\... ``` 2. comment the content of the file `__init__.py` ``` #from AudioFile import AudioFile #from Frame import Frame #from Spectrum impor...
20,154,490
I am trying to use `RotatingHandler` for our logging purpose in Python. I have kept backup files as 500 which means it will create maximum of 500 files I guess and the size that I have set is 2000 Bytes (not sure what is the recommended size limit is). If I run my below code, it doesn't log everything into a file. I w...
2013/11/22
[ "https://Stackoverflow.com/questions/20154490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
> > It doesn't print out INFO, DEBUG message into the file somehow.. Any > thoughts why it is not working out? > > > you don't seem to set a loglevel, so the default (warning) is used from <http://docs.python.org/2/library/logging.html> : > > Note that the root logger is created with level WARNING. > > > a...
I know, it is very late ,but I just got same error, and while searching that are I got your problem. I am able to resolve my problem, and I thought it might be helpful for some other user also : you have created a logger object and trying to access **my\_logger.config.fileConfig('log.conf')** which is wrong you should...
20,420,937
I have python script that set the IP4 address for my wireless and wired interfaces. So far, I use `subprocess` command like : ``` subprocess.call(["ip addr add local 192.168.1.2/24 broadcast 192.168.1.255 dev wlan0"]) ``` How can I set the IP4 address of an interface using python libraries? and if there is any way ...
2013/12/06
[ "https://Stackoverflow.com/questions/20420937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2468276/" ]
Set an address via the older `ioctl` interface: ``` import socket, struct, fcntl SIOCSIFADDR = 0x8916 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def setIpAddr(iface, ip): bin_ip = socket.inet_aton(ip) ifreq = struct.pack('16sH2s4s8s', iface, socket.AF_INET, '\x00' * 2, bin_ip, '\x00' * 8) f...
You have multiple options to do it from your python program. One could use the `ip` tool like you showed. While this is not the best option at all this usualy does the job while being a little bit slow and arkward to program. Another way would be to do the things `ip` does on your own by using the kernel netlink inte...
20,420,937
I have python script that set the IP4 address for my wireless and wired interfaces. So far, I use `subprocess` command like : ``` subprocess.call(["ip addr add local 192.168.1.2/24 broadcast 192.168.1.255 dev wlan0"]) ``` How can I set the IP4 address of an interface using python libraries? and if there is any way ...
2013/12/06
[ "https://Stackoverflow.com/questions/20420937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2468276/" ]
With [pyroute2](https://github.com/svinota/pyroute2).IPRoute: ``` from pyroute2 import IPRoute ip = IPRoute() index = ip.link_lookup(ifname='em1')[0] ip.addr('add', index, address='192.168.0.1', mask=24) ip.close() ``` With [pyroute2](https://github.com/svinota/pyroute2).IPDB: ``` from pyroute2 import IPDB ip = IPD...
You have multiple options to do it from your python program. One could use the `ip` tool like you showed. While this is not the best option at all this usualy does the job while being a little bit slow and arkward to program. Another way would be to do the things `ip` does on your own by using the kernel netlink inte...
48,756,249
I have 2 models `Task` and `TaskImage` which is a collection of images belonging to `Task` object. What I want is to be able to add multiple images to my `Task` object, but I can only do it using 2 models. Currently, when I add images, it doesn't let me upload them and save new objects. **settings.py** ``` MEDIA_ROO...
2018/02/12
[ "https://Stackoverflow.com/questions/48756249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4729764/" ]
**Description for the issue** The origin of the exception was a `KeyError`, because of this statement ``` images_data = validated_data.pop('images') ``` This is because the validated data has no key `images`. This means the images input doesn't validate the image inputs from postman. Django post request store `In...
You have `read_only` set to true in `TaskImageSerializer` nested field. So there will be no validated\_data there.
7,461,570
I'm trying to build the most recent version of OpenCV on a minimal enough VPS but am running into trouble with CMake. I'm not familiar with CMake so I'm finding it difficult to interpret the log output and thus how to proceed to debug the problem. From the command line (x11 isn't installed) and within devel/OpenCV/-2....
2011/09/18
[ "https://Stackoverflow.com/questions/7461570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413797/" ]
Check your CMake version. Support for `set_property(CACHE ... )` was implemented in 2.8.0. If upgrading CMake is not an option for you - I guess it's safe to comment line #44. It seems to be used to create values for drop-down list in GUI. <http://www.kitware.com/blog/home/post/82> <http://blog.bethcodes.com/cmake-...
I've experienced lots of error building opencv that were caused by the wrong version of OpenCV. I successfully built opencv 3.0 using cmake 3.0 (though cmake 2.6 did not work for me). Then when I found I had to downgrade to opencv 2.4.9 I had to go back to my system's default cmake 2.6, as cmake 3.0 did not work. The f...