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 |
|---|---|---|---|---|---|
41,883,254 | I am trying to process a form in django/python using the following code.
---
home.html:
```html
<form action="{% url 'home:submit' %}" method='post'>
```
---
views.py:
```py
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
... | 2017/01/26 | [
"https://Stackoverflow.com/questions/41883254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169431/"
] | For Django 3.0, if you're handling your urls within the app and using `include` with `path`, in your `project/urls.py`:
```
urlpatterns = [
path(os.getenv('ADMIN_PATH'), admin.site.urls),
path('', include('my_simple_blog.urls', namespace='my_simple_blog')),
path('account/', include('account.urls', namespac... | Maybe someone will find this suggestion helpful.
Go to your applications `urls.py` and type this before the urlpatterns:
```
app_name = 'Your app name'
``` |
41,883,254 | I am trying to process a form in django/python using the following code.
---
home.html:
```html
<form action="{% url 'home:submit' %}" method='post'>
```
---
views.py:
```py
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
... | 2017/01/26 | [
"https://Stackoverflow.com/questions/41883254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169431/"
] | In your main project, open url.py first. Then check, there should be app\_name declared at first. If it is not, declare it.
For example, my app name is user info which is declared in url.py
```
app_name = "userinfo"
urlpatterns = [
url(r'home/', views.home, name='home'),
url(r'register/', views.registration,... | Probably 2 things could be a root cause,
in app/urls.py do include as below
```
app_name = 'required_name'
```
and in project urls.py also include the app\_name
```
url(r'^required_name/$',views.home,name='required_name'),
```
Check: register app in settings.py INSTALLED\_APPS |
41,883,254 | I am trying to process a form in django/python using the following code.
---
home.html:
```html
<form action="{% url 'home:submit' %}" method='post'>
```
---
views.py:
```py
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
... | 2017/01/26 | [
"https://Stackoverflow.com/questions/41883254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169431/"
] | You should just change you action url in your template:
```
<form action="{% url 'submit' %} "method='post'>
```
---
On the note of url namespaces...
In order to be able to call urls using `home` namespace you should have in your main urls.py file line something like:
for django 1.x:
```
url(r'^', include('home.... | I also faced the same issue.
it is fixed now by adding
```
app_name = "<name of your app>"
```
in app/urls.py |
41,883,254 | I am trying to process a form in django/python using the following code.
---
home.html:
```html
<form action="{% url 'home:submit' %}" method='post'>
```
---
views.py:
```py
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
... | 2017/01/26 | [
"https://Stackoverflow.com/questions/41883254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169431/"
] | In your main project, open url.py first. Then check, there should be app\_name declared at first. If it is not, declare it.
For example, my app name is user info which is declared in url.py
```
app_name = "userinfo"
urlpatterns = [
url(r'home/', views.home, name='home'),
url(r'register/', views.registration,... | For the ***namespace error***,
Make sure you have linked the app's url in the main urls.py file
```
path('app_name/',include('app_name.urls'))
```
also in the urls.py of your app,make sure you mention the app's name as
```
app_name='app_name'
```
Also make sure you have registered the app's name on your installed... |
41,883,254 | I am trying to process a form in django/python using the following code.
---
home.html:
```html
<form action="{% url 'home:submit' %}" method='post'>
```
---
views.py:
```py
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
... | 2017/01/26 | [
"https://Stackoverflow.com/questions/41883254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169431/"
] | tag name must be unique in the `urls.py` file inside your application package inside the project! it is important for the template tagging to route whats what and where.
now [1] inside the `urls.py` file you need to declare the variable `appName` and give it the unique value. for example `appName = "myApp";` in your c... | Check your urls.py
```
urlpatterns = [
re_path(r'^submit/expense/$', views.submit_expense, name='submit_expense'),
re_path(r'^submit/income/$', views.submit_income, name='submit_income'),
re_path(r'^register/$', views.register, name='register'),
]
```
then open template.html
put for example register reg... |
41,883,254 | I am trying to process a form in django/python using the following code.
---
home.html:
```html
<form action="{% url 'home:submit' %}" method='post'>
```
---
views.py:
```py
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
... | 2017/01/26 | [
"https://Stackoverflow.com/questions/41883254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169431/"
] | I also faced the same issue.
it is fixed now by adding
```
app_name = "<name of your app>"
```
in app/urls.py | For Django 3.0, if you're handling your urls within the app and using `include` with `path`, in your `project/urls.py`:
```
urlpatterns = [
path(os.getenv('ADMIN_PATH'), admin.site.urls),
path('', include('my_simple_blog.urls', namespace='my_simple_blog')),
path('account/', include('account.urls', namespac... |
41,883,254 | I am trying to process a form in django/python using the following code.
---
home.html:
```html
<form action="{% url 'home:submit' %}" method='post'>
```
---
views.py:
```py
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
... | 2017/01/26 | [
"https://Stackoverflow.com/questions/41883254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169431/"
] | As azmirfakkri has said if you're using `redirect`, dont use this `{% url 'namespace:name' %}` syntax, use `return redirect('namespace:name')`. | tag name must be unique in the `urls.py` file inside your application package inside the project! it is important for the template tagging to route whats what and where.
now [1] inside the `urls.py` file you need to declare the variable `appName` and give it the unique value. for example `appName = "myApp";` in your c... |
41,883,254 | I am trying to process a form in django/python using the following code.
---
home.html:
```html
<form action="{% url 'home:submit' %}" method='post'>
```
---
views.py:
```py
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
... | 2017/01/26 | [
"https://Stackoverflow.com/questions/41883254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169431/"
] | A common mistake that I always find is when you have some name space in your template,
and in YourApp.url you don't have any name space so if you should use name space add
in YourApp.url something like this
app\_name = "blog"
then on your temples make sure you add your name space,
so you will have some thing like ... | I got the same error below:
>
> NoReverseMatch at /account/register/ 'account' is not a registered
> namespace
>
>
>
So, I set **"app\_name"** with **the application name "account"** to **"account/urls.py"** as shown below then the error above is solved:
```py
# "account/urls.py"
from django.urls import path
fr... |
41,883,254 | I am trying to process a form in django/python using the following code.
---
home.html:
```html
<form action="{% url 'home:submit' %}" method='post'>
```
---
views.py:
```py
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
... | 2017/01/26 | [
"https://Stackoverflow.com/questions/41883254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169431/"
] | You should just change you action url in your template:
```
<form action="{% url 'submit' %} "method='post'>
```
---
On the note of url namespaces...
In order to be able to call urls using `home` namespace you should have in your main urls.py file line something like:
for django 1.x:
```
url(r'^', include('home.... | For the ***namespace error***,
Make sure you have linked the app's url in the main urls.py file
```
path('app_name/',include('app_name.urls'))
```
also in the urls.py of your app,make sure you mention the app's name as
```
app_name='app_name'
```
Also make sure you have registered the app's name on your installed... |
59,918,219 | ```
AttributeError at /addpatient_to_db
'QuerySet' object has no attribute 'wardno'
```
Request Method: POST
Request URL: <http://127.0.0.1:8000/addpatient_to_db>
Django Version: 2.2.5
Exception Type: `AttributeError`
Exception Value: `'QuerySet' object has no attribute 'wardno'`
Exception Location: `C:\Users\Sa... | 2020/01/26 | [
"https://Stackoverflow.com/questions/59918219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11056524/"
] | **TLDR:**
**Solution is that you should either provide engine and user\_id in params or you should remove presence true validation and add optional true case (for user association) from model.**
**Explanation:**
If your model says that it should validate presence of `engine` then how can you not provide engine param... | From your log file
```
Started POST "/cars" for ::1 at 2020-01-26 14:45:06 +0000
```
Shows that the create action is being called on the cars controller
The parameters being passed in are
```
{"authenticity_token"=>"Oom+xdVDc0PqSwLbLIEP0R8H6U38+v9ISVql4Fr/0WSxZGSrxzTHccsgghd1U30OugcUBAA1R4BtsB0YigAUtA==", "car"=>{"... |
62,377,906 | I want to run a batch file in a Conda environment, not in the **base** env, but in another virtual environment (here **pylayers**).
I copied the `activate.bat` script from `F:\Anaconda3\Scripts` to `F:\Anaconda3\envs\pylayers\Scripts`.
And my batch script (`installer_win.bat`) is:
```
call F:\Anaconda3\envs\pylayer... | 2020/06/14 | [
"https://Stackoverflow.com/questions/62377906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11051182/"
] | There are two ways to go. I think the first is the cleaner way to go.
Option 1: YAML Definition
=========================
If the entire procedure is only for installations, it can be condensed into a single [YAML environment definition](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environmen... | To run a bat file from a dos prompt inside a new (non-base) conda env, you can try something like this:
prompt> cmd "/c activate ds\_tensorflow && myfile.bat && deactivate"
contents of myfile.bat to show you are in the non-base env:
```
echo hello
python -c "import sys; print(sys.version)"
```
You can replace myfi... |
66,577,552 | I would like to suppress some sensitive information displayed in the logs.
Code:
```
pipeline {
parameters {
string(defaultValue: '', description: '', name: 'pki_client_cacert_password', trim: true)
string(defaultValue: '', description: '', name: 'db_url', trim: true)
}
stages {
stage(... | 2021/03/11 | [
"https://Stackoverflow.com/questions/66577552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1234419/"
] | First option is to set it as environment var:
```
withEnv(["MYSECRET=${params.pki_client_cacert_password}",
"MYURL=${env.db_url}"]) {
env.artifacts = sh(
returnStdout: true,
script: '.. python3 .. encrypter_creds.py --db_url=$MYURL ' +
' --pki_client_cacert_password=$MYSECRET... | I have added @MaratC suggestion however that did not help much, so I ended up adding `set +x` and `set -x` more so this question was related to
[Echo off in Jenkins Console Output](https://stackoverflow.com/questions/26797219/echo-off-in-jenkins-console-output)
which worked as expected
```
script{
... |
54,811,697 | I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form.
Is there any other form?
I am used to looping until a con... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54811697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191073/"
] | A for loop is the same thing as a while loop, just in a slightly different syntax. If you have a for loop that looks like
```
for(init; condition; post)
//do something
```
that is equivalent to the while loop
```
init;
while(condition)
//do something
post;
```
because Python has while loops, if you wanted t... | (Most Common)Three kinds of loops :
1. `Count controlled` - You dont have this kind of loop in python
2. `Condition controlled` - while loop in python
3. `Collection controlled` - for loop in python |
54,811,697 | I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form.
Is there any other form?
I am used to looping until a con... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54811697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191073/"
] | Consider this (credit to @Teghan for pointing out [::2] version):
```
> myStrs = ['A', 'B', 'C', 'D', 'E', 'F']
>
> for i in range(0, len(myStrs), 2):
> print(myStrs[i])
>
> print([(myStrs[i]) for i in range(0, len(myStrs), 2)])
> print([x+"a" for x in myStrs[::2]])
```
Output:
>
>
> ```... | You want a while loop:
```
i = 0
n = int
while i < n:
# do something
if some_possible_condition = True:
i = i + 1
```
To your specific example:
>
> how would you do something like iterate over every other string in a collection of strings, in python?
>
>
>
You could use a for loop and check ... |
54,811,697 | I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form.
Is there any other form?
I am used to looping until a con... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54811697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191073/"
] | >
> I am used to looping until a condition is false. There doesn't seem to
> be a way to evaluate a condition in a for loop in Python. Is that
> correct?
>
>
>
Correct. For loops don't evaluate conditions by themselfs, they iterate through an iterable. When you write `for i in something`, that `something` must b... | You want a while loop:
```
i = 0
n = int
while i < n:
# do something
if some_possible_condition = True:
i = i + 1
```
To your specific example:
>
> how would you do something like iterate over every other string in a collection of strings, in python?
>
>
>
You could use a for loop and check ... |
54,811,697 | I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form.
Is there any other form?
I am used to looping until a con... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54811697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191073/"
] | A for loop is the same thing as a while loop, just in a slightly different syntax. If you have a for loop that looks like
```
for(init; condition; post)
//do something
```
that is equivalent to the while loop
```
init;
while(condition)
//do something
post;
```
because Python has while loops, if you wanted t... | >
> I am used to looping until a condition is false. There doesn't seem to
> be a way to evaluate a condition in a for loop in Python. Is that
> correct?
>
>
>
Correct. For loops don't evaluate conditions by themselfs, they iterate through an iterable. When you write `for i in something`, that `something` must b... |
54,811,697 | I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form.
Is there any other form?
I am used to looping until a con... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54811697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191073/"
] | >
> I am used to looping until a condition is false. There doesn't seem to
> be a way to evaluate a condition in a for loop in Python. Is that
> correct?
>
>
>
Correct. For loops don't evaluate conditions by themselfs, they iterate through an iterable. When you write `for i in something`, that `something` must b... | You might be searching for [while](https://www.w3schools.com/python/python_while_loops.asp) loops |
54,811,697 | I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form.
Is there any other form?
I am used to looping until a con... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54811697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191073/"
] | A for loop is the same thing as a while loop, just in a slightly different syntax. If you have a for loop that looks like
```
for(init; condition; post)
//do something
```
that is equivalent to the while loop
```
init;
while(condition)
//do something
post;
```
because Python has while loops, if you wanted t... | You might be searching for [while](https://www.w3schools.com/python/python_while_loops.asp) loops |
54,811,697 | I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form.
Is there any other form?
I am used to looping until a con... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54811697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191073/"
] | A for loop is the same thing as a while loop, just in a slightly different syntax. If you have a for loop that looks like
```
for(init; condition; post)
//do something
```
that is equivalent to the while loop
```
init;
while(condition)
//do something
post;
```
because Python has while loops, if you wanted t... | Consider this (credit to @Teghan for pointing out [::2] version):
```
> myStrs = ['A', 'B', 'C', 'D', 'E', 'F']
>
> for i in range(0, len(myStrs), 2):
> print(myStrs[i])
>
> print([(myStrs[i]) for i in range(0, len(myStrs), 2)])
> print([x+"a" for x in myStrs[::2]])
```
Output:
>
>
> ```... |
54,811,697 | I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form.
Is there any other form?
I am used to looping until a con... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54811697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191073/"
] | A for loop is the same thing as a while loop, just in a slightly different syntax. If you have a for loop that looks like
```
for(init; condition; post)
//do something
```
that is equivalent to the while loop
```
init;
while(condition)
//do something
post;
```
because Python has while loops, if you wanted t... | You want a while loop:
```
i = 0
n = int
while i < n:
# do something
if some_possible_condition = True:
i = i + 1
```
To your specific example:
>
> how would you do something like iterate over every other string in a collection of strings, in python?
>
>
>
You could use a for loop and check ... |
54,811,697 | I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form.
Is there any other form?
I am used to looping until a con... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54811697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191073/"
] | (Most Common)Three kinds of loops :
1. `Count controlled` - You dont have this kind of loop in python
2. `Condition controlled` - while loop in python
3. `Collection controlled` - for loop in python | You want a while loop:
```
i = 0
n = int
while i < n:
# do something
if some_possible_condition = True:
i = i + 1
```
To your specific example:
>
> how would you do something like iterate over every other string in a collection of strings, in python?
>
>
>
You could use a for loop and check ... |
54,811,697 | I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form.
Is there any other form?
I am used to looping until a con... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54811697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191073/"
] | (Most Common)Three kinds of loops :
1. `Count controlled` - You dont have this kind of loop in python
2. `Condition controlled` - while loop in python
3. `Collection controlled` - for loop in python | You might be searching for [while](https://www.w3schools.com/python/python_while_loops.asp) loops |
6,289,699 | >
> **Possible Duplicate:**
>
> [How do I get the name of a function or method from within a Python function or method?](https://stackoverflow.com/questions/245304/how-do-i-get-the-name-of-a-function-or-method-from-within-a-python-function-or-me)
>
>
>
The below code function return it's name.
It works but I s... | 2011/06/09 | [
"https://Stackoverflow.com/questions/6289699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240041/"
] | If I understand correctly - [Inspect](http://docs.python.org/library/inspect.html) is what you are looking for.
```
import inspect
def test():
print inspect.stack()[0][3]
``` | There is no way to access the function name in a python function without using a backtrace.
```
In [1]: import inspect
In [2]: def test():
...: print inspect.stack()[0][3]
...:
In [3]: test()
test
```
So, what you want to use is `inspect.stack()[0][3]` or, if you want to move it into a separate function,... |
614,458 | How do i look for the following pattern using regular expression in python? for the two cases
Am looking for str2 after the "=" sign
* Case 1: `str1=str2`
* Case 2: `str1 = str2`
please note there can be a **space or none** between the either side of the "=" sign
Mine is like this, but only works for one of the ca... | 2009/03/05 | [
"https://Stackoverflow.com/questions/614458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74170/"
] | if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on `=` and strip (or even lstrip) last element of a resulting tuple:
```
>>> case = 'str = str2'
>>> case.partition('=')[2].lstrip()
'str2'
```
it'll be much faster than regexps. and just to show how fast i... | ```
re.search(r'=\s*(.*)', 'str = str2').group(1)
```
or if you just want a single word:
```
re.search(r'=\s*(\w+)', 'str = str2').group(1)
```
Extended to specific initial string:
```
re.search(r'\bstr\s*=\s*(\w+)', 'str=str2').group(1)
```
`\b` = word boundary, so won't match `"somestr=foo"`
It would be qui... |
614,458 | How do i look for the following pattern using regular expression in python? for the two cases
Am looking for str2 after the "=" sign
* Case 1: `str1=str2`
* Case 2: `str1 = str2`
please note there can be a **space or none** between the either side of the "=" sign
Mine is like this, but only works for one of the ca... | 2009/03/05 | [
"https://Stackoverflow.com/questions/614458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74170/"
] | ```
re.search(r'=\s*(.*)', 'str = str2').group(1)
```
or if you just want a single word:
```
re.search(r'=\s*(\w+)', 'str = str2').group(1)
```
Extended to specific initial string:
```
re.search(r'\bstr\s*=\s*(\w+)', 'str=str2').group(1)
```
`\b` = word boundary, so won't match `"somestr=foo"`
It would be qui... | Expanding on @batbrat's answer, and the other suggestions, you can use `re.split()` to separate the input string. The pattern can use `\s` (whitespace) or an explicit space.
```
>>> import re
>>> c1="str1=str2"
>>> c2="str1 = str2"
>>> re.split(' ?= ?',c1)
['str1', 'str2']
>>> re.split(' ?= ?',c2)
['str1', 'str2']
>>>... |
614,458 | How do i look for the following pattern using regular expression in python? for the two cases
Am looking for str2 after the "=" sign
* Case 1: `str1=str2`
* Case 2: `str1 = str2`
please note there can be a **space or none** between the either side of the "=" sign
Mine is like this, but only works for one of the ca... | 2009/03/05 | [
"https://Stackoverflow.com/questions/614458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74170/"
] | if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on `=` and strip (or even lstrip) last element of a resulting tuple:
```
>>> case = 'str = str2'
>>> case.partition('=')[2].lstrip()
'str2'
```
it'll be much faster than regexps. and just to show how fast i... | If your data is fixed then you can do this without using regex. Just split it on '='.
For example:
```
>>> case1 = "str1=str2"
>>> case2 = "str1 = str2"
>>> str2 = case1.split('=')[1].strip()
>>> str2 = case2.split('=')[1].strip()
```
This `YOURCASE.split('=')[1].strip()` statement will work for any cases. |
614,458 | How do i look for the following pattern using regular expression in python? for the two cases
Am looking for str2 after the "=" sign
* Case 1: `str1=str2`
* Case 2: `str1 = str2`
please note there can be a **space or none** between the either side of the "=" sign
Mine is like this, but only works for one of the ca... | 2009/03/05 | [
"https://Stackoverflow.com/questions/614458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74170/"
] | if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on `=` and strip (or even lstrip) last element of a resulting tuple:
```
>>> case = 'str = str2'
>>> case.partition('=')[2].lstrip()
'str2'
```
it'll be much faster than regexps. and just to show how fast i... | Related idea: I find using graphical regular expression tool helpful when trying to figure out correct pattern: <http://kodos.sf.net>. |
614,458 | How do i look for the following pattern using regular expression in python? for the two cases
Am looking for str2 after the "=" sign
* Case 1: `str1=str2`
* Case 2: `str1 = str2`
please note there can be a **space or none** between the either side of the "=" sign
Mine is like this, but only works for one of the ca... | 2009/03/05 | [
"https://Stackoverflow.com/questions/614458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74170/"
] | ```
re.search(r'=\s*(.*)', 'str = str2').group(1)
```
or if you just want a single word:
```
re.search(r'=\s*(\w+)', 'str = str2').group(1)
```
Extended to specific initial string:
```
re.search(r'\bstr\s*=\s*(\w+)', 'str=str2').group(1)
```
`\b` = word boundary, so won't match `"somestr=foo"`
It would be qui... | Related idea: I find using graphical regular expression tool helpful when trying to figure out correct pattern: <http://kodos.sf.net>. |
614,458 | How do i look for the following pattern using regular expression in python? for the two cases
Am looking for str2 after the "=" sign
* Case 1: `str1=str2`
* Case 2: `str1 = str2`
please note there can be a **space or none** between the either side of the "=" sign
Mine is like this, but only works for one of the ca... | 2009/03/05 | [
"https://Stackoverflow.com/questions/614458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74170/"
] | If your data is fixed then you can do this without using regex. Just split it on '='.
For example:
```
>>> case1 = "str1=str2"
>>> case2 = "str1 = str2"
>>> str2 = case1.split('=')[1].strip()
>>> str2 = case2.split('=')[1].strip()
```
This `YOURCASE.split('=')[1].strip()` statement will work for any cases. | Two cases:
* (case 1) if there is a single space before the '=', then there **must** also be a single space after the '='
```
m=re.search(r'(?<=\S)(?:\s=\s|=)(\w+)','str = str2')
print m.group(1)
```
* (case 2) otherwise,
```
m=re.search(r'(?<=\S)\s?=\s?(\w+)','str = str2')
print m.group(1)
```
In the first case,... |
614,458 | How do i look for the following pattern using regular expression in python? for the two cases
Am looking for str2 after the "=" sign
* Case 1: `str1=str2`
* Case 2: `str1 = str2`
please note there can be a **space or none** between the either side of the "=" sign
Mine is like this, but only works for one of the ca... | 2009/03/05 | [
"https://Stackoverflow.com/questions/614458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74170/"
] | Simply use split function | Expanding on @batbrat's answer, and the other suggestions, you can use `re.split()` to separate the input string. The pattern can use `\s` (whitespace) or an explicit space.
```
>>> import re
>>> c1="str1=str2"
>>> c2="str1 = str2"
>>> re.split(' ?= ?',c1)
['str1', 'str2']
>>> re.split(' ?= ?',c2)
['str1', 'str2']
>>>... |
614,458 | How do i look for the following pattern using regular expression in python? for the two cases
Am looking for str2 after the "=" sign
* Case 1: `str1=str2`
* Case 2: `str1 = str2`
please note there can be a **space or none** between the either side of the "=" sign
Mine is like this, but only works for one of the ca... | 2009/03/05 | [
"https://Stackoverflow.com/questions/614458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74170/"
] | If your data is fixed then you can do this without using regex. Just split it on '='.
For example:
```
>>> case1 = "str1=str2"
>>> case2 = "str1 = str2"
>>> str2 = case1.split('=')[1].strip()
>>> str2 = case2.split('=')[1].strip()
```
This `YOURCASE.split('=')[1].strip()` statement will work for any cases. | Expanding on @batbrat's answer, and the other suggestions, you can use `re.split()` to separate the input string. The pattern can use `\s` (whitespace) or an explicit space.
```
>>> import re
>>> c1="str1=str2"
>>> c2="str1 = str2"
>>> re.split(' ?= ?',c1)
['str1', 'str2']
>>> re.split(' ?= ?',c2)
['str1', 'str2']
>>>... |
614,458 | How do i look for the following pattern using regular expression in python? for the two cases
Am looking for str2 after the "=" sign
* Case 1: `str1=str2`
* Case 2: `str1 = str2`
please note there can be a **space or none** between the either side of the "=" sign
Mine is like this, but only works for one of the ca... | 2009/03/05 | [
"https://Stackoverflow.com/questions/614458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74170/"
] | if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on `=` and strip (or even lstrip) last element of a resulting tuple:
```
>>> case = 'str = str2'
>>> case.partition('=')[2].lstrip()
'str2'
```
it'll be much faster than regexps. and just to show how fast i... | Two cases:
* (case 1) if there is a single space before the '=', then there **must** also be a single space after the '='
```
m=re.search(r'(?<=\S)(?:\s=\s|=)(\w+)','str = str2')
print m.group(1)
```
* (case 2) otherwise,
```
m=re.search(r'(?<=\S)\s?=\s?(\w+)','str = str2')
print m.group(1)
```
In the first case,... |
614,458 | How do i look for the following pattern using regular expression in python? for the two cases
Am looking for str2 after the "=" sign
* Case 1: `str1=str2`
* Case 2: `str1 = str2`
please note there can be a **space or none** between the either side of the "=" sign
Mine is like this, but only works for one of the ca... | 2009/03/05 | [
"https://Stackoverflow.com/questions/614458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74170/"
] | if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on `=` and strip (or even lstrip) last element of a resulting tuple:
```
>>> case = 'str = str2'
>>> case.partition('=')[2].lstrip()
'str2'
```
it'll be much faster than regexps. and just to show how fast i... | I think a regex is overkill if you only want to deal with the above two cases. Here's what I'd do-
```
>>> case1 = "str1=str2"
>>> case2 = "str1 = str2"
>>> case2.split()
['str1', '=', 'str2']
>>> ''.join(case2.split())
'str1=str2'
>>> case1[5:]
'str2'
>>> ''.join(case2.split())[5:]
'str2'
>>>
```
**Assumption**
--... |
37,974,645 | I recently started learning ruby, coming from a background in python. This is one of my first programs above a few lines in length, and I have made a mistake somewhere in the syntax that I cannot catch, that is causing the program to fail with the error "unexpected end-of-output, expected keyword\_end"
Here is the cod... | 2016/06/22 | [
"https://Stackoverflow.com/questions/37974645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5506705/"
] | One missing `end` after line 35, i.e. at
```
number = (numberRev / 100).reverse
# HERE! there should be an `end`
if left == 0
return numEnglish
```
In addition, at line 18 and 19 you are asking `number[0]` for the first non-zero digit of... | Some advice:
* use two spaces. It's more common and easier to read and spot such errors.
* use an editor like Sublime Text or a IDE like RubyMine. ST has several add-ons that facilitate debugging. In this case all I had to do is run a "Beautify-Ruby" on the code and it gave me this output.
It looks like you are miss... |
70,630,205 | I don't know how to get the all total price of the product that the customer bought from my system. the price of each item I can get but the price of all the item that have been choose i can't get the output. I'm using python.
Below is my code:
```
#below is the price of products
shopping_cart = {}
option = 1
while... | 2022/01/08 | [
"https://Stackoverflow.com/questions/70630205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Just putting `("Not found")` as a statement doesn't print anything. You need to add your item total into `total_cost` immediately after the print statement. There's no point defining a function, since you don't call the function. So, replace everything after that last "else:" with this:
```
else:
total = 0... | You can add `total_cost += total` for every choice,
So its added to the total cost when somebody choose the item and if he add another it also adds to the total cost.
```py
elif option == 6:
print("Foaming Milk")
qnty = int(input("Enter the quantity: "))
total = qnty*12.70
print("Th... |
70,630,205 | I don't know how to get the all total price of the product that the customer bought from my system. the price of each item I can get but the price of all the item that have been choose i can't get the output. I'm using python.
Below is my code:
```
#below is the price of products
shopping_cart = {}
option = 1
while... | 2022/01/08 | [
"https://Stackoverflow.com/questions/70630205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Just putting `("Not found")` as a statement doesn't print anything. You need to add your item total into `total_cost` immediately after the print statement. There's no point defining a function, since you don't call the function. So, replace everything after that last "else:" with this:
```
else:
total = 0... | 1. You basically have the same couple lines for every option
2. You dont save your values
You can try this:
```
items = {
"UHT Milk" : 6.49,
"Pasteurised Milk" : 5.50,
"Sterilised Milk" : 4.00,
"Eating and Drinking Yoghurt" : 10.50,
"Full Cream Milk" : 15.50,
"Foaming Milk" :12.70
}
... |
65,797,818 | I'm trying to understand regex and i have an error message.
I don't understand this message because I don't use list. If I use just print(number) it doesn't delete the [ ] of the result. The goal is to obtain only the number in the sentence as result.
I use python 3.6.
Below my code:
```
import re
user_sentence = inp... | 2021/01/19 | [
"https://Stackoverflow.com/questions/65797818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15039238/"
] | `groups()` (with an `s`) is on the return value of a `re.match`, not a `findall`. If you're looking to print each item in the list returned by a findall, you can print use `join` to join them on a space, or loop over the list. Note that the list may include tuples though (not in your case, but in general). Example of j... | findall returns list type by default and list does not have any such method/attribute. If you try to running print (number), you see a list as the output. But to convert the list elements into number you can add these lines after you have evaluated number
```
number = re.findall("[0-9]+", user_sentence)
#add these lin... |
65,797,818 | I'm trying to understand regex and i have an error message.
I don't understand this message because I don't use list. If I use just print(number) it doesn't delete the [ ] of the result. The goal is to obtain only the number in the sentence as result.
I use python 3.6.
Below my code:
```
import re
user_sentence = inp... | 2021/01/19 | [
"https://Stackoverflow.com/questions/65797818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15039238/"
] | Why are you running `re.findall` twice ? Your code should be like this:
```py
import re
user_sentence = input(">>> : ")
while user_sentence != "quit":
numbers = re.findall("[0-9]+", user_sentence)
if numbers:
print("found numbers " + " ".join(numbers))
user_sentence = input(">>> : ")
else:
print("no n... | findall returns list type by default and list does not have any such method/attribute. If you try to running print (number), you see a list as the output. But to convert the list elements into number you can add these lines after you have evaluated number
```
number = re.findall("[0-9]+", user_sentence)
#add these lin... |
29,802,931 | I have a csv file of customer ids (`CRM_id`). I need to get their primary keys (an autoincrement int) from the customers table of the database. (I can't be assured of the integrity of the `CRM_id`s so I chose not to make that the primary key).
So:
```
customers = []
with open("CRM_ids.csv", 'r', newline='') as csvfil... | 2015/04/22 | [
"https://Stackoverflow.com/questions/29802931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3790954/"
] | What about changing your query to get what you want?
```
crm_ids = ",".join(customers)
select_customer = "SELECT UNIQUE id FROM customers WHERE CRM_id IN (%s);" % crm_ids
```
MySQL should be fine with even a multi-megabyte query, according to [the manual](http://dev.mysql.com/doc/refman/5.0/en/packet-too-large.html)... | how about storing your csv in a dict instead of a list:
```
customers = [c for c in customerfile]
```
becomes:
```
customers = {c['CRM_id']:c for c in customerfile}
```
then select the entire xref:
```
result = cursor.execute('select id, CRM_id from customers')
```
and add the new rowid as a new entry in the d... |
55,351,039 | There is an excel file logging a set of data. Its columns are as below, where each column is seperated by comma.
```
SampleData
year,date,month,location,time,count
2019,20,Jan,Japan,22:33,1
2019,31,Jan,Japan,19:21,1
2019,1,Jan,Japan,8:00,1
2019,4,Jan,Japan,4:28,2
2019,13,Feb,Japan,6:19,1
```
From this data, I would ... | 2019/03/26 | [
"https://Stackoverflow.com/questions/55351039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11258673/"
] | try this
```
from datetime import datetime
data['datetime'] = data[['year','date','month','time']].apply(lambda x: datetime.strptime(str(x['year'])+'-'+str(x['date'])+'-'+str(x['month'])+' '+str(x['time']), "%Y-%d-%b %H:%M").timestamp(), axis=1)
data[['datetime','location','count']]
```
**Output**
```
dat... | You are close, need `%Y%b%d%H:%M` format and then convert to unix time by cast to `int64` with integer division by `10**9`:
```
s = (DataFrame["year"].astype(str)+
DataFrame["month"].astype(str)+
DataFrame["date"].astype(str)+
DataFrame["time"].astype(str))
DataFrame['u_datetime'] = pd.to_datetime(s, fo... |
55,351,039 | There is an excel file logging a set of data. Its columns are as below, where each column is seperated by comma.
```
SampleData
year,date,month,location,time,count
2019,20,Jan,Japan,22:33,1
2019,31,Jan,Japan,19:21,1
2019,1,Jan,Japan,8:00,1
2019,4,Jan,Japan,4:28,2
2019,13,Feb,Japan,6:19,1
```
From this data, I would ... | 2019/03/26 | [
"https://Stackoverflow.com/questions/55351039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11258673/"
] | In case you are working with csv file this can be done easily using [parse\_dates](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#csv-text-files).
```
dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv('/home/users/user/xxx.csv', parse_dates ={'date_time':[0,1,2,4]})
d... | You are close, need `%Y%b%d%H:%M` format and then convert to unix time by cast to `int64` with integer division by `10**9`:
```
s = (DataFrame["year"].astype(str)+
DataFrame["month"].astype(str)+
DataFrame["date"].astype(str)+
DataFrame["time"].astype(str))
DataFrame['u_datetime'] = pd.to_datetime(s, fo... |
5,195,295 | I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg:
```
reader = csv.reader(open("file.csv", "r... | 2011/03/04 | [
"https://Stackoverflow.com/questions/5195295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644926/"
] | The simplest way is to write your script like this:
```
import sys
reader = csv.reader(open(sys.argv[1], "rb"))
```
and then run it like this:
```
python testfile.py file.csv
```
You should put in some error checking, eg:
```
if len(sys.argv) < 2:
print "Usage..."
sys.exit(1)
```
For more power, use th... | You can use [optparse](http://docs.python.org/library/optparse.html) ([argparse](http://docs.python.org/library/argparse.html#module-argparse) after 2.7) or [getopt](http://docs.python.org/library/getopt.html) to parse command line parameters. Only use getopt if you're already familiar with argument parsing in C. Other... |
5,195,295 | I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg:
```
reader = csv.reader(open("file.csv", "r... | 2011/03/04 | [
"https://Stackoverflow.com/questions/5195295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644926/"
] | The simplest way is to write your script like this:
```
import sys
reader = csv.reader(open(sys.argv[1], "rb"))
```
and then run it like this:
```
python testfile.py file.csv
```
You should put in some error checking, eg:
```
if len(sys.argv) < 2:
print "Usage..."
sys.exit(1)
```
For more power, use th... | Maybe the *argparse* python module fits your depends:
<http://docs.python.org/library/argparse.html>
The old *optparse* is deprecated. |
5,195,295 | I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg:
```
reader = csv.reader(open("file.csv", "r... | 2011/03/04 | [
"https://Stackoverflow.com/questions/5195295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644926/"
] | The simplest way is to write your script like this:
```
import sys
reader = csv.reader(open(sys.argv[1], "rb"))
```
and then run it like this:
```
python testfile.py file.csv
```
You should put in some error checking, eg:
```
if len(sys.argv) < 2:
print "Usage..."
sys.exit(1)
```
For more power, use th... | You can access `sys.argv` which is an array of the inputs. But keep in mind that the first argument is the actual program itself. |
5,195,295 | I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg:
```
reader = csv.reader(open("file.csv", "r... | 2011/03/04 | [
"https://Stackoverflow.com/questions/5195295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644926/"
] | You can use [optparse](http://docs.python.org/library/optparse.html) ([argparse](http://docs.python.org/library/argparse.html#module-argparse) after 2.7) or [getopt](http://docs.python.org/library/getopt.html) to parse command line parameters. Only use getopt if you're already familiar with argument parsing in C. Other... | Maybe the *argparse* python module fits your depends:
<http://docs.python.org/library/argparse.html>
The old *optparse* is deprecated. |
5,195,295 | I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg:
```
reader = csv.reader(open("file.csv", "r... | 2011/03/04 | [
"https://Stackoverflow.com/questions/5195295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644926/"
] | You can use [optparse](http://docs.python.org/library/optparse.html) ([argparse](http://docs.python.org/library/argparse.html#module-argparse) after 2.7) or [getopt](http://docs.python.org/library/getopt.html) to parse command line parameters. Only use getopt if you're already familiar with argument parsing in C. Other... | You can access `sys.argv` which is an array of the inputs. But keep in mind that the first argument is the actual program itself. |
5,195,295 | I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg:
```
reader = csv.reader(open("file.csv", "r... | 2011/03/04 | [
"https://Stackoverflow.com/questions/5195295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644926/"
] | For reference the optparse (http://docs.python.org/library/optparse.html) version would look something like this.
```
import optparse
parser = optparse.OptionParser()
parser.add_option("-i","--input",dest="filename")
(options,args) = parser.parse_args()
thefile = options.filename
reader = csv.reader(thefile,"rb")
`... | You can use [optparse](http://docs.python.org/library/optparse.html) ([argparse](http://docs.python.org/library/argparse.html#module-argparse) after 2.7) or [getopt](http://docs.python.org/library/getopt.html) to parse command line parameters. Only use getopt if you're already familiar with argument parsing in C. Other... |
5,195,295 | I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg:
```
reader = csv.reader(open("file.csv", "r... | 2011/03/04 | [
"https://Stackoverflow.com/questions/5195295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644926/"
] | For reference the optparse (http://docs.python.org/library/optparse.html) version would look something like this.
```
import optparse
parser = optparse.OptionParser()
parser.add_option("-i","--input",dest="filename")
(options,args) = parser.parse_args()
thefile = options.filename
reader = csv.reader(thefile,"rb")
`... | Maybe the *argparse* python module fits your depends:
<http://docs.python.org/library/argparse.html>
The old *optparse* is deprecated. |
5,195,295 | I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg:
```
reader = csv.reader(open("file.csv", "r... | 2011/03/04 | [
"https://Stackoverflow.com/questions/5195295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644926/"
] | For reference the optparse (http://docs.python.org/library/optparse.html) version would look something like this.
```
import optparse
parser = optparse.OptionParser()
parser.add_option("-i","--input",dest="filename")
(options,args) = parser.parse_args()
thefile = options.filename
reader = csv.reader(thefile,"rb")
`... | You can access `sys.argv` which is an array of the inputs. But keep in mind that the first argument is the actual program itself. |
11,724,779 | I am trying to install a local version of ScrumDo for testing. Only then I come to the point in my installation that I have to run:
>
> source bin/activate
>
> pip install -r requirements.txt
>
>
>
I get the error:
>
> Downloading/unpacking django-storages
>
>
>
> >
> > Cannot fetch index base URL http ... | 2012/07/30 | [
"https://Stackoverflow.com/questions/11724779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411141/"
] | You can try installing django-storages on its own.. try this?
```
sudo pip install https://bitbucket.org/david/django-storages/get/def732408163.zip
``` | Try giving the proxy settings in the command as such
```
pip --proxy=http://user:password@Proxy:PortNumber install -r requirements.txt
```
or try
```
export http_proxy=http://user:password@Proxy:PortNumber
``` |
11,724,779 | I am trying to install a local version of ScrumDo for testing. Only then I come to the point in my installation that I have to run:
>
> source bin/activate
>
> pip install -r requirements.txt
>
>
>
I get the error:
>
> Downloading/unpacking django-storages
>
>
>
> >
> > Cannot fetch index base URL http ... | 2012/07/30 | [
"https://Stackoverflow.com/questions/11724779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411141/"
] | You can try installing django-storages on its own.. try this?
```
sudo pip install https://bitbucket.org/david/django-storages/get/def732408163.zip
``` | This problem is most-likely caused by DNS setup: server cannot resolve the Domain Name, so cannot download the package.
Solution:
sudo nano /etc/network/interface
add a line:
dns-nameservers 8.8.8.8
save file and exit
```
sudo ifdown eth0 && sudo ifup eth0
```
Then pip install should be working now. |
11,724,779 | I am trying to install a local version of ScrumDo for testing. Only then I come to the point in my installation that I have to run:
>
> source bin/activate
>
> pip install -r requirements.txt
>
>
>
I get the error:
>
> Downloading/unpacking django-storages
>
>
>
> >
> > Cannot fetch index base URL http ... | 2012/07/30 | [
"https://Stackoverflow.com/questions/11724779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411141/"
] | If you've tried installing a package with pip recently, you may have encountered this error:
```
Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest ... | Try giving the proxy settings in the command as such
```
pip --proxy=http://user:password@Proxy:PortNumber install -r requirements.txt
```
or try
```
export http_proxy=http://user:password@Proxy:PortNumber
``` |
11,724,779 | I am trying to install a local version of ScrumDo for testing. Only then I come to the point in my installation that I have to run:
>
> source bin/activate
>
> pip install -r requirements.txt
>
>
>
I get the error:
>
> Downloading/unpacking django-storages
>
>
>
> >
> > Cannot fetch index base URL http ... | 2012/07/30 | [
"https://Stackoverflow.com/questions/11724779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411141/"
] | Try giving the proxy settings in the command as such
```
pip --proxy=http://user:password@Proxy:PortNumber install -r requirements.txt
```
or try
```
export http_proxy=http://user:password@Proxy:PortNumber
``` | This problem is most-likely caused by DNS setup: server cannot resolve the Domain Name, so cannot download the package.
Solution:
sudo nano /etc/network/interface
add a line:
dns-nameservers 8.8.8.8
save file and exit
```
sudo ifdown eth0 && sudo ifup eth0
```
Then pip install should be working now. |
11,724,779 | I am trying to install a local version of ScrumDo for testing. Only then I come to the point in my installation that I have to run:
>
> source bin/activate
>
> pip install -r requirements.txt
>
>
>
I get the error:
>
> Downloading/unpacking django-storages
>
>
>
> >
> > Cannot fetch index base URL http ... | 2012/07/30 | [
"https://Stackoverflow.com/questions/11724779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411141/"
] | If you've tried installing a package with pip recently, you may have encountered this error:
```
Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest ... | This problem is most-likely caused by DNS setup: server cannot resolve the Domain Name, so cannot download the package.
Solution:
sudo nano /etc/network/interface
add a line:
dns-nameservers 8.8.8.8
save file and exit
```
sudo ifdown eth0 && sudo ifup eth0
```
Then pip install should be working now. |
53,162,325 | I use google composer. I have a dag that uses the `panda.read_csv()` function to read a `.csv.gz` file. The DAG keeps trying without showing any errors. Here is the airflow log:
```
*** Reading remote log from gs://us-central1-data-airflo-dxxxxx-bucket/logs/youtubetv_gcpbucket_to_bq_daily_v2_csv/file_transfer_gcp_to_... | 2018/11/05 | [
"https://Stackoverflow.com/questions/53162325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183883/"
] | Based on this discussion [airflow google composer group](https://groups.google.com/forum/#!topic/cloud-composer-discuss/alnKzMjEj8Q) it is a known issue.
One of the reason can be because of overkilling all the composer resources (in my case memory) | I have a [similar issue](https://groups.google.com/forum/#!topic/cloud-composer-discuss/lKsy7X1fy00) recently.
In my case it's beacause the kubernetes worker overload.
You can watch the worker performance on kubernetes dashboard too see whether your case is cluster overloadding issue.
If yes, you can try set the val... |
57,602,726 | I'm wondering why we can have Tensorflow [run in a multi-thread fashion](https://www.tensorflow.org/guide/performance/overview#optimizing_for_cpu) while python can only execute one thread at a time due to [GIL](https://wiki.python.org/moin/GlobalInterpreterLock)? | 2019/08/22 | [
"https://Stackoverflow.com/questions/57602726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7850499/"
] | The GIL's restriction is slightly more subtle: only one thread at a time can be *executing Python bytecode*.
Extensions using Python's C API (like `tensorflow`) can release the GIL if they don't need it. I/O operations like using files or sockets also tend to release the GIL because they generally involve lots of wait... | Most of the `tensorflow` core is written in `C++` and the python APIs are just the wrappers around it. While running the `C++` code regular python restrictions do not apply. |
4,631,377 | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | 2011/01/07 | [
"https://Stackoverflow.com/questions/4631377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567620/"
] | I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great:
* Select **Project**-> RightClick-> **PyDev**-> **Remove PyDev Project Config**
* file-> **rest... | Following, in my opinion will solve the problem
1. Adding the **init**.py to your "~/Desktop/Python\_Tutorials/diveintopython/py" folder
2. Go to Window --> Preferences --> PyDev --> Interpreters --> Python Interpreter to remove your Python Interpreter setting (reason being is because PyDev unable to auto refresh any ... |
4,631,377 | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | 2011/01/07 | [
"https://Stackoverflow.com/questions/4631377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567620/"
] | I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great:
* Select **Project**-> RightClick-> **PyDev**-> **Remove PyDev Project Config**
* file-> **rest... | ```
KD.py
class A:
a=10;
KD2.py
from com.jbk.KD import A;
class B:
b=120;
aa=A();
print(aa.a)
```
THIS works perfectly file for me
Another example is
```
main.py
=======
from com.jbk.scenarios.objectcreation.settings import _init
from com.jbk.scenarios.objectcreation.subfile import stuff
_init();
stuff();
... |
4,631,377 | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | 2011/01/07 | [
"https://Stackoverflow.com/questions/4631377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567620/"
] | I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great:
* Select **Project**-> RightClick-> **PyDev**-> **Remove PyDev Project Config**
* file-> **rest... | There are two ways of solving this issue:
* Delete the Python interpreter from "Python interpreters" and add it again.
* Or just add the folder with the libraries in the interpreter you are using in your project, in my case I was using "bottle" and the folder I added was "c:\Python33\Lib\site-packages\bottle-0.11.6-py... |
4,631,377 | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | 2011/01/07 | [
"https://Stackoverflow.com/questions/4631377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567620/"
] | I just upgraded a WXWindows project to Python 2.7 and had no end of trouble getting Pydev to recognize the new interpreter. Did the same thing as above configuring the interpreter, made a fresh install of Eclipse and Pydev. Thought some part of python must have been corrupt, so I re-installed everything again. Arghh! C... | Here is what worked for me (sugested by soulBit):
```
1) Restart using restart from the file menu
2) Once it started again, manually close and open it.
```
This is the simplest solution ever and it completely removes the annoying thing. |
4,631,377 | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | 2011/01/07 | [
"https://Stackoverflow.com/questions/4631377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567620/"
] | I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great:
* Select **Project**-> RightClick-> **PyDev**-> **Remove PyDev Project Config**
* file-> **rest... | I'm running Eclipse 4.2.0 (Juno) and PyDev 2.8.1, and ran into this problem with a lib installed to my site-packages path. According to this SO question:
[Pydev and \*.pyc Files](https://stackoverflow.com/questions/13967342/pydev-and-pyc-files)
...there is an issue with PyDev and pyc files. In the case of the particu... |
4,631,377 | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | 2011/01/07 | [
"https://Stackoverflow.com/questions/4631377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567620/"
] | **project-->properties-->pydev-pythonpath-->external libraries --> add** source folder, add the PARENT FOLDER of the project. Then restart eclipse. | ```
KD.py
class A:
a=10;
KD2.py
from com.jbk.KD import A;
class B:
b=120;
aa=A();
print(aa.a)
```
THIS works perfectly file for me
Another example is
```
main.py
=======
from com.jbk.scenarios.objectcreation.settings import _init
from com.jbk.scenarios.objectcreation.subfile import stuff
_init();
stuff();
... |
4,631,377 | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | 2011/01/07 | [
"https://Stackoverflow.com/questions/4631377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567620/"
] | I had some issues importing additional libraries, after trying to resolve the problem, by understanding
PYTHONPATH, Interpreter, and Grammar I found that I did everything write but the problems continue. After that, **I just add a new empty line in the files that had the import errors and saved them and the error was ... | ```
KD.py
class A:
a=10;
KD2.py
from com.jbk.KD import A;
class B:
b=120;
aa=A();
print(aa.a)
```
THIS works perfectly file for me
Another example is
```
main.py
=======
from com.jbk.scenarios.objectcreation.settings import _init
from com.jbk.scenarios.objectcreation.subfile import stuff
_init();
stuff();
... |
4,631,377 | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | 2011/01/07 | [
"https://Stackoverflow.com/questions/4631377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567620/"
] | I fixed my pythonpath and everything was dandy when I imported stuff through the console, but all these previously unresolved imports were still marked as errors in my code, no matter how many times I restarted eclipse or refreshed/cleaned the project.
I right clicked the project->Pydev->Remove error markers and it g... | I had some issues importing additional libraries, after trying to resolve the problem, by understanding
PYTHONPATH, Interpreter, and Grammar I found that I did everything write but the problems continue. After that, **I just add a new empty line in the files that had the import errors and saved them and the error was ... |
4,631,377 | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | 2011/01/07 | [
"https://Stackoverflow.com/questions/4631377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567620/"
] | I just upgraded a WXWindows project to Python 2.7 and had no end of trouble getting Pydev to recognize the new interpreter. Did the same thing as above configuring the interpreter, made a fresh install of Eclipse and Pydev. Thought some part of python must have been corrupt, so I re-installed everything again. Arghh! C... | **project-->properties-->pydev-pythonpath-->external libraries --> add** source folder, add the PARENT FOLDER of the project. Then restart eclipse. |
4,631,377 | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | 2011/01/07 | [
"https://Stackoverflow.com/questions/4631377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567620/"
] | I'm running Eclipse 4.2.0 (Juno) and PyDev 2.8.1, and ran into this problem with a lib installed to my site-packages path. According to this SO question:
[Pydev and \*.pyc Files](https://stackoverflow.com/questions/13967342/pydev-and-pyc-files)
...there is an issue with PyDev and pyc files. In the case of the particu... | ```
KD.py
class A:
a=10;
KD2.py
from com.jbk.KD import A;
class B:
b=120;
aa=A();
print(aa.a)
```
THIS works perfectly file for me
Another example is
```
main.py
=======
from com.jbk.scenarios.objectcreation.settings import _init
from com.jbk.scenarios.objectcreation.subfile import stuff
_init();
stuff();
... |
62,504,019 | I am calling the Giphy API using another [wrapper API](https://github.com/Giphy/giphy-python-client) which returns a **list of dictionaries**. I am having hard times to serialize the data to return it to AJAX.
The data is returned as `InlineResponse200` with three [properties](https://github.com/Giphy/giphy-python-cli... | 2020/06/21 | [
"https://Stackoverflow.com/questions/62504019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12001122/"
] | ```
render(request, template_name, context=None, content_type=None, status=None, using=None)
```
>
> `render()` Combines a given template with a given context dictionary
> and returns an HttpResponse object with that rendered text.
>
>
>
You can either use Django defaults `JsonResponse` class or Django REST fram... | Python has a built in function for converting dicts to json.
```
import json
data = api_response.data
return render(request, json.dumps(data))
```
If you use that in your return statement it should return json. |
62,504,019 | I am calling the Giphy API using another [wrapper API](https://github.com/Giphy/giphy-python-client) which returns a **list of dictionaries**. I am having hard times to serialize the data to return it to AJAX.
The data is returned as `InlineResponse200` with three [properties](https://github.com/Giphy/giphy-python-cli... | 2020/06/21 | [
"https://Stackoverflow.com/questions/62504019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12001122/"
] | I go though your code everything is correct except `return JsonResponse(api_response.data[0])` in your views
**JsonResponse**:
The **first parameter, data, should be a dict instance.** If the **safe parameter is set to False**, it can be any JSON-serializable object. [official documentation link](https://docs.djangop... | Python has a built in function for converting dicts to json.
```
import json
data = api_response.data
return render(request, json.dumps(data))
```
If you use that in your return statement it should return json. |
62,504,019 | I am calling the Giphy API using another [wrapper API](https://github.com/Giphy/giphy-python-client) which returns a **list of dictionaries**. I am having hard times to serialize the data to return it to AJAX.
The data is returned as `InlineResponse200` with three [properties](https://github.com/Giphy/giphy-python-cli... | 2020/06/21 | [
"https://Stackoverflow.com/questions/62504019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12001122/"
] | I go though your code everything is correct except `return JsonResponse(api_response.data[0])` in your views
**JsonResponse**:
The **first parameter, data, should be a dict instance.** If the **safe parameter is set to False**, it can be any JSON-serializable object. [official documentation link](https://docs.djangop... | ```
render(request, template_name, context=None, content_type=None, status=None, using=None)
```
>
> `render()` Combines a given template with a given context dictionary
> and returns an HttpResponse object with that rendered text.
>
>
>
You can either use Django defaults `JsonResponse` class or Django REST fram... |
16,518,142 | I'm trying out threads in python. I want a spinning cursor to display while another method runs (for 5-10 mins). I've done out some code but am wondering is this how you would do it? i don't like to use globals, so I assume there is a better way?
```
c = True
def b():
for j in itertools.cycle('/-\|'):
if... | 2013/05/13 | [
"https://Stackoverflow.com/questions/16518142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1803007/"
] | You could use events:
<http://docs.python.org/2/library/threading.html>
I tested this and it works. It also keeps everything in sync. You should avoid changing/reading the same variables in different threads without synchronizing them.
```
#!/usr/bin/python
from threading import Thread
from threading import Event
im... | This is not properly synchronized. But I will not try to explain it all to you right now because it's a whole lot of knowledge. Try to read this: <http://effbot.org/zone/thread-synchronization.htm>
But in your case it's not that bad that things aren't synchronized correctyl. The only thing that could happen, is that t... |
16,518,142 | I'm trying out threads in python. I want a spinning cursor to display while another method runs (for 5-10 mins). I've done out some code but am wondering is this how you would do it? i don't like to use globals, so I assume there is a better way?
```
c = True
def b():
for j in itertools.cycle('/-\|'):
if... | 2013/05/13 | [
"https://Stackoverflow.com/questions/16518142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1803007/"
] | You're on the right track mostly, except for the global variable. Normally you'd needed to coordinate access to shared data like that with a lock or semaphore, but in this special case you can take a short-cut and just use whether one of the threads is running or not instead. This is what I mean:
```
from threading im... | This is not properly synchronized. But I will not try to explain it all to you right now because it's a whole lot of knowledge. Try to read this: <http://effbot.org/zone/thread-synchronization.htm>
But in your case it's not that bad that things aren't synchronized correctyl. The only thing that could happen, is that t... |
3,076,798 | I'm trying to start a text editor (nano) from inside Python, have the user enter text, and then capture the text once they writeout (Control-O). I haven't worked with the `subprocess` module before, nor pipes, so I don't know what to try next.
So far I have this code:
```
a = subprocess.Popen('nano', stdout=subproces... | 2010/06/19 | [
"https://Stackoverflow.com/questions/3076798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104297/"
] | Control-O in Nano writes to **the file being edited**, i.e., *not* to standard output -- so, forego the attempt to capture stdout and just read the file once the user writes it out and exits Nano. E.g., on my Mac:
```
>>> import tempfile
>>> f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
>>> n = f.name
>>> ... | I'm not sure you can capture what the user has entered into `nano`. After all, that's nano's job.
What you can (and I think should do) to get user input from an editor is to spawn it off with a [temporary file](http://docs.python.org/library/tempfile.html). Then when the user has entered what he wants, he saves and q... |
61,109,903 | I'm new to python and programing and I'm trying to make a code to display an image with some data from a `.fits` file. I'm first trying to make this example I found from this site: <https://docs.astropy.org/en/stable/generated/examples/io/plot_fits-image.html#sphx-glr-download-generated-examples-io-plot-fits-image-py>.... | 2020/04/08 | [
"https://Stackoverflow.com/questions/61109903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13263274/"
] | Do you like it better that way?
```
if (
!(profile.name.hasError ||
profile.crn.hasError ||
profile.employeesNbr.hasError ||
profile.phoneNumber.hasError ||
profile.userRole.hasError) &&
profile.personCheck.hasError
) {
showModal.modal.error = true;
}... | It would be easy to simplify it into a loop if you were doing the same check for all properties in the profile. Doing a different check for `personCheck` makes it hard to reduce it like that.
You can use an array for all the properties that you want the same check on.
```
if (profile.personCheck.hasError &&
["na... |
61,109,903 | I'm new to python and programing and I'm trying to make a code to display an image with some data from a `.fits` file. I'm first trying to make this example I found from this site: <https://docs.astropy.org/en/stable/generated/examples/io/plot_fits-image.html#sphx-glr-download-generated-examples-io-plot-fits-image-py>.... | 2020/04/08 | [
"https://Stackoverflow.com/questions/61109903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13263274/"
] | In the following way it would be optimized since as soon as one of the `profile.*` props has `hasError` to `true` would "returns" (due the **or** instead of **and**): the **and** (`&&`) needs to evaluate all the conditions where the **or** `||` it stops as soon as one is `true`.
You can also probably remove the `if` s... | Do you like it better that way?
```
if (
!(profile.name.hasError ||
profile.crn.hasError ||
profile.employeesNbr.hasError ||
profile.phoneNumber.hasError ||
profile.userRole.hasError) &&
profile.personCheck.hasError
) {
showModal.modal.error = true;
}... |
61,109,903 | I'm new to python and programing and I'm trying to make a code to display an image with some data from a `.fits` file. I'm first trying to make this example I found from this site: <https://docs.astropy.org/en/stable/generated/examples/io/plot_fits-image.html#sphx-glr-download-generated-examples-io-plot-fits-image-py>.... | 2020/04/08 | [
"https://Stackoverflow.com/questions/61109903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13263274/"
] | In the following way it would be optimized since as soon as one of the `profile.*` props has `hasError` to `true` would "returns" (due the **or** instead of **and**): the **and** (`&&`) needs to evaluate all the conditions where the **or** `||` it stops as soon as one is `true`.
You can also probably remove the `if` s... | It would be easy to simplify it into a loop if you were doing the same check for all properties in the profile. Doing a different check for `personCheck` makes it hard to reduce it like that.
You can use an array for all the properties that you want the same check on.
```
if (profile.personCheck.hasError &&
["na... |
65,183,558 | Let's say I want to implement some **list class** in python with extra structure, like a new constructor. I wrote:
```
import random
class Lis(list):
def __init__(self, n):
self = []
for i in range(n):
self.append(random.randint(0, 30))
```
Now doing `Lis(3)` gives me an empty list. ... | 2020/12/07 | [
"https://Stackoverflow.com/questions/65183558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4821555/"
] | You are overriding the object with `self = []`
try the following
```
import random
class Lis(list):
def __init__(self, n):
for i in range(n):
self.append(random.randint(0, 30))
``` | if you want to return a list from object call
```py
class MyClass(object):
def __init__(self):
print "never called in this case"
def __new__(cls):
return [1,2,3]
obj = MyClass()
print(obj)
```
[How to return a value from \_\_init\_\_ in Python?](https://stackoverflow.com/questions/2491819/ho... |
12,454,675 | I made a simple server and a simple client with `socket` module in python.
server:
```
# server.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from', addr)
c.send(b'Thank you for your c... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12454675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477871/"
] | From the [`socket` documentation](http://docs.python.org/library/socket.html):
>
> A pair (host, port) is used for the AF\_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer.
>
>
>... | Quote from [python documentation](http://docs.python.org/library/socket.html#socket.socket.accept):
>
> `socket.accept()`
>
>
> Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair `(conn, address)` where conn is a new socket object usable to send an... |
54,730,763 | I am trying to understand how RxPy works, I am getting this error
>
> type object 'ObservableBase' has no attribute 'create'
>
>
>
I am using python 3.6 and my code is
```
from rx import Observable
stocks = [
{'TCKR': 'APPL', 'PRICE': 200},
{'TCKR': 'GOOG', 'PRICE': 90},
{'TCKR': 'TSLA', 'PRICE': 120},
... | 2019/02/17 | [
"https://Stackoverflow.com/questions/54730763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291507/"
] | They have updated RxPy module. Install 1.6.1, it will solve the problem. Thanks | I have found the solution,
change the code from
```
from rx import Observable
source = Observable.create(buy_stock_events)
```
to
```
import rx
source = rx.Observable.create(buy_stock_events)
```
and it's working |
54,417,893 | I have a business problem, I have run the regression model in python to predict my target value. When validating it with my test set I came to know that my predicted variable is very far from my actual value. Now the thing I want to extract from this model is that, which feature played the role to deviate my predicted ... | 2019/01/29 | [
"https://Stackoverflow.com/questions/54417893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4634959/"
] | It depends on the estimator you chose, linear models often have a coef\_ method you can call to get the coef used for each feature, given they are normalized this tells you what you want to know.
As told above for tree model you have the feature importance. You can also use libraries like treeinterpreter described her... | You can have a look at this -
[Feature selection](https://scikit-learn.org/stable/modules/feature_selection.html) |
54,417,893 | I have a business problem, I have run the regression model in python to predict my target value. When validating it with my test set I came to know that my predicted variable is very far from my actual value. Now the thing I want to extract from this model is that, which feature played the role to deviate my predicted ... | 2019/01/29 | [
"https://Stackoverflow.com/questions/54417893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4634959/"
] | It depends on the estimator you chose, linear models often have a coef\_ method you can call to get the coef used for each feature, given they are normalized this tells you what you want to know.
As told above for tree model you have the feature importance. You can also use libraries like treeinterpreter described her... | Check the Random [Forest Regressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html) - for performing Regression.
```py
# Example
from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import make_regression
X, y = make_regression(n_features=4, n_informa... |
58,558,135 | I'm writing a wrapper or pipeline to create a tfrecords dataset to which I would like to supply a function to apply to the dataset.
I would like to make it possible for the user to inject a function defined in another python file which is called in my script to transform the data.
Why? The only thing the user has to ... | 2019/10/25 | [
"https://Stackoverflow.com/questions/58558135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6489953/"
] | 1. Pass the name of the file as an argument to your script (and function name)
2. Read the file into a string, possibly extracting the given function
3. use Python [exec()](https://www.programiz.com/python-programming/methods/built-in/exec) to execute the code
An example:
```
file = "def fun(*args): \n return args"
... | Ok so I have composed the answer myself now using the information from comments and [this answer](https://stackoverflow.com/a/58558215/6489953).
```py
import importlib, inspect, sys, os
# path is given path to file, funcion_name is name of function and args are the function arguments
# Create package and ... |
45,346,418 | I am trying to generate word vectors using PySpark. Using gensim I can see the words and the closest words as below:
```python
sentences = open(os.getcwd() + "/tweets.txt").read().splitlines()
w2v_input=[]
for i in sentences:
tokenised=i.split()
w2v_input.append(tokenised)
model = word2vec.Word2Vec(w2v_input)
... | 2017/07/27 | [
"https://Stackoverflow.com/questions/45346418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6071445/"
] | The equivalent command in Spark is `model.getVectors()`, which again returns a dictionary. Here is a quick toy example with only 3 words (`alpha, beta, charlie`), adapted from the [documentation](https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.feature.Word2Vec):
```python
sc.version
# ... | And as suggested [here](https://stackoverflow.com/questions/48062278/would-model-getvectors-keys-return-all-the-keys-from-a-model),
if you want to include all the words in your document set the MinCount parameter accordingly (default=5):
```
word2vec = Word2Vec()
word2vec.setMinCount(1)
``` |
68,821,867 | I'm trying to install `pyinstaller 3.5` in `python 3.4.3` but i get this error:
```
ERROR: Command "python setup.py egg_info" failed with error code 1 in C:\Users\DTI~1.DES\AppData\Local\Temp\pip-install-_dyh3r_g\pefile\
```
The command i use is this:
```
pip install pyinstaller==3.5
```
I'm using the latest vers... | 2021/08/17 | [
"https://Stackoverflow.com/questions/68821867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15496915/"
] | `pefile` (one of the PyInstaller dependencies) [requires python >= 3.6.0](https://github.com/erocarrera/pefile/blob/master/setup.py#L89) | Try `pip install pyinstaller` This should work
or
If you wanted the specific version you can do that by
`pip install pyinstaller == "3.5"` |
8,011,087 | Disclaimer:
I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option.
This application was developed time ago and several developers have worked on it,
Having said that, the problem is this;
In the api for mobile of this site (just views than returns js... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150647/"
] | In your nginx configuration file (f.e. **mysite\_nginx.conf**) in the **server** section add this parameter: `uwsgi_pass_request_headers on;`.
For example:
```
server {
# the port your site will be served on
listen 8000;
...
underscores_in_headers on;
}
```
And if access to Django goes throu... | The answers above are enough for us to figure out the way. But there is still an annoying point we need to know. Yes, it is very annoying.
```
proxy_set_header X_FORWARDED_FOR # oops it never works. 1.16.1 on centos7
proxy_set_header X-FORWARDED-FOR # this will do the job
```
So you get it. Underscore could never ap... |
8,011,087 | Disclaimer:
I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option.
This application was developed time ago and several developers have worked on it,
Having said that, the problem is this;
In the api for mobile of this site (just views than returns js... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150647/"
] | If Django is accessed using uwsgi\_pass, then in the appropriate location(s) ...
```
# All request headers should be passed on by default
# Make sure "Token" response header is passed to user
uwsgi_pass_header Token;
```
If Django is accessed using fastcgi\_pass, then in the appropriate location(s) ...
```
#... | In your nginx configuration file (f.e. **mysite\_nginx.conf**) in the **server** section add this parameter: `uwsgi_pass_request_headers on;`.
For example:
```
server {
# the port your site will be served on
listen 8000;
...
underscores_in_headers on;
}
```
And if access to Django goes throu... |
8,011,087 | Disclaimer:
I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option.
This application was developed time ago and several developers have worked on it,
Having said that, the problem is this;
In the api for mobile of this site (just views than returns js... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150647/"
] | If Django is accessed using uwsgi\_pass, then in the appropriate location(s) ...
```
# All request headers should be passed on by default
# Make sure "Token" response header is passed to user
uwsgi_pass_header Token;
```
If Django is accessed using fastcgi\_pass, then in the appropriate location(s) ...
```
#... | I think this is what you need:
```
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" "$http_http_token" "$upstream_http_http_token"'
```
to log what is happening.
You might look deeper ... |
8,011,087 | Disclaimer:
I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option.
This application was developed time ago and several developers have worked on it,
Having said that, the problem is this;
In the api for mobile of this site (just views than returns js... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150647/"
] | I didn't find a **real** answer, but was able to make a workaround. I was having the same problem with RFC standard headers if-none-match and if-modified-since, so my solution is tested for those headers.
Added to my nginx config:
```
uwsgi_param HTTP_IF_NONE_MATCH $http_if_none_match;
uwsgi_param HTTP_IF_MODIFIED_SI... | The answers above are enough for us to figure out the way. But there is still an annoying point we need to know. Yes, it is very annoying.
```
proxy_set_header X_FORWARDED_FOR # oops it never works. 1.16.1 on centos7
proxy_set_header X-FORWARDED-FOR # this will do the job
```
So you get it. Underscore could never ap... |
8,011,087 | Disclaimer:
I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option.
This application was developed time ago and several developers have worked on it,
Having said that, the problem is this;
In the api for mobile of this site (just views than returns js... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150647/"
] | If Django is accessed using uwsgi\_pass, then in the appropriate location(s) ...
```
# All request headers should be passed on by default
# Make sure "Token" response header is passed to user
uwsgi_pass_header Token;
```
If Django is accessed using fastcgi\_pass, then in the appropriate location(s) ...
```
#... | I didn't find a **real** answer, but was able to make a workaround. I was having the same problem with RFC standard headers if-none-match and if-modified-since, so my solution is tested for those headers.
Added to my nginx config:
```
uwsgi_param HTTP_IF_NONE_MATCH $http_if_none_match;
uwsgi_param HTTP_IF_MODIFIED_SI... |
8,011,087 | Disclaimer:
I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option.
This application was developed time ago and several developers have worked on it,
Having said that, the problem is this;
In the api for mobile of this site (just views than returns js... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150647/"
] | I think this is what you need:
```
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" "$http_http_token" "$upstream_http_http_token"'
```
to log what is happening.
You might look deeper ... | It depends on how the custom header is named. My was in format "SomethingLike.this", it contains a dot. It was not possible to rename the header in the request, because it is not our code. So writing this would not work:
```
proxy_set_header SomethingLike.this $http_somethinglike.this;
proxy_pass_header SomethingLike... |
8,011,087 | Disclaimer:
I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option.
This application was developed time ago and several developers have worked on it,
Having said that, the problem is this;
In the api for mobile of this site (just views than returns js... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150647/"
] | I think this is what you need:
```
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" "$http_http_token" "$upstream_http_http_token"'
```
to log what is happening.
You might look deeper ... | The answers above are enough for us to figure out the way. But there is still an annoying point we need to know. Yes, it is very annoying.
```
proxy_set_header X_FORWARDED_FOR # oops it never works. 1.16.1 on centos7
proxy_set_header X-FORWARDED-FOR # this will do the job
```
So you get it. Underscore could never ap... |
8,011,087 | Disclaimer:
I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option.
This application was developed time ago and several developers have worked on it,
Having said that, the problem is this;
In the api for mobile of this site (just views than returns js... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150647/"
] | If Django is accessed using uwsgi\_pass, then in the appropriate location(s) ...
```
# All request headers should be passed on by default
# Make sure "Token" response header is passed to user
uwsgi_pass_header Token;
```
If Django is accessed using fastcgi\_pass, then in the appropriate location(s) ...
```
#... | It depends on how the custom header is named. My was in format "SomethingLike.this", it contains a dot. It was not possible to rename the header in the request, because it is not our code. So writing this would not work:
```
proxy_set_header SomethingLike.this $http_somethinglike.this;
proxy_pass_header SomethingLike... |
8,011,087 | Disclaimer:
I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option.
This application was developed time ago and several developers have worked on it,
Having said that, the problem is this;
In the api for mobile of this site (just views than returns js... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150647/"
] | I didn't find a **real** answer, but was able to make a workaround. I was having the same problem with RFC standard headers if-none-match and if-modified-since, so my solution is tested for those headers.
Added to my nginx config:
```
uwsgi_param HTTP_IF_NONE_MATCH $http_if_none_match;
uwsgi_param HTTP_IF_MODIFIED_SI... | It depends on how the custom header is named. My was in format "SomethingLike.this", it contains a dot. It was not possible to rename the header in the request, because it is not our code. So writing this would not work:
```
proxy_set_header SomethingLike.this $http_somethinglike.this;
proxy_pass_header SomethingLike... |
8,011,087 | Disclaimer:
I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option.
This application was developed time ago and several developers have worked on it,
Having said that, the problem is this;
In the api for mobile of this site (just views than returns js... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150647/"
] | In your nginx configuration file (f.e. **mysite\_nginx.conf**) in the **server** section add this parameter: `uwsgi_pass_request_headers on;`.
For example:
```
server {
# the port your site will be served on
listen 8000;
...
underscores_in_headers on;
}
```
And if access to Django goes throu... | It depends on how the custom header is named. My was in format "SomethingLike.this", it contains a dot. It was not possible to rename the header in the request, because it is not our code. So writing this would not work:
```
proxy_set_header SomethingLike.this $http_somethinglike.this;
proxy_pass_header SomethingLike... |
62,187,893 | I am new to python and I would like to print different words from the sentence. Below is the text file
```
Test.txt
1. As more than one social media historian has reminded few people, the Stonewall uprising was a rio-— more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s... | 2020/06/04 | [
"https://Stackoverflow.com/questions/62187893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11144691/"
] | here is your code:
```
datalist = ['few','people','morning','1969','majority','people','evening','1979']
with open('file.txt', 'r') as file:
data = file.read().replace('\n', ' ')
outputlist = data.replace('.','').split(" ")
for data in outputlist:
if data in datalist:
print(data)
``` | Using split("reminded"), you splitted your sentence into two pieces addressable using indexes 0 and 1, but if you want to separate the words of the second part you can do another split on space. For example:
```
line.split('reminded',1)[1].split(" ")
```
In this way you will have a list of string which contains the... |
62,187,893 | I am new to python and I would like to print different words from the sentence. Below is the text file
```
Test.txt
1. As more than one social media historian has reminded few people, the Stonewall uprising was a rio-— more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s... | 2020/06/04 | [
"https://Stackoverflow.com/questions/62187893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11144691/"
] | here is your code:
```
datalist = ['few','people','morning','1969','majority','people','evening','1979']
with open('file.txt', 'r') as file:
data = file.read().replace('\n', ' ')
outputlist = data.replace('.','').split(" ")
for data in outputlist:
if data in datalist:
print(data)
``` | ```
text = "1. This is something abc Yes I like to swim No My Hair is real.\n2. i like to bike uphill and smile"
split_text = text.split("\n", 1) #split on new line
SomeWordFirstHalf = split_text[0].split()
SomeWordSecondHalf = split_text[1].split()
print(SomeWordFirstHalf[3])
print(SomeWordSecondHalf[5])
``` |
7,538,628 | So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't r... | 2011/09/24 | [
"https://Stackoverflow.com/questions/7538628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151048/"
] | I can't find the way to trigger the commands of `virtualenvwrapper` in shell. But this trick can help: assume your env. name is `myenv`, then put following lines at the beginning of scripts:
```
ENV=myenv
source $WORKON_HOME/$ENV/bin/activate
``` | add these lines to your .bashrc or .bash\_profile
```
export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh
```
and reopen your terminal and try |
7,538,628 | So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't r... | 2011/09/24 | [
"https://Stackoverflow.com/questions/7538628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151048/"
] | I can't find the way to trigger the commands of `virtualenvwrapper` in shell. But this trick can help: assume your env. name is `myenv`, then put following lines at the beginning of scripts:
```
ENV=myenv
source $WORKON_HOME/$ENV/bin/activate
``` | Apparently, I was doing this the wrong way. Instead of saving the virtualenv's name in the .venv file, I should be putting the virtualenv's directory path.
```
(cdvirtualenv && pwd) > .venv
```
and in the `bin/run-app`, I put
```
source "$(cat .venv)/bin/activate"
python main.py
```
And yay! |
7,538,628 | So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't r... | 2011/09/24 | [
"https://Stackoverflow.com/questions/7538628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151048/"
] | It's a [known issue](https://bitbucket.org/dhellmann/virtualenvwrapper/issue/219/cant-deactivate-active-virtualenv-from). As a workaround, you can make the content of the script a function and place it in either `~/.bashrc` or `~/.profile`
```
function run-app() {
workon "$(cat .venv)"
python main.py
}
``` | add these lines to your .bashrc or .bash\_profile
```
export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh
```
and reopen your terminal and try |
7,538,628 | So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't r... | 2011/09/24 | [
"https://Stackoverflow.com/questions/7538628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151048/"
] | It's a [known issue](https://bitbucket.org/dhellmann/virtualenvwrapper/issue/219/cant-deactivate-active-virtualenv-from). As a workaround, you can make the content of the script a function and place it in either `~/.bashrc` or `~/.profile`
```
function run-app() {
workon "$(cat .venv)"
python main.py
}
``` | If your Python script requires a particular virtualenv then put/install it in virtualenv's `bin` directory. If you need access to that script outside of the environment then you could make a symlink.
main.py from virtualenv's `bin`:
```
#!/path/to/virtualenv/bin/python
import yourmodule
if __name__=="__main__":
y... |
7,538,628 | So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't r... | 2011/09/24 | [
"https://Stackoverflow.com/questions/7538628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151048/"
] | Just source the `virtualenvwrapper.sh` script in your script to import the virtualenvwrapper's functions. You should then be able to use the `workon` function in your script.
And maybe better, you could create a shell script (you could name it `venv-run.sh` for example) to run any Python script into a given virtualenv... | It's a [known issue](https://bitbucket.org/dhellmann/virtualenvwrapper/issue/219/cant-deactivate-active-virtualenv-from). As a workaround, you can make the content of the script a function and place it in either `~/.bashrc` or `~/.profile`
```
function run-app() {
workon "$(cat .venv)"
python main.py
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.