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 |
|---|---|---|---|---|---|
1,104,762 | How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case.
Correct ouptut but strangely indented:
```
if True:
print "long test long test long test long test long \
tes... | 2009/07/09 | [
"https://Stackoverflow.com/questions/1104762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] | You can use a trailing backslash to join separate strings like this:
```
if True:
print "long test long test long test long test long " \
"test long test long test long test long test long test"
``` | Why isn't anyone recommending triple quotes?
```
print """ blah blah
blah .............."""
``` |
1,104,762 | How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case.
Correct ouptut but strangely indented:
```
if True:
print "long test long test long test long test long \
tes... | 2009/07/09 | [
"https://Stackoverflow.com/questions/1104762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] | ```
if True:
print "long test long test long test long test long"\
"test long test long test long test long test long test"
``` | ```
if True:
print "long test long test long test "+
"long test long test long test "+
"long test long test long test "
```
And so on. |
1,104,762 | How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case.
Correct ouptut but strangely indented:
```
if True:
print "long test long test long test long test long \
tes... | 2009/07/09 | [
"https://Stackoverflow.com/questions/1104762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] | ```
if True:
print "long test long test long test long test long"\
"test long test long test long test long test long test"
``` | Why isn't anyone recommending triple quotes?
```
print """ blah blah
blah .............."""
``` |
1,104,762 | How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case.
Correct ouptut but strangely indented:
```
if True:
print "long test long test long test long test long \
tes... | 2009/07/09 | [
"https://Stackoverflow.com/questions/1104762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] | Why isn't anyone recommending triple quotes?
```
print """ blah blah
blah .............."""
``` | ```
if True:
print "long test long test long test "+
"long test long test long test "+
"long test long test long test "
```
And so on. |
56,680,581 | If there's a function `f(x)`, and x's type may be Int or String,
if it's Int, then this f will return `x+1`
if it's String, then f will reverse x and return it.
This is easy in dynamic typed languages like python and javascript which
just uses `isinstance(x, Int)`.
We can know its type and do something with if-else,... | 2019/06/20 | [
"https://Stackoverflow.com/questions/56680581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11674346/"
] | In kotlin you have [Arrow](https://arrow-kt.io/) that provides a lot of functional capabilities to the language. Between them you have [`EitherT`](https://arrow-kt.io/docs/arrow/data/eithert/).
That lets you define:
```
fun f(x: Either<Int, String>): Either<Int, String> =
x.bimap({ it+1 }, { it.reversed() })
``` | You could do something like:
```
fun getValue(id: Int): Any { ... }
fun process(value: Int) { ... }
fun process(value: String) { ... }
val value = getValue(valueId)
when (value) {
is Int -> process(value)
is String -> process(value)
else -> ... }
```
This way, you can use method overloading to do the job for yo... |
56,680,581 | If there's a function `f(x)`, and x's type may be Int or String,
if it's Int, then this f will return `x+1`
if it's String, then f will reverse x and return it.
This is easy in dynamic typed languages like python and javascript which
just uses `isinstance(x, Int)`.
We can know its type and do something with if-else,... | 2019/06/20 | [
"https://Stackoverflow.com/questions/56680581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11674346/"
] | sealed class E
data class L(val v: String) : E()
data class R(val v: Int): E()
fun poly(expr: E):E = when(expr) {
```
is L -> L(expr.v)
is R -> R(expr.v + 1)
```
}
println(poly(poly(R(3))))
println(poly(L("aha")))
fun poly2(expr: E):Any? = when(expr) {
```
is L -> expr.v
is R -> expr.v + 1
```
} | You could do something like:
```
fun getValue(id: Int): Any { ... }
fun process(value: Int) { ... }
fun process(value: String) { ... }
val value = getValue(valueId)
when (value) {
is Int -> process(value)
is String -> process(value)
else -> ... }
```
This way, you can use method overloading to do the job for yo... |
34,894,096 | What is the best way to read in a line of numbers from a file when they are presented in a format like this:
```
[1, 2, 3 , -4, 5]
[10, 11, -12, 13, 14 ]
```
Annoyingly, as I depicted, sometimes there are extra spaces between the numbers, sometimes not. I've attempted to use `CSV` to work around the commas, but the ... | 2016/01/20 | [
"https://Stackoverflow.com/questions/34894096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5814412/"
] | Use regular expression to remove any unwanted characters from strings
```
import re
text_ = re.sub("[0-9]+", " ", text);
```
Second Method:
```
str = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in str.split() if s.isdigit()]
[23, 11, 2]
``` | Use the [`json`](https://docs.python.org/3/library/json.html#json.loads) module to parse each line as a [JSON](http://json.org/) array.
```
import json
list_of_ints = []
for line in open("/tmp/so.txt").readlines():
a = json.loads(line)
list_of_ints.extend(a)
print(list_of_ints)
```
This collects all integer... |
34,894,096 | What is the best way to read in a line of numbers from a file when they are presented in a format like this:
```
[1, 2, 3 , -4, 5]
[10, 11, -12, 13, 14 ]
```
Annoyingly, as I depicted, sometimes there are extra spaces between the numbers, sometimes not. I've attempted to use `CSV` to work around the commas, but the ... | 2016/01/20 | [
"https://Stackoverflow.com/questions/34894096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5814412/"
] | Since each line already seems a literal python list you can use [ast](https://docs.python.org/2.7/library/ast.html) module:
```
import ast
with open('myfile.txt') as fh:
for line in fh:
numbers_list = ast.literal_eval(line)
```
Note that you could have obtained the same result using the builtin function... | Use the [`json`](https://docs.python.org/3/library/json.html#json.loads) module to parse each line as a [JSON](http://json.org/) array.
```
import json
list_of_ints = []
for line in open("/tmp/so.txt").readlines():
a = json.loads(line)
list_of_ints.extend(a)
print(list_of_ints)
```
This collects all integer... |
34,894,096 | What is the best way to read in a line of numbers from a file when they are presented in a format like this:
```
[1, 2, 3 , -4, 5]
[10, 11, -12, 13, 14 ]
```
Annoyingly, as I depicted, sometimes there are extra spaces between the numbers, sometimes not. I've attempted to use `CSV` to work around the commas, but the ... | 2016/01/20 | [
"https://Stackoverflow.com/questions/34894096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5814412/"
] | Using the [`ast.literal_eval()`](https://docs.python.org/3/library/ast.html#ast.literal_eval) is another option:
```
from ast import literal_eval
with open("your_file.txt") as file_obj:
for line in file_obj:
lst = literal_eval(line)
do_stuff(lst)
``` | Use the [`json`](https://docs.python.org/3/library/json.html#json.loads) module to parse each line as a [JSON](http://json.org/) array.
```
import json
list_of_ints = []
for line in open("/tmp/so.txt").readlines():
a = json.loads(line)
list_of_ints.extend(a)
print(list_of_ints)
```
This collects all integer... |
34,894,096 | What is the best way to read in a line of numbers from a file when they are presented in a format like this:
```
[1, 2, 3 , -4, 5]
[10, 11, -12, 13, 14 ]
```
Annoyingly, as I depicted, sometimes there are extra spaces between the numbers, sometimes not. I've attempted to use `CSV` to work around the commas, but the ... | 2016/01/20 | [
"https://Stackoverflow.com/questions/34894096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5814412/"
] | Use regular expression to remove any unwanted characters from strings
```
import re
text_ = re.sub("[0-9]+", " ", text);
```
Second Method:
```
str = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in str.split() if s.isdigit()]
[23, 11, 2]
``` | Since each line already seems a literal python list you can use [ast](https://docs.python.org/2.7/library/ast.html) module:
```
import ast
with open('myfile.txt') as fh:
for line in fh:
numbers_list = ast.literal_eval(line)
```
Note that you could have obtained the same result using the builtin function... |
34,894,096 | What is the best way to read in a line of numbers from a file when they are presented in a format like this:
```
[1, 2, 3 , -4, 5]
[10, 11, -12, 13, 14 ]
```
Annoyingly, as I depicted, sometimes there are extra spaces between the numbers, sometimes not. I've attempted to use `CSV` to work around the commas, but the ... | 2016/01/20 | [
"https://Stackoverflow.com/questions/34894096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5814412/"
] | Use regular expression to remove any unwanted characters from strings
```
import re
text_ = re.sub("[0-9]+", " ", text);
```
Second Method:
```
str = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in str.split() if s.isdigit()]
[23, 11, 2]
``` | Using the [`ast.literal_eval()`](https://docs.python.org/3/library/ast.html#ast.literal_eval) is another option:
```
from ast import literal_eval
with open("your_file.txt") as file_obj:
for line in file_obj:
lst = literal_eval(line)
do_stuff(lst)
``` |
34,894,096 | What is the best way to read in a line of numbers from a file when they are presented in a format like this:
```
[1, 2, 3 , -4, 5]
[10, 11, -12, 13, 14 ]
```
Annoyingly, as I depicted, sometimes there are extra spaces between the numbers, sometimes not. I've attempted to use `CSV` to work around the commas, but the ... | 2016/01/20 | [
"https://Stackoverflow.com/questions/34894096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5814412/"
] | Using the [`ast.literal_eval()`](https://docs.python.org/3/library/ast.html#ast.literal_eval) is another option:
```
from ast import literal_eval
with open("your_file.txt") as file_obj:
for line in file_obj:
lst = literal_eval(line)
do_stuff(lst)
``` | Since each line already seems a literal python list you can use [ast](https://docs.python.org/2.7/library/ast.html) module:
```
import ast
with open('myfile.txt') as fh:
for line in fh:
numbers_list = ast.literal_eval(line)
```
Note that you could have obtained the same result using the builtin function... |
30,798,447 | I tried the following code, but I ran into problems.
I think .values is the problem but how do I encode this as a Theano object?
The following is my data source
```
home_team,away_team,home_score,away_score
Wales,Italy,23,15
France,England,26,24
Ireland,Scotland,28,6
Ireland,Wales,26,3
Scotland,England,0,20
France,I... | 2015/06/12 | [
"https://Stackoverflow.com/questions/30798447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2610971/"
] | Here is my translation of your PyMC2 model:
```
model = pm.Model()
with pm.Model() as model:
# global model parameters
home = pm.Normal('home', 0, .0001)
tau_att = pm.Gamma('tau_att', .1, .1)
tau_def = pm.Gamma('tau_def', .1, .1)
intercept = pm.Normal('intercept', 0, .0001... | Your model is failing because you can't use NumPy functions on theano tensors. Thus
```
np.mean(atts_star3)
```
Will give you an error. You can remove `atts_star3 = pm3.Normal("atts_star",...)` and just use the NumPy array directly `atts_star3 = x`.
I don't think you need to explicitly model `tau_att3`, `tau_def3`... |
30,798,447 | I tried the following code, but I ran into problems.
I think .values is the problem but how do I encode this as a Theano object?
The following is my data source
```
home_team,away_team,home_score,away_score
Wales,Italy,23,15
France,England,26,24
Ireland,Scotland,28,6
Ireland,Wales,26,3
Scotland,England,0,20
France,I... | 2015/06/12 | [
"https://Stackoverflow.com/questions/30798447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2610971/"
] | Here is my translation of your PyMC2 model:
```
model = pm.Model()
with pm.Model() as model:
# global model parameters
home = pm.Normal('home', 0, .0001)
tau_att = pm.Gamma('tau_att', .1, .1)
tau_def = pm.Gamma('tau_def', .1, .1)
intercept = pm.Normal('intercept', 0, .0001... | So I did this. It isn't a direct port of my previous version but it gives me an answer. Does anyone have any feedback?
```
import os
import math
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pymc3 as pm3# I know folks are switching to "as pm" but I'm just not there yet
%... |
61,195,729 | I have been working with binance websocket. Worked well if the start/stop command is in the main programm. Now I wanted to start and stop the socket through a GUI. So I placed the start/stop command in a function each. But it doesn't work. Just no reaction while calling the function. Any idea what's the problem?
Here ... | 2020/04/13 | [
"https://Stackoverflow.com/questions/61195729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13305068/"
] | Whatever user is executing that code, does not have permission to write to that file path. If you go to C:\Users\chris\Source\Repos\inventory2.0\PIC\_Program\_1.0\Content\images\Components, right click, properties, Security tab, you will see the users that have permissions and what those permissions are. You can add or... | I think the problem is your application user don't have permission to access your the folder. If you are testing this in VS IIS express, then you should grant permission for your current user.
However, if you are receiving this error message from IIS Server. Then you should grant permission for application pool ident... |
52,436,084 | I have a word list and I need to find the count of words that are present in the string.
eg:
```
text_string = 'I came, I saw, I conquered!'
word_list=['I','saw','Britain']
```
I require a python script that prints
```
{‘i’:3,’saw’:1,’britain':0}
``` | 2018/09/21 | [
"https://Stackoverflow.com/questions/52436084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9635284/"
] | You can use a [property accessor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) to reference `mutableValue` from accessing the property `a` like this:
```js
let mutableValue = 3
const obj = { get a() { return mutableValue } }
console.log(obj.a)
mutableValue = 4
co... | object -> reference values
try
```
let mutableValue = {aa: 3}
const getText = () => mutableValue
const obj = {a: getText()}
```
run
```
obj.a// {aa: 3}
mutableValue.aa = 4
obj.a// {aa: 4}
``` |
52,436,084 | I have a word list and I need to find the count of words that are present in the string.
eg:
```
text_string = 'I came, I saw, I conquered!'
word_list=['I','saw','Britain']
```
I require a python script that prints
```
{‘i’:3,’saw’:1,’britain':0}
``` | 2018/09/21 | [
"https://Stackoverflow.com/questions/52436084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9635284/"
] | In order to mutate you have to keep the value in an object for example
```
let mutatingObject = {
mutableValue: 3
};
const getText = () => mutatingObject ;
const obj12 = {
a: getText()
}
mutatingObject.mutableValue=4;
console.log(obj12.a);
``... | object -> reference values
try
```
let mutableValue = {aa: 3}
const getText = () => mutableValue
const obj = {a: getText()}
```
run
```
obj.a// {aa: 3}
mutableValue.aa = 4
obj.a// {aa: 4}
``` |
58,901,682 | First of all i tried command from their main page, that they gave me:
```
pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html
```
Could not find a version that satisfies the requirement torch==1.3.1+cpu (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)
ERROR: No ... | 2019/11/17 | [
"https://Stackoverflow.com/questions/58901682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8037832/"
] | There is no any wheels for Python 3.8 at <https://download.pytorch.org/whl/torch_stable.html>.
>
> not supported wheel on my platform
>
>
>
This is because the wheel is for Python 3.7.
Advice: downgrade to Python 3.7. | Adding to @phd's answer, you could consider [installing from source](https://github.com/pytorch/pytorch#from-source). Note that I have built PyTorch from the source in the past (and it was a mostly straightforward process) but I have not done this on windows or for Python 3.8. |
58,901,682 | First of all i tried command from their main page, that they gave me:
```
pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html
```
Could not find a version that satisfies the requirement torch==1.3.1+cpu (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)
ERROR: No ... | 2019/11/17 | [
"https://Stackoverflow.com/questions/58901682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8037832/"
] | There is no any wheels for Python 3.8 at <https://download.pytorch.org/whl/torch_stable.html>.
>
> not supported wheel on my platform
>
>
>
This is because the wheel is for Python 3.7.
Advice: downgrade to Python 3.7. | windows
-check your system is 32 or 64 bit
-check your python is 32 or 64 bit
match your system and python version
check if pip is installed by
pip --version
install CUDA 10.2(i didn't check for CUDA 11(latest at the time of writing))
got to pytorch and select your the option and copy past the command in cmd |
58,901,682 | First of all i tried command from their main page, that they gave me:
```
pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html
```
Could not find a version that satisfies the requirement torch==1.3.1+cpu (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)
ERROR: No ... | 2019/11/17 | [
"https://Stackoverflow.com/questions/58901682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8037832/"
] | There is no any wheels for Python 3.8 at <https://download.pytorch.org/whl/torch_stable.html>.
>
> not supported wheel on my platform
>
>
>
This is because the wheel is for Python 3.7.
Advice: downgrade to Python 3.7. | ```
pip install numpy
pip install --pre torch torchvision -f https://download.pytorch.org/whl/nightly/cu102/torch_nightly.html
``` |
58,901,682 | First of all i tried command from their main page, that they gave me:
```
pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html
```
Could not find a version that satisfies the requirement torch==1.3.1+cpu (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)
ERROR: No ... | 2019/11/17 | [
"https://Stackoverflow.com/questions/58901682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8037832/"
] | There is no any wheels for Python 3.8 at <https://download.pytorch.org/whl/torch_stable.html>.
>
> not supported wheel on my platform
>
>
>
This is because the wheel is for Python 3.7.
Advice: downgrade to Python 3.7. | Also see this issue that currently affects Windows installations (even if you downgrade to Python 3.7):
<https://github.com/pytorch/pytorch/issues/54172>
TL;DR run this command instead:
```
pip install torch==1.8.0+cu101 torchvision==0.9.0+cu101 torchaudio===0.8.0 -f https://download.pytorch.org/whl/torch_stable.html... |
58,901,682 | First of all i tried command from their main page, that they gave me:
```
pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html
```
Could not find a version that satisfies the requirement torch==1.3.1+cpu (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)
ERROR: No ... | 2019/11/17 | [
"https://Stackoverflow.com/questions/58901682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8037832/"
] | Adding to @phd's answer, you could consider [installing from source](https://github.com/pytorch/pytorch#from-source). Note that I have built PyTorch from the source in the past (and it was a mostly straightforward process) but I have not done this on windows or for Python 3.8. | windows
-check your system is 32 or 64 bit
-check your python is 32 or 64 bit
match your system and python version
check if pip is installed by
pip --version
install CUDA 10.2(i didn't check for CUDA 11(latest at the time of writing))
got to pytorch and select your the option and copy past the command in cmd |
58,901,682 | First of all i tried command from their main page, that they gave me:
```
pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html
```
Could not find a version that satisfies the requirement torch==1.3.1+cpu (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)
ERROR: No ... | 2019/11/17 | [
"https://Stackoverflow.com/questions/58901682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8037832/"
] | Adding to @phd's answer, you could consider [installing from source](https://github.com/pytorch/pytorch#from-source). Note that I have built PyTorch from the source in the past (and it was a mostly straightforward process) but I have not done this on windows or for Python 3.8. | ```
pip install numpy
pip install --pre torch torchvision -f https://download.pytorch.org/whl/nightly/cu102/torch_nightly.html
``` |
58,901,682 | First of all i tried command from their main page, that they gave me:
```
pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html
```
Could not find a version that satisfies the requirement torch==1.3.1+cpu (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)
ERROR: No ... | 2019/11/17 | [
"https://Stackoverflow.com/questions/58901682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8037832/"
] | Adding to @phd's answer, you could consider [installing from source](https://github.com/pytorch/pytorch#from-source). Note that I have built PyTorch from the source in the past (and it was a mostly straightforward process) but I have not done this on windows or for Python 3.8. | Also see this issue that currently affects Windows installations (even if you downgrade to Python 3.7):
<https://github.com/pytorch/pytorch/issues/54172>
TL;DR run this command instead:
```
pip install torch==1.8.0+cu101 torchvision==0.9.0+cu101 torchaudio===0.8.0 -f https://download.pytorch.org/whl/torch_stable.html... |
12,938,786 | Im trying to pass a sql ( wich works perfectly if i run it on the client ) inside my python script, but i receive the error "not enough arguments for format string"
Following, the code:
```
sql = """
SELECT
rr.iserver,
foo.*, rr.queue_capacity,
rr.queue_refill_level,
rr.is_concurrent,
rr.max_executi... | 2012/10/17 | [
"https://Stackoverflow.com/questions/12938786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1323826/"
] | ```
WHERE
TRIGGER LIKE '%(package)s%'
```
you have an EXTRA '%'
if you want the actual character '%', you need to escape with a double '%'.
so it should be
```
WHERE
TRIGGER LIKE '%(package)s%%'
```
if you want to display a '%'
and
```
WHERE
TRIGGER LIKE '%(pac... | Don't build SQL like this using `%`:
```
"SELECT %(foo)s FROM bar WHERE %(baz)s" %
{"foo": "FOO", "baz": "1=1;-- DROP TABLE bar;"}
```
This opens the door for nasty SQL injection attacks.
Use the proper form of your [Python Database API Specification v2.0](http://www.python.org/dev/peps/pep-0249/) adapter. For Ps... |
54,311,678 | I have a UDP socket application where I am working on the server side. To test the server side I put together a simple python client program that sends the message "hello world how are you". The server, should then receive the message, convert to uppercase and send back to the client. The problem lies here: I can obser... | 2019/01/22 | [
"https://Stackoverflow.com/questions/54311678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5970879/"
] | **Quick and dirty:**
Remove this line from your C code:
```
claddr.sin_port = htons(PORT_NUM);
```
**Now why:**
When you send a message in your python script, your operating system will fill a [UDP packet](https://en.wikipedia.org/wiki/User_Datagram_Protocol) with the destination IP address and port you specified,... | N. Dijkhoffz, Would love to hear how you fixed it and perhaps post the correct code. |
36,965,951 | I'm begineer in python. I'm bit confused about this basic python program and its output
```
for num in range(2,10):
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
```
output
```
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (In... | 2016/05/01 | [
"https://Stackoverflow.com/questions/36965951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5483135/"
] | You can use `ajax`.
**timestamp.php**
```
<?php
date_default_timezone_set('YOUR TIMEZONE');
echo $timestamp = date('H:i:s');
```
**jQuery**
```
$(document).ready(function() {
setInterval(timestamp, 1000);
});
function timestamp() {
$.ajax({
url: 'http://localhost/timestamp.php',
su... | PHP is a server-side programming language, Javascript is a client-side programming language.
The PHP code that fills the variables will only update when the webpage is loaded, after that you are left with Javascript code and nothing more.
I recommend you to search a basic programming book which mentions concepts such... |
36,965,951 | I'm begineer in python. I'm bit confused about this basic python program and its output
```
for num in range(2,10):
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
```
output
```
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (In... | 2016/05/01 | [
"https://Stackoverflow.com/questions/36965951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5483135/"
] | You can use `ajax`.
**timestamp.php**
```
<?php
date_default_timezone_set('YOUR TIMEZONE');
echo $timestamp = date('H:i:s');
```
**jQuery**
```
$(document).ready(function() {
setInterval(timestamp, 1000);
});
function timestamp() {
$.ajax({
url: 'http://localhost/timestamp.php',
su... | I would send the timestamp across from the server just to get a snapshot of the current server time and then let JS take over from there. JS can keep the local clock pretty close to being synced with your server and you could run a new ajax call every x number of minutes/hours to resync with a fresh timestamp.
I haven... |
58,543,054 | I am trying to use pyspark to preprocess data for the prediction model.
I get an error when I try spark.createDataFrame out of my preprocessing.Is there a way to check how processedRDD look like before making it to dataframe?
```
import findspark
findspark.init('/usr/local/spark')
import pyspark
from p... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58543054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9240223/"
] | I don't know what this script has to do with Django exactly, but adding the following lines at the top of the script will probably fix this issue:
```
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
import django
django.setup()
``` | Basically, you need to load your settings and populate Django’s application registry before doing anything else. You have all the information required in the Django docs.
<https://docs.djangoproject.com/en/2.2/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage> |
58,543,054 | I am trying to use pyspark to preprocess data for the prediction model.
I get an error when I try spark.createDataFrame out of my preprocessing.Is there a way to check how processedRDD look like before making it to dataframe?
```
import findspark
findspark.init('/usr/local/spark')
import pyspark
from p... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58543054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9240223/"
] | I don't know what this script has to do with Django exactly, but adding the following lines at the top of the script will probably fix this issue:
```
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
import django
django.setup()
``` | Instead of manualy running Hadoop I am making a python server which is using pyspack and calculate 10 times faster heavy AI algorithms on Django server. The problem I had came from SPARK-LOCAL-IP, different IP was used (the one I use to connect to a remote database vis sshtunnel). I import and use pyspark. I had to ren... |
149,474 | This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.
```
big_story_export.xml
```
turns into
```
lifestyles.xml
food.xml
nascar.xml
```
...and so on.
I got the job done using a one-off python script, *however*, **I origi... | 2008/09/29 | [
"https://Stackoverflow.com/questions/149474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22491/"
] | This sounds like a bug in the large XML file or the XSLT processor. There are two things you should check on your file.
1. Is the file well-formed XML? That is, are all tags and attributes properly terminated and matched? An XML processor, like [xmlstarlet](http://xmlstar.sourceforge.net/), can tell you that.
2. Does ... | What language/parser were you using?
For large files I try to use Unix command line tools.
They are usually much, much more efficient than other solutions and don't "crap out" on large files.
Try using `xsltproc` |
149,474 | This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.
```
big_story_export.xml
```
turns into
```
lifestyles.xml
food.xml
nascar.xml
```
...and so on.
I got the job done using a one-off python script, *however*, **I origi... | 2008/09/29 | [
"https://Stackoverflow.com/questions/149474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22491/"
] | The problem with using XSLT to process arbitrarily large XML documents is that XSLT processing begins by parsing the input document into a source tree. This tree gets parsed into memory. This means that eventually you'll encounter an input document large enough to cause problems even if you're using a robust XSLT proce... | What language/parser were you using?
For large files I try to use Unix command line tools.
They are usually much, much more efficient than other solutions and don't "crap out" on large files.
Try using `xsltproc` |
149,474 | This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.
```
big_story_export.xml
```
turns into
```
lifestyles.xml
food.xml
nascar.xml
```
...and so on.
I got the job done using a one-off python script, *however*, **I origi... | 2008/09/29 | [
"https://Stackoverflow.com/questions/149474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22491/"
] | What language/parser were you using?
For large files I try to use Unix command line tools.
They are usually much, much more efficient than other solutions and don't "crap out" on large files.
Try using `xsltproc` | Check out Apache's [Xalan C++](http://xml.apache.org/xalan-c/index.html). In my experience, where others (including Saxon) have failed on "large" XML files (>600 MB), this was able to run with memory to spare. |
149,474 | This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.
```
big_story_export.xml
```
turns into
```
lifestyles.xml
food.xml
nascar.xml
```
...and so on.
I got the job done using a one-off python script, *however*, **I origi... | 2008/09/29 | [
"https://Stackoverflow.com/questions/149474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22491/"
] | This sounds like a bug in the large XML file or the XSLT processor. There are two things you should check on your file.
1. Is the file well-formed XML? That is, are all tags and attributes properly terminated and matched? An XML processor, like [xmlstarlet](http://xmlstar.sourceforge.net/), can tell you that.
2. Does ... | Can I recommend Saxon XSLT processor - I know for a fact it can handle large files, provided you give the Java JVM enough memory.
Another thing is that there may be optimisations n your XSLT that could help, but its hard to make blanket statements about things like that. |
149,474 | This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.
```
big_story_export.xml
```
turns into
```
lifestyles.xml
food.xml
nascar.xml
```
...and so on.
I got the job done using a one-off python script, *however*, **I origi... | 2008/09/29 | [
"https://Stackoverflow.com/questions/149474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22491/"
] | This sounds like a bug in the large XML file or the XSLT processor. There are two things you should check on your file.
1. Is the file well-formed XML? That is, are all tags and attributes properly terminated and matched? An XML processor, like [xmlstarlet](http://xmlstar.sourceforge.net/), can tell you that.
2. Does ... | Check out Apache's [Xalan C++](http://xml.apache.org/xalan-c/index.html). In my experience, where others (including Saxon) have failed on "large" XML files (>600 MB), this was able to run with memory to spare. |
149,474 | This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.
```
big_story_export.xml
```
turns into
```
lifestyles.xml
food.xml
nascar.xml
```
...and so on.
I got the job done using a one-off python script, *however*, **I origi... | 2008/09/29 | [
"https://Stackoverflow.com/questions/149474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22491/"
] | The problem with using XSLT to process arbitrarily large XML documents is that XSLT processing begins by parsing the input document into a source tree. This tree gets parsed into memory. This means that eventually you'll encounter an input document large enough to cause problems even if you're using a robust XSLT proce... | Can I recommend Saxon XSLT processor - I know for a fact it can handle large files, provided you give the Java JVM enough memory.
Another thing is that there may be optimisations n your XSLT that could help, but its hard to make blanket statements about things like that. |
149,474 | This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.
```
big_story_export.xml
```
turns into
```
lifestyles.xml
food.xml
nascar.xml
```
...and so on.
I got the job done using a one-off python script, *however*, **I origi... | 2008/09/29 | [
"https://Stackoverflow.com/questions/149474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22491/"
] | Can I recommend Saxon XSLT processor - I know for a fact it can handle large files, provided you give the Java JVM enough memory.
Another thing is that there may be optimisations n your XSLT that could help, but its hard to make blanket statements about things like that. | Check out Apache's [Xalan C++](http://xml.apache.org/xalan-c/index.html). In my experience, where others (including Saxon) have failed on "large" XML files (>600 MB), this was able to run with memory to spare. |
149,474 | This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.
```
big_story_export.xml
```
turns into
```
lifestyles.xml
food.xml
nascar.xml
```
...and so on.
I got the job done using a one-off python script, *however*, **I origi... | 2008/09/29 | [
"https://Stackoverflow.com/questions/149474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22491/"
] | The problem with using XSLT to process arbitrarily large XML documents is that XSLT processing begins by parsing the input document into a source tree. This tree gets parsed into memory. This means that eventually you'll encounter an input document large enough to cause problems even if you're using a robust XSLT proce... | Check out Apache's [Xalan C++](http://xml.apache.org/xalan-c/index.html). In my experience, where others (including Saxon) have failed on "large" XML files (>600 MB), this was able to run with memory to spare. |
56,921,192 | I have created a text file using file operations in python. I want the file to be pushed to my existed GITLAB repository.
I have tried the below code where i get the created file in my local folders.
```
file_path = 'E:\My material\output.txt'
k= 'Fail/Pass'
with open (file_path, 'w+') as text:
text.write('Test ... | 2019/07/07 | [
"https://Stackoverflow.com/questions/56921192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7547718/"
] | You can use `.loc` and column names in the following way:
```
import pandas as pd
import numpy as np
np.random.seed(12)
df = pd.DataFrame(
{
"df0" : np.random.choice(["a", "b"], 100),
"df1" : np.random.randint(0, 15, 100),
"df2" : np.random.randint(0, 15, 100),
"df3" : np.random.... | I think you were doing correct you need to define all columns you need to multiply
```
df.iloc[:,1:] = df.iloc[:,1:]*l
``` |
56,921,192 | I have created a text file using file operations in python. I want the file to be pushed to my existed GITLAB repository.
I have tried the below code where i get the created file in my local folders.
```
file_path = 'E:\My material\output.txt'
k= 'Fail/Pass'
with open (file_path, 'w+') as text:
text.write('Test ... | 2019/07/07 | [
"https://Stackoverflow.com/questions/56921192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7547718/"
] | You can use `.loc` and column names in the following way:
```
import pandas as pd
import numpy as np
np.random.seed(12)
df = pd.DataFrame(
{
"df0" : np.random.choice(["a", "b"], 100),
"df1" : np.random.randint(0, 15, 100),
"df2" : np.random.randint(0, 15, 100),
"df3" : np.random.... | Use [`DataFrame.iloc`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html) and multiple all columns without first:
```
l = [2, 3, 1, 4]
df.iloc[:, 1:] *= l
print (df)
Name c1 c2 c3 c4
0 a1 2 6 2 12
1 a2 4 3 1 8
2 a3 6 3 2 4
3 a4 4 9 3 16
``... |
56,921,192 | I have created a text file using file operations in python. I want the file to be pushed to my existed GITLAB repository.
I have tried the below code where i get the created file in my local folders.
```
file_path = 'E:\My material\output.txt'
k= 'Fail/Pass'
with open (file_path, 'w+') as text:
text.write('Test ... | 2019/07/07 | [
"https://Stackoverflow.com/questions/56921192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7547718/"
] | I think you were doing correct you need to define all columns you need to multiply
```
df.iloc[:,1:] = df.iloc[:,1:]*l
``` | Use [`DataFrame.iloc`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html) and multiple all columns without first:
```
l = [2, 3, 1, 4]
df.iloc[:, 1:] *= l
print (df)
Name c1 c2 c3 c4
0 a1 2 6 2 12
1 a2 4 3 1 8
2 a3 6 3 2 4
3 a4 4 9 3 16
``... |
31,745,613 | I have the below mysql table. I need to pull out the first two rows as a dictionary using python. I am using python 2.7.
```
C1 C2 C3 C4 C5 C6 C7
25 33 76 87 56 76 47
67 94 90 56 77 32 84
53 66 24 93 33 88 99
73 34 52 85 67 ... | 2015/07/31 | [
"https://Stackoverflow.com/questions/31745613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070767/"
] | [`dict` keys have no easily predictable order](https://stackoverflow.com/q/4458169/190597). To obtain the database table fields in the order in which they appear in the database, use the cursor's [description attribute](https://www.python.org/dev/peps/pep-0249/#description):
```
fields = [item[0] for item in cursor.de... | Instead of
```
data_keys = data.keys()
```
Try:
```
data_keys = exp_cur.column_names
```
Source: [10.5.11 Property MySQLCursor.column\_names](http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html) |
31,745,613 | I have the below mysql table. I need to pull out the first two rows as a dictionary using python. I am using python 2.7.
```
C1 C2 C3 C4 C5 C6 C7
25 33 76 87 56 76 47
67 94 90 56 77 32 84
53 66 24 93 33 88 99
73 34 52 85 67 ... | 2015/07/31 | [
"https://Stackoverflow.com/questions/31745613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070767/"
] | Instead of
```
data_keys = data.keys()
```
Try:
```
data_keys = exp_cur.column_names
```
Source: [10.5.11 Property MySQLCursor.column\_names](http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html) | While creating the cursor pass an argument as `dictionary=True`.
example:
```
exp = MySQLdb.connect(host,port,user,passwd,db)
exp_cur = van.cursor(dictionary=True)
```
Now when you will fetch the data, you will get a dictionary as a result. |
31,745,613 | I have the below mysql table. I need to pull out the first two rows as a dictionary using python. I am using python 2.7.
```
C1 C2 C3 C4 C5 C6 C7
25 33 76 87 56 76 47
67 94 90 56 77 32 84
53 66 24 93 33 88 99
73 34 52 85 67 ... | 2015/07/31 | [
"https://Stackoverflow.com/questions/31745613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070767/"
] | [`dict` keys have no easily predictable order](https://stackoverflow.com/q/4458169/190597). To obtain the database table fields in the order in which they appear in the database, use the cursor's [description attribute](https://www.python.org/dev/peps/pep-0249/#description):
```
fields = [item[0] for item in cursor.de... | While creating the cursor pass an argument as `dictionary=True`.
example:
```
exp = MySQLdb.connect(host,port,user,passwd,db)
exp_cur = van.cursor(dictionary=True)
```
Now when you will fetch the data, you will get a dictionary as a result. |
67,384,831 | Using this option in python it is possible to calculate the mean from multiple csv file
If file1.csv through file100.csv are all in the same directory, you can use this Python script:
```
#!/usr/bin/env python3
N = 100
mean_sum = 0
std_sum = 0
for i in range(1, N + 1):
with open(f"file{i}.csv") as f:
mea... | 2021/05/04 | [
"https://Stackoverflow.com/questions/67384831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14961922/"
] | Try the following
**Solution 1, create a new axios instance in your plugins folder:**
```
export default function ({ $axios }, inject) {
// Create a custom axios instance
const api = $axios.create({
headers: {
// headers you need
}
})
// Inject to context as $api
inject... | You can pass the below configuration to `nuxt-auth`. Beware, those `plugins` are not related to the root configuration, but related to the `nuxt-auth` package.
`nuxt.config.js`
```js
auth: {
redirect: {
login: '/login',
home: '/',
logout: '/login',
callback: false,
},
strategies: {
...
},
... |
35,387,277 | Is there a way in python with selenium that instead of selecting an option using a value or name from a drop down menu, that I can select an option via count? Like select option 1 and another example select option 2. This is because it's a possibility that a value or text of a drop down menu option can change so to ens... | 2016/02/14 | [
"https://Stackoverflow.com/questions/35387277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096892/"
] | If this represents the way you have been trying to match output, it's your problem:
```
while(reader.readLine() != "\u001B") {}
```
Except in special cases, you have to use the `equals()` method on `String` instances:
```
while (true) {
String line = reader.readLine();
if ((line == null) || "\u001B".equals(line... | I believe you need to call the Process.waitFor() method.
So you need something like:
```
Process p = build.start();
p.waitFor()
```
If you are trying to simulate a bash shell, allowing input of a command, executing, and processing output without terminating. There is an open source project that may be a good referen... |
60,959,688 | I have a python2 script I want to run with the [pwntools python module](https://github.com/Gallopsled/pwntools) and I tried running it using:
>
> python test.py
>
>
>
But then I get:
>
> File "test.py", line 3, in
> from pwn import \*
> ImportError: No module named pwn
>
>
>
But when I try it with python... | 2020/03/31 | [
"https://Stackoverflow.com/questions/60959688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12941653/"
] | **Yes**,
It's absolutely possible to include a `JavaScript` object into `makeStyles`.
Thanks to the `spread` operator.
>
> Advice is to spread over the object first, so that you can easily override any styles.
>
> Therefore it's preferred to do as follows.
>
>
>
```js
const useStyles = makeStyles(theme =... | For the benefit of future posters, the code in my original post worked perfectly, I just had something overriding it later! (Without the callback function it was undefined) – H Capello just |
65,370,140 | Thanks for looking into this, I have a python program for which I need to have `process_tweet` and `build_freqs` for some NLP task, `nltk` is installed already and `utils` **wasn't** so I installed it via `pip install utils` but the above mentioned two modules apparently weren't installed, the error I got is standard o... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65370140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779635/"
] | You can easily access any source code with ??, for example in this case: process\_tweet?? (the code above from deeplearning.ai NLP course custome utils library):
```
def process_tweet(tweet):
"""Process tweet function.
Input:
tweet: a string containing a tweet
Output:
tweets_clean: a list of words containing t... | Try this code, It should work:
```
def process_tweet(tweet):
stemmer = PorterStemmer()
stopwords_english = stopwords.words('english')
tweet = re.sub(r'\$\w*', '', tweet)
tweet = re.sub(r'^RT[\s]+', '', tweet)
tweet = re.sub(r'https?:\/\/.*[\r\n]*', '', tweet)
tweet = re.sub(r'#', '', tweet)
tokenizer = TweetTokenizer(... |
65,370,140 | Thanks for looking into this, I have a python program for which I need to have `process_tweet` and `build_freqs` for some NLP task, `nltk` is installed already and `utils` **wasn't** so I installed it via `pip install utils` but the above mentioned two modules apparently weren't installed, the error I got is standard o... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65370140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779635/"
] | Try this code, It should work:
```
def process_tweet(tweet):
stemmer = PorterStemmer()
stopwords_english = stopwords.words('english')
tweet = re.sub(r'\$\w*', '', tweet)
tweet = re.sub(r'^RT[\s]+', '', tweet)
tweet = re.sub(r'https?:\/\/.*[\r\n]*', '', tweet)
tweet = re.sub(r'#', '', tweet)
tokenizer = TweetTokenizer(... | I guess you don't need to use `process_tweet` as all. The code in the course is just a shortcut to summarize everything you do from the beginning to the stemming step; hence, just ignore the step and just print out the `tweet_stem` to see the difference between original text and preprocessed text. |
65,370,140 | Thanks for looking into this, I have a python program for which I need to have `process_tweet` and `build_freqs` for some NLP task, `nltk` is installed already and `utils` **wasn't** so I installed it via `pip install utils` but the above mentioned two modules apparently weren't installed, the error I got is standard o... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65370140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779635/"
] | Try this code, It should work:
```
def process_tweet(tweet):
stemmer = PorterStemmer()
stopwords_english = stopwords.words('english')
tweet = re.sub(r'\$\w*', '', tweet)
tweet = re.sub(r'^RT[\s]+', '', tweet)
tweet = re.sub(r'https?:\/\/.*[\r\n]*', '', tweet)
tweet = re.sub(r'#', '', tweet)
tokenizer = TweetTokenizer(... | You can try this.
```
def preprocess_tweet(tweet):
# cleaning
tweet = re.sub(r'^RT[\s]+','',tweet)
tweet = re.sub(r'https?://[^\s\n\r]+', '', tweet)
tweet = re.sub(r'#', '',tweet)
tweet= re.sub(r'@', '',tweet)
# tokenization
token = TweetTokenizer(preserve_case=False, strip_handles=True,reduce_len=True)
tweet_to... |
65,370,140 | Thanks for looking into this, I have a python program for which I need to have `process_tweet` and `build_freqs` for some NLP task, `nltk` is installed already and `utils` **wasn't** so I installed it via `pip install utils` but the above mentioned two modules apparently weren't installed, the error I got is standard o... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65370140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779635/"
] | You can easily access any source code with ??, for example in this case: process\_tweet?? (the code above from deeplearning.ai NLP course custome utils library):
```
def process_tweet(tweet):
"""Process tweet function.
Input:
tweet: a string containing a tweet
Output:
tweets_clean: a list of words containing t... | If you are following the NLP course on deeplearning.ai, then I believe the utils.py file was created by the instructors of that course, for use within the lab sessions, and shouldn't be confused with the usual utils. |
65,370,140 | Thanks for looking into this, I have a python program for which I need to have `process_tweet` and `build_freqs` for some NLP task, `nltk` is installed already and `utils` **wasn't** so I installed it via `pip install utils` but the above mentioned two modules apparently weren't installed, the error I got is standard o... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65370140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779635/"
] | If you are following the NLP course on deeplearning.ai, then I believe the utils.py file was created by the instructors of that course, for use within the lab sessions, and shouldn't be confused with the usual utils. | I guess you don't need to use `process_tweet` as all. The code in the course is just a shortcut to summarize everything you do from the beginning to the stemming step; hence, just ignore the step and just print out the `tweet_stem` to see the difference between original text and preprocessed text. |
65,370,140 | Thanks for looking into this, I have a python program for which I need to have `process_tweet` and `build_freqs` for some NLP task, `nltk` is installed already and `utils` **wasn't** so I installed it via `pip install utils` but the above mentioned two modules apparently weren't installed, the error I got is standard o... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65370140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779635/"
] | If you are following the NLP course on deeplearning.ai, then I believe the utils.py file was created by the instructors of that course, for use within the lab sessions, and shouldn't be confused with the usual utils. | You can try this.
```
def preprocess_tweet(tweet):
# cleaning
tweet = re.sub(r'^RT[\s]+','',tweet)
tweet = re.sub(r'https?://[^\s\n\r]+', '', tweet)
tweet = re.sub(r'#', '',tweet)
tweet= re.sub(r'@', '',tweet)
# tokenization
token = TweetTokenizer(preserve_case=False, strip_handles=True,reduce_len=True)
tweet_to... |
65,370,140 | Thanks for looking into this, I have a python program for which I need to have `process_tweet` and `build_freqs` for some NLP task, `nltk` is installed already and `utils` **wasn't** so I installed it via `pip install utils` but the above mentioned two modules apparently weren't installed, the error I got is standard o... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65370140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779635/"
] | You can easily access any source code with ??, for example in this case: process\_tweet?? (the code above from deeplearning.ai NLP course custome utils library):
```
def process_tweet(tweet):
"""Process tweet function.
Input:
tweet: a string containing a tweet
Output:
tweets_clean: a list of words containing t... | I guess you don't need to use `process_tweet` as all. The code in the course is just a shortcut to summarize everything you do from the beginning to the stemming step; hence, just ignore the step and just print out the `tweet_stem` to see the difference between original text and preprocessed text. |
65,370,140 | Thanks for looking into this, I have a python program for which I need to have `process_tweet` and `build_freqs` for some NLP task, `nltk` is installed already and `utils` **wasn't** so I installed it via `pip install utils` but the above mentioned two modules apparently weren't installed, the error I got is standard o... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65370140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779635/"
] | You can easily access any source code with ??, for example in this case: process\_tweet?? (the code above from deeplearning.ai NLP course custome utils library):
```
def process_tweet(tweet):
"""Process tweet function.
Input:
tweet: a string containing a tweet
Output:
tweets_clean: a list of words containing t... | You can try this.
```
def preprocess_tweet(tweet):
# cleaning
tweet = re.sub(r'^RT[\s]+','',tweet)
tweet = re.sub(r'https?://[^\s\n\r]+', '', tweet)
tweet = re.sub(r'#', '',tweet)
tweet= re.sub(r'@', '',tweet)
# tokenization
token = TweetTokenizer(preserve_case=False, strip_handles=True,reduce_len=True)
tweet_to... |
65,370,140 | Thanks for looking into this, I have a python program for which I need to have `process_tweet` and `build_freqs` for some NLP task, `nltk` is installed already and `utils` **wasn't** so I installed it via `pip install utils` but the above mentioned two modules apparently weren't installed, the error I got is standard o... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65370140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779635/"
] | I guess you don't need to use `process_tweet` as all. The code in the course is just a shortcut to summarize everything you do from the beginning to the stemming step; hence, just ignore the step and just print out the `tweet_stem` to see the difference between original text and preprocessed text. | You can try this.
```
def preprocess_tweet(tweet):
# cleaning
tweet = re.sub(r'^RT[\s]+','',tweet)
tweet = re.sub(r'https?://[^\s\n\r]+', '', tweet)
tweet = re.sub(r'#', '',tweet)
tweet= re.sub(r'@', '',tweet)
# tokenization
token = TweetTokenizer(preserve_case=False, strip_handles=True,reduce_len=True)
tweet_to... |
25,916,444 | I would like to test, using unittest, a method which reads from a file using a context manager:
```
with open(k_file, 'r') as content_file:
content = content_file.read()
```
I don't want to have to create a file on my system so I wanted to mock it, but I'm not suceeding much at the moment. I've found [mock\_open... | 2014/09/18 | [
"https://Stackoverflow.com/questions/25916444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/914086/"
] | `mock_open()` is the way to go; you patch `open` in your code-under-test with the result of a `mock_open()` call:
```
mocked_open = unittest.mock.mock_open(read_data='file contents\nas needed\n')
with unittest.mock.patch('yourmodule.open', mocked_open, create=True):
# tests calling your code; the open function wil... | An alternative is [pyfakefs](http://github.com/jmcgeheeiv/pyfakefs). It allows you to create a fake file system, write and read files, set permissions and more without ever touching your real disk. It also contains a practical example and tutorial showing how to apply pyfakefs to both unittest and doctest. |
26,679,011 | I am trying to use mpl\_toolkits.basemap on python and everytime I use a function for plotting like drawcoastlines() or any other, the program automatically shows the plot on the screen.
My problem is that I am trying to use those programs later on an external server and it returns 'SystemExit: Unable to access the X... | 2014/10/31 | [
"https://Stackoverflow.com/questions/26679011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3510686/"
] | Use the `Agg` backend, it doesn't require a graphical environment:
Do this at the very beginning of your script:
```
import matplotlib as mpl
mpl.use('Agg')
```
See also the FAQ on [Generate images without having a window appear](http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appea... | The easiest way is to put off the interactive mode of matplotlib.
```
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
#NOT SHOW
plt.ioff()
m = Basemap(projection='robin',lon_0=0)
m.drawcoastlines()
#m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and me... |
32,567,357 | Since today i've been using [remote\_api](https://cloud.google.com/appengine/articles/remote_api) (python) to access the datastore on GAE.
I usually do `remote_api_shell.py -s <mydomain>`.
Today I tried and it fails, the error is:
>
> oauth2client.client.ApplicationDefaultCredentialsError: The
> Application Defaul... | 2015/09/14 | [
"https://Stackoverflow.com/questions/32567357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257185/"
] | You could try implementing [SignalR](http://www.asp.net/signalr/overview/deployment/tutorial-signalr-self-host). It is a great library that uses web sockets to push data to clients.
Edit:
SignalR can help you solve your problem by allowing you to set up Hubs on your console app (server) that WPF application (clients)... | You need to create some kind of subscription model for the clients to the server to handle a Publish-Subscribe channel (see <http://www.enterpriseintegrationpatterns.com/patterns/messaging/PublishSubscribeChannel.html>). The basic architecture is this:
1. Client sends a request to the messaging channel to register its... |
32,567,357 | Since today i've been using [remote\_api](https://cloud.google.com/appengine/articles/remote_api) (python) to access the datastore on GAE.
I usually do `remote_api_shell.py -s <mydomain>`.
Today I tried and it fails, the error is:
>
> oauth2client.client.ApplicationDefaultCredentialsError: The
> Application Defaul... | 2015/09/14 | [
"https://Stackoverflow.com/questions/32567357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257185/"
] | You could try implementing [SignalR](http://www.asp.net/signalr/overview/deployment/tutorial-signalr-self-host). It is a great library that uses web sockets to push data to clients.
Edit:
SignalR can help you solve your problem by allowing you to set up Hubs on your console app (server) that WPF application (clients)... | Sounds like you want to track users à la <https://www.simple-talk.com/dotnet/asp.net/tracking-online-users-with-signalr/> , but in a desktop app in the sense of <http://www.codeproject.com/Articles/804770/Implementing-SignalR-in-Desktop-Applications> or damienbod.wordpress.com/2013/11/20/signalr-a-complete-wpf-client-u... |
32,567,357 | Since today i've been using [remote\_api](https://cloud.google.com/appengine/articles/remote_api) (python) to access the datastore on GAE.
I usually do `remote_api_shell.py -s <mydomain>`.
Today I tried and it fails, the error is:
>
> oauth2client.client.ApplicationDefaultCredentialsError: The
> Application Defaul... | 2015/09/14 | [
"https://Stackoverflow.com/questions/32567357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257185/"
] | You could try implementing [SignalR](http://www.asp.net/signalr/overview/deployment/tutorial-signalr-self-host). It is a great library that uses web sockets to push data to clients.
Edit:
SignalR can help you solve your problem by allowing you to set up Hubs on your console app (server) that WPF application (clients)... | In general, whatever solution you choose is plagued with a common problem - clients hide behind firewalls and have dynamic IP addresses. This makes it difficult (I've heard of technologies claiming to overcome this but haven't seen any in action) for a server to push to a client.
In reality, the client talks and the ... |
32,567,357 | Since today i've been using [remote\_api](https://cloud.google.com/appengine/articles/remote_api) (python) to access the datastore on GAE.
I usually do `remote_api_shell.py -s <mydomain>`.
Today I tried and it fails, the error is:
>
> oauth2client.client.ApplicationDefaultCredentialsError: The
> Application Defaul... | 2015/09/14 | [
"https://Stackoverflow.com/questions/32567357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257185/"
] | You need to create some kind of subscription model for the clients to the server to handle a Publish-Subscribe channel (see <http://www.enterpriseintegrationpatterns.com/patterns/messaging/PublishSubscribeChannel.html>). The basic architecture is this:
1. Client sends a request to the messaging channel to register its... | Sounds like you want to track users à la <https://www.simple-talk.com/dotnet/asp.net/tracking-online-users-with-signalr/> , but in a desktop app in the sense of <http://www.codeproject.com/Articles/804770/Implementing-SignalR-in-Desktop-Applications> or damienbod.wordpress.com/2013/11/20/signalr-a-complete-wpf-client-u... |
32,567,357 | Since today i've been using [remote\_api](https://cloud.google.com/appengine/articles/remote_api) (python) to access the datastore on GAE.
I usually do `remote_api_shell.py -s <mydomain>`.
Today I tried and it fails, the error is:
>
> oauth2client.client.ApplicationDefaultCredentialsError: The
> Application Defaul... | 2015/09/14 | [
"https://Stackoverflow.com/questions/32567357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257185/"
] | In general, whatever solution you choose is plagued with a common problem - clients hide behind firewalls and have dynamic IP addresses. This makes it difficult (I've heard of technologies claiming to overcome this but haven't seen any in action) for a server to push to a client.
In reality, the client talks and the ... | Sounds like you want to track users à la <https://www.simple-talk.com/dotnet/asp.net/tracking-online-users-with-signalr/> , but in a desktop app in the sense of <http://www.codeproject.com/Articles/804770/Implementing-SignalR-in-Desktop-Applications> or damienbod.wordpress.com/2013/11/20/signalr-a-complete-wpf-client-u... |
11,866,944 | I would like to be able to pickle a function or class from within \_\_main\_\_, with the obvious problem (mentioned in other posts) that the pickled function/class is in the \_\_main\_\_ namespace and unpickling in another script/module will fail.
I have the following solution which works, is there a reason this shoul... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11866944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1068490/"
] | You can get a better handle on global objects by importing `__main__`, and using the methods available in that module. This is what [dill](http://pythonhosted.org/dill) does in order to serialize almost anything in python. Basically, when dill serializes an interactively defined function, it uses some name mangling on ... | If you are trying to pickle something so that you can use it somewhere else, separate from `test_script`, that's not going to work, because pickle (apparently) just tries to load the function from the module. Here's an example:
test\_script.py
```
def my_awesome_function(x, y, z):
return x + y + z
```
picklescr... |
11,866,944 | I would like to be able to pickle a function or class from within \_\_main\_\_, with the obvious problem (mentioned in other posts) that the pickled function/class is in the \_\_main\_\_ namespace and unpickling in another script/module will fail.
I have the following solution which works, is there a reason this shoul... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11866944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1068490/"
] | Pickle seems to look at the **main** scope for definitions of classes and functions. From inside the module you're unpickling from, try this:
```
import myscript
import __main__
__main__.myclass = myscript.myclass
#unpickle anywhere after this
``` | If you are trying to pickle something so that you can use it somewhere else, separate from `test_script`, that's not going to work, because pickle (apparently) just tries to load the function from the module. Here's an example:
test\_script.py
```
def my_awesome_function(x, y, z):
return x + y + z
```
picklescr... |
11,866,944 | I would like to be able to pickle a function or class from within \_\_main\_\_, with the obvious problem (mentioned in other posts) that the pickled function/class is in the \_\_main\_\_ namespace and unpickling in another script/module will fail.
I have the following solution which works, is there a reason this shoul... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11866944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1068490/"
] | Pickle seems to look at the **main** scope for definitions of classes and functions. From inside the module you're unpickling from, try this:
```
import myscript
import __main__
__main__.myclass = myscript.myclass
#unpickle anywhere after this
``` | You can get a better handle on global objects by importing `__main__`, and using the methods available in that module. This is what [dill](http://pythonhosted.org/dill) does in order to serialize almost anything in python. Basically, when dill serializes an interactively defined function, it uses some name mangling on ... |
50,005,229 | So the assignment is:
take 2 lists and write a program that returns a list that contains only the elements that are common to the lists without duplicates, and it must work on lists of different sizes.
My code is:
```
a = [1, 2, 4]
b = [3, 1, 5, 2]
for j < len(a):
for i < len(b):
if a(elem) == b(i):
... | 2018/04/24 | [
"https://Stackoverflow.com/questions/50005229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9691751/"
] | The value is a regular JavaScript expression. This way, if you want to pass a string, say `'test'`, use:
```
v-my-directive="'test'"
```
Demo:
```js
Vue.directive('my-directive', function (el, binding) {
console.log('directive expression:', binding.value) // => "test"
})
new Vue({
el: '#app',
data: {
... | You have to quote the string, otherwise it will look for the `test` variable in your component context (its `props` or `data`):
```
v-my-directive="'test'"
```
Inside your custom directive, you can access the passed value as in the `binding.value`:
```
Vue.directive('demo', {
bind: function (el, binding, vnode) {... |
37,490,609 | i'm working on site for renting rooms. User picks 2 dates(UserStartDate & UserEndDate).
with this python code i gonna get number of days in his date range:
```
user_date_range = [endUser - timedelta(i) for i in range((endUser - startUser).days+1)]
user_range_num_days = len(user_date_range)
```
and i have a day pri... | 2016/05/27 | [
"https://Stackoverflow.com/questions/37490609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6361942/"
] | It doesn't have anything to do with django but rather python. I assume `user_start_date` and `user_end_date` are both python `datetime.date` or `datetime.datetime` objects, then you could do:
```
num_days = (user_end_date - user_start_date).days
total_price = num_days * 20
``` | <https://docs.python.org/2/library/calendar.html>
A calendar is necessary as you should be aware that not all months have the same amount of days in them. itermonthdates(year, month) returns an iterator for all days in the month. Run through that iterator and increment a count for every date match within the range. Of... |
6,831,685 | I am learning python via dive into python. Got few questions and unable to understand, even through the documentation.
1) ***BaseClass***
2) ***InheritClass***
What exactly happens when we assign a *InheritClass* instance to a variable, when the *InheritClass* doesn't contain an `__init__` method and *BaseClass* doe... | 2011/07/26 | [
"https://Stackoverflow.com/questions/6831685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/570928/"
] | Yes, `BaseClass.__init__` will be called automatically. Same goes for any other methods defined in the parent class but not the child class. Observe:
```
>>> class Parent(object):
... def __init__(self):
... print 'Parent.__init__'
... def func(self, x):
... print x
...
>>> class Child(Parent):
... pass
... | @FogleBird has already answered your question, but I wanted to add something and can't comment on his post:
You may also want to look at the [`super` function](http://docs.python.org/library/functions.html#super). It's a way to call a parent's method from inside a child. It's helpful when you want to extend a method, ... |
23,969,296 | I wanted to get number of indexes in two string which are not same.
Things that are fixed:
String data will only have 0 or 1 on any index. i.e strings are binary representation of a number.
Both the string will be of same length.
For the above problem I wrote the below function in python
```
def foo(a,b):
resu... | 2014/05/31 | [
"https://Stackoverflow.com/questions/23969296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3694018/"
] | I'll walk through the options here, but basically you are calculating the hamming distance between two numbers. There are dedicated libraries that can make this really, really fast, but lets focus on the pure Python options first.
Your approach, zipping
----------------------
`zip()` produces one big list *first*, th... | Not tested, but how would this perform:
```
sum(x!=y for x,y in zip(a,b))
``` |
23,969,296 | I wanted to get number of indexes in two string which are not same.
Things that are fixed:
String data will only have 0 or 1 on any index. i.e strings are binary representation of a number.
Both the string will be of same length.
For the above problem I wrote the below function in python
```
def foo(a,b):
resu... | 2014/05/31 | [
"https://Stackoverflow.com/questions/23969296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3694018/"
] | I'll walk through the options here, but basically you are calculating the hamming distance between two numbers. There are dedicated libraries that can make this really, really fast, but lets focus on the pure Python options first.
Your approach, zipping
----------------------
`zip()` produces one big list *first*, th... | If the strings represent binary numbers, you can convert to integers and use bitwise operators:
```
def foo(s1, s2):
# return sum(map(int, format(int(a, 2) ^ int(b, 2), 'b'))) # one-liner
a = int(s1, 2) # convert string to integer
b = int(s2, 2)
c = a ^ b # use xor to get differences
s = format(c,... |
23,969,296 | I wanted to get number of indexes in two string which are not same.
Things that are fixed:
String data will only have 0 or 1 on any index. i.e strings are binary representation of a number.
Both the string will be of same length.
For the above problem I wrote the below function in python
```
def foo(a,b):
resu... | 2014/05/31 | [
"https://Stackoverflow.com/questions/23969296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3694018/"
] | I'll walk through the options here, but basically you are calculating the hamming distance between two numbers. There are dedicated libraries that can make this really, really fast, but lets focus on the pure Python options first.
Your approach, zipping
----------------------
`zip()` produces one big list *first*, th... | Pack your strings as short integers (16 bits). After xoring, pass to a precomputed lookup table of 65536 entries that gives the number of 1s per short.
If pre-packing is not an option, switch to C++ with inline AVX2 intrinsics. They will allow you to load 32 characters in a single instruction, perform the comparisons,... |
24,502,360 | I am a Python newbie and am trying to write a numpy array into format readable in Matlab in the following format into an array [xi, yi, ti], separated by a semi-colon.
In python, I am able to currently write it in the following form, which is a numpy array printed on screen/written to file as [[xi yi ti]].
Here is th... | 2014/07/01 | [
"https://Stackoverflow.com/questions/24502360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3792245/"
] | It is not very necessary to write your `array` into a special format. Write it into a normal `csv` and use [`dlmread`](http://www.mathworks.com/help/matlab/ref/dlmread.html) to open it in `matlab`.
In `numpy` side, write your `array` using `np.savetxt('some_name.txt', aar, delimiter=' ')` | If you have scipy than you can do:
```
import scipy.io
scipy.io.savemat('/tmp/test.mat', dict(SPOT=SPOT))
```
And in matlab:
```
a=load('/tmp/test.mat');
a.SPOT % should have your data
``` |
24,502,360 | I am a Python newbie and am trying to write a numpy array into format readable in Matlab in the following format into an array [xi, yi, ti], separated by a semi-colon.
In python, I am able to currently write it in the following form, which is a numpy array printed on screen/written to file as [[xi yi ti]].
Here is th... | 2014/07/01 | [
"https://Stackoverflow.com/questions/24502360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3792245/"
] | It is not very necessary to write your `array` into a special format. Write it into a normal `csv` and use [`dlmread`](http://www.mathworks.com/help/matlab/ref/dlmread.html) to open it in `matlab`.
In `numpy` side, write your `array` using `np.savetxt('some_name.txt', aar, delimiter=' ')` | Thanks everyone and thanks @CT Zhu for letting me know!
Since I am not using Scipy, I tried using np.savetxt and it seems to work! Added the following and it writes into a format that is readable in Matlab as an array directly. Thanks again!
```
np.savetxt('test.txt', SPOT, fmt = '%10.5f', delimiter=',', newline = ... |
24,502,360 | I am a Python newbie and am trying to write a numpy array into format readable in Matlab in the following format into an array [xi, yi, ti], separated by a semi-colon.
In python, I am able to currently write it in the following form, which is a numpy array printed on screen/written to file as [[xi yi ti]].
Here is th... | 2014/07/01 | [
"https://Stackoverflow.com/questions/24502360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3792245/"
] | Try `scipy.io` to export data for `Matlab`
```
import scipy.io as sio
matlab_data = dict(SPOT=SPOT)
sio.savemat('data_dump.mat', matlab_data)
```
`data_dump.mat` is `Matlab` data. For more detail, see <http://docs.scipy.org/doc/scipy/reference/tutorial/io.html> | If you have scipy than you can do:
```
import scipy.io
scipy.io.savemat('/tmp/test.mat', dict(SPOT=SPOT))
```
And in matlab:
```
a=load('/tmp/test.mat');
a.SPOT % should have your data
``` |
24,502,360 | I am a Python newbie and am trying to write a numpy array into format readable in Matlab in the following format into an array [xi, yi, ti], separated by a semi-colon.
In python, I am able to currently write it in the following form, which is a numpy array printed on screen/written to file as [[xi yi ti]].
Here is th... | 2014/07/01 | [
"https://Stackoverflow.com/questions/24502360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3792245/"
] | Try `scipy.io` to export data for `Matlab`
```
import scipy.io as sio
matlab_data = dict(SPOT=SPOT)
sio.savemat('data_dump.mat', matlab_data)
```
`data_dump.mat` is `Matlab` data. For more detail, see <http://docs.scipy.org/doc/scipy/reference/tutorial/io.html> | Thanks everyone and thanks @CT Zhu for letting me know!
Since I am not using Scipy, I tried using np.savetxt and it seems to work! Added the following and it writes into a format that is readable in Matlab as an array directly. Thanks again!
```
np.savetxt('test.txt', SPOT, fmt = '%10.5f', delimiter=',', newline = ... |
24,502,360 | I am a Python newbie and am trying to write a numpy array into format readable in Matlab in the following format into an array [xi, yi, ti], separated by a semi-colon.
In python, I am able to currently write it in the following form, which is a numpy array printed on screen/written to file as [[xi yi ti]].
Here is th... | 2014/07/01 | [
"https://Stackoverflow.com/questions/24502360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3792245/"
] | If you have scipy than you can do:
```
import scipy.io
scipy.io.savemat('/tmp/test.mat', dict(SPOT=SPOT))
```
And in matlab:
```
a=load('/tmp/test.mat');
a.SPOT % should have your data
``` | Thanks everyone and thanks @CT Zhu for letting me know!
Since I am not using Scipy, I tried using np.savetxt and it seems to work! Added the following and it writes into a format that is readable in Matlab as an array directly. Thanks again!
```
np.savetxt('test.txt', SPOT, fmt = '%10.5f', delimiter=',', newline = ... |
65,753,830 | I'm trying to train Mask-R CNN model from cocoapi(<https://github.com/cocodataset/cocoapi>), and this error code keep come out.
```
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-8-83356bb9cf95> in <module>
19 sys.path.append(os.path.join(ROOT_DIR, "samples/... | 2021/01/16 | [
"https://Stackoverflow.com/questions/65753830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14258016/"
] | The answer is summarise from [these](https://github.com/cocodataset/cocoapi/issues/172) [three](https://github.com/cocodataset/cocoapi/issues/168) [GitHub issues](https://github.com/cocodataset/cocoapi/issues/141#issuecomment-386606299)
1.whether you have installed cython in the correct version. Namely, you should ins... | Try cloning official repo and run below commands
```
python setup.py install
make
``` |
53,469,976 | I am using the osmnx library (python) to extract the road network of a city. I also have a separate data source that corresponds to GPS coordinates being sent by vehicles as they traverse the aforementioned road network. My issue is that I only have the GPS coordinates but I wish to also know which road they correspond... | 2018/11/25 | [
"https://Stackoverflow.com/questions/53469976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10702801/"
] | You can do map matching with OSMnx. See the nearest\_nodes and nearest\_edges functions in the OSMnx documentation: <https://osmnx.readthedocs.io/> | My suggestion woud be to use the leuvenmapmatching package. You will get the details in the documentation of the package itself.
<https://github.com/wannesm/LeuvenMapMatching> |
13,793,973 | I have a string in python 3 that has several unicode representations in it, for example:
```
t = 'R\\u00f3is\\u00edn'
```
and I want to convert t so that it has the proper representation when I print it, ie:
```
>>> print(t)
Róisín
```
However I just get the original string back. I've tried re.sub and some others... | 2012/12/10 | [
"https://Stackoverflow.com/questions/13793973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1205923/"
] | You want to use the built-in codec `unicode_escape`.
If `t` is already a `bytes` (an 8-bit string), it's as simple as this:
```
>>> print(t.decode('unicode_escape'))
Róisín
```
If `t` has already been decoded to Unicode, you can to encode it back to a `bytes` and then `decode` it this way. If you're sure that all o... | First of all, it is rather confused what you what to convert to.
Just imagine that you may want to convert to 'o' and 'i'. In this case you can just make a map:
```
mp = {u'\u00f3':'o', u'\u00ed':'i'}
```
Than you may apply the replacement like:
```
t = u'R\u00f3is\u00edn'
for i in range(len(t)):
if t[i] in mp... |
13,793,973 | I have a string in python 3 that has several unicode representations in it, for example:
```
t = 'R\\u00f3is\\u00edn'
```
and I want to convert t so that it has the proper representation when I print it, ie:
```
>>> print(t)
Róisín
```
However I just get the original string back. I've tried re.sub and some others... | 2012/12/10 | [
"https://Stackoverflow.com/questions/13793973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1205923/"
] | You want to use the built-in codec `unicode_escape`.
If `t` is already a `bytes` (an 8-bit string), it's as simple as this:
```
>>> print(t.decode('unicode_escape'))
Róisín
```
If `t` has already been decoded to Unicode, you can to encode it back to a `bytes` and then `decode` it this way. If you're sure that all o... | I apologize for posting as a second answer, I don't have the reputation to comment on abarnert's solution.
After using his function to process approximately 50K android strings I noticed that there is yet another small improvement possible for certain use-cases.
I changed the + to {1,4} to deal with the case where va... |
62,502,606 | I have the following python code which should be able to read a .csv file with cities and their coordinates. The .csv file is in the form of:
```
name,x,y
name,x,y
name,x,y
```
However, I am getting the error '**list index out of range**' at line 764:
```
758 """function to calculate the route for files in data f... | 2020/06/21 | [
"https://Stackoverflow.com/questions/62502606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13722495/"
] | Change DateCutting to **DateTime** and adjust your criteria:
```vb
Dim strCriteria As String
strCriteria = "[DateCutting] >= #" & Format(Me.txtfrom, "yyyy\/mm\/dd") & "# And [DateCutting] <= #" & Format(Me.txtto, "yyyy\/mm\/dd") & "#"
DoCmd.ApplyFilter strCriteria
```
To find a number:
```
strCriteria = "[Number]... | Try
`Dim strCriteria as String`
`dim task As String` |
36,706,131 | I am having trouble getting one of my functions in python to work. The code for my function is below:
```
def checkBlackjack(value, pot, player, wager):
if (value == 21):
print("Congratulations!! Blackjack!!")
pot -= wager
player += wager
print ("The pot value is $", pot)
pr... | 2016/04/18 | [
"https://Stackoverflow.com/questions/36706131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4832091/"
] | You're only returning something if the condition in your function is met, otherwise the function returns `None` by default and it is then trying to unpack `None` into two values (your variables) | Here is an [MCVE](https://stackoverflow.com/help/mcve) for this question:
```
>>> a, b = None
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
a, b = None
TypeError: 'NoneType' object is not iterable
```
At this point, the problem should be clear. If not, one could look up multiple as... |
59,952,898 | I am trying to install `python3-psycopg2` as a part of `postgresql` installation, but I get:
```
The following packages have unmet dependencies:
python3-psycopg2 : Depends: python3 (>= 3.7~) but 3.6.7-1~18.04 is to be installed
E: Unable to correct problems, you have held broken packages.
```
I installed `python3.8... | 2020/01/28 | [
"https://Stackoverflow.com/questions/59952898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1626977/"
] | The `Psycopg2` library is built as a wrapper around `libpq` and mostly
written in C. It is distributed as a `sdist` and is built during
installation. For this reason it requires some `PostgreSQL` binaries and
headers to be present during installation.
Consider running these 2 commands:
```
sudo apt install python3-de... | While the explanation of Gitau is very good. You can simply install the psycopg2 binary instead as mentioned by Maurice:
`python3 -m pip install psycopg2-binary`
or just
`pip install psycopg2-binary` |
59,952,898 | I am trying to install `python3-psycopg2` as a part of `postgresql` installation, but I get:
```
The following packages have unmet dependencies:
python3-psycopg2 : Depends: python3 (>= 3.7~) but 3.6.7-1~18.04 is to be installed
E: Unable to correct problems, you have held broken packages.
```
I installed `python3.8... | 2020/01/28 | [
"https://Stackoverflow.com/questions/59952898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1626977/"
] | The `Psycopg2` library is built as a wrapper around `libpq` and mostly
written in C. It is distributed as a `sdist` and is built during
installation. For this reason it requires some `PostgreSQL` binaries and
headers to be present during installation.
Consider running these 2 commands:
```
sudo apt install python3-de... | Sometime psycopg2-binary is not a solution because other packages require for psycopg2 on their dependencies.
As cited above, you need to install some libs on ubuntu before install psycopg2.
For me, I had to install build-essential as well.
```
sudo apt install python3-dev libpq-dev build-essential
```
and then
``... |
60,140,174 | I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment.
requirements.txt given below,
```
aniso8601==6.0.0
Click==7.0
Flask==1.0.3
Flask-Cors==3.0.7
Flask-RESTful==0.3.7
Flask-SQLAlchemy==2.4.0
itsdangerous==1.1.0
Jinja2==2... | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727390/"
] | The bug was fixed in [werkzeug 0.15.5](https://werkzeug.palletsprojects.com/en/1.0.x/changes/#version-0-15-5). Upgrade from 0.15.4 to to a later version. | I had the error in django shell, it seems there is a bug in ipython. finally, I decided to remove ipython temporary until bug fix
```
pip uninstall ipython
```
[more info](https://bugs.python.org/issue35894) |
60,140,174 | I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment.
requirements.txt given below,
```
aniso8601==6.0.0
Click==7.0
Flask==1.0.3
Flask-Cors==3.0.7
Flask-RESTful==0.3.7
Flask-SQLAlchemy==2.4.0
itsdangerous==1.1.0
Jinja2==2... | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727390/"
] | The bug was fixed in [werkzeug 0.15.5](https://werkzeug.palletsprojects.com/en/1.0.x/changes/#version-0-15-5). Upgrade from 0.15.4 to to a later version. | I solved the error by simply executing the following line of code on the terminal:
```
sudo pip3 install --upgrade ipython
``` |
60,140,174 | I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment.
requirements.txt given below,
```
aniso8601==6.0.0
Click==7.0
Flask==1.0.3
Flask-Cors==3.0.7
Flask-RESTful==0.3.7
Flask-SQLAlchemy==2.4.0
itsdangerous==1.1.0
Jinja2==2... | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727390/"
] | The bug was fixed in [werkzeug 0.15.5](https://werkzeug.palletsprojects.com/en/1.0.x/changes/#version-0-15-5). Upgrade from 0.15.4 to to a later version. | [werkzeug](https://github.com/pallets/werkzeug) library can have issues with different python versions.
First of all, upgrade the werkzeug library to be the latest, then try again.
```
pip3 install --upgrade werkzeug
```
If that didn't work, I presume you may be using python version which kind of creates the whol... |
60,140,174 | I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment.
requirements.txt given below,
```
aniso8601==6.0.0
Click==7.0
Flask==1.0.3
Flask-Cors==3.0.7
Flask-RESTful==0.3.7
Flask-SQLAlchemy==2.4.0
itsdangerous==1.1.0
Jinja2==2... | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727390/"
] | The bug was fixed in [werkzeug 0.15.5](https://werkzeug.palletsprojects.com/en/1.0.x/changes/#version-0-15-5). Upgrade from 0.15.4 to to a later version. | try
```
pip uninstall Flask
```
then
```
pip install Flask
```
and
`pip uninstall Werkzeug`
then
`pip install Werkzeug` |
60,140,174 | I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment.
requirements.txt given below,
```
aniso8601==6.0.0
Click==7.0
Flask==1.0.3
Flask-Cors==3.0.7
Flask-RESTful==0.3.7
Flask-SQLAlchemy==2.4.0
itsdangerous==1.1.0
Jinja2==2... | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727390/"
] | I solved the error by simply executing the following line of code on the terminal:
```
sudo pip3 install --upgrade ipython
``` | I had the error in django shell, it seems there is a bug in ipython. finally, I decided to remove ipython temporary until bug fix
```
pip uninstall ipython
```
[more info](https://bugs.python.org/issue35894) |
60,140,174 | I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment.
requirements.txt given below,
```
aniso8601==6.0.0
Click==7.0
Flask==1.0.3
Flask-Cors==3.0.7
Flask-RESTful==0.3.7
Flask-SQLAlchemy==2.4.0
itsdangerous==1.1.0
Jinja2==2... | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727390/"
] | [werkzeug](https://github.com/pallets/werkzeug) library can have issues with different python versions.
First of all, upgrade the werkzeug library to be the latest, then try again.
```
pip3 install --upgrade werkzeug
```
If that didn't work, I presume you may be using python version which kind of creates the whol... | I had the error in django shell, it seems there is a bug in ipython. finally, I decided to remove ipython temporary until bug fix
```
pip uninstall ipython
```
[more info](https://bugs.python.org/issue35894) |
60,140,174 | I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment.
requirements.txt given below,
```
aniso8601==6.0.0
Click==7.0
Flask==1.0.3
Flask-Cors==3.0.7
Flask-RESTful==0.3.7
Flask-SQLAlchemy==2.4.0
itsdangerous==1.1.0
Jinja2==2... | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727390/"
] | try
```
pip uninstall Flask
```
then
```
pip install Flask
```
and
`pip uninstall Werkzeug`
then
`pip install Werkzeug` | I had the error in django shell, it seems there is a bug in ipython. finally, I decided to remove ipython temporary until bug fix
```
pip uninstall ipython
```
[more info](https://bugs.python.org/issue35894) |
60,140,174 | I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment.
requirements.txt given below,
```
aniso8601==6.0.0
Click==7.0
Flask==1.0.3
Flask-Cors==3.0.7
Flask-RESTful==0.3.7
Flask-SQLAlchemy==2.4.0
itsdangerous==1.1.0
Jinja2==2... | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727390/"
] | I solved the error by simply executing the following line of code on the terminal:
```
sudo pip3 install --upgrade ipython
``` | [werkzeug](https://github.com/pallets/werkzeug) library can have issues with different python versions.
First of all, upgrade the werkzeug library to be the latest, then try again.
```
pip3 install --upgrade werkzeug
```
If that didn't work, I presume you may be using python version which kind of creates the whol... |
60,140,174 | I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment.
requirements.txt given below,
```
aniso8601==6.0.0
Click==7.0
Flask==1.0.3
Flask-Cors==3.0.7
Flask-RESTful==0.3.7
Flask-SQLAlchemy==2.4.0
itsdangerous==1.1.0
Jinja2==2... | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727390/"
] | I solved the error by simply executing the following line of code on the terminal:
```
sudo pip3 install --upgrade ipython
``` | try
```
pip uninstall Flask
```
then
```
pip install Flask
```
and
`pip uninstall Werkzeug`
then
`pip install Werkzeug` |
60,140,174 | I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment.
requirements.txt given below,
```
aniso8601==6.0.0
Click==7.0
Flask==1.0.3
Flask-Cors==3.0.7
Flask-RESTful==0.3.7
Flask-SQLAlchemy==2.4.0
itsdangerous==1.1.0
Jinja2==2... | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727390/"
] | [werkzeug](https://github.com/pallets/werkzeug) library can have issues with different python versions.
First of all, upgrade the werkzeug library to be the latest, then try again.
```
pip3 install --upgrade werkzeug
```
If that didn't work, I presume you may be using python version which kind of creates the whol... | try
```
pip uninstall Flask
```
then
```
pip install Flask
```
and
`pip uninstall Werkzeug`
then
`pip install Werkzeug` |
6,377,535 | I have trouble setting up funkload to work well with cookies. I turn on `fl-record` and perform a series of requests of which each is sending a cookie. If I use the command without supplying a folder path, the output is stored in TCPWatch-Proxy format and I can see the contents of all the cookies, so I know that they a... | 2011/06/16 | [
"https://Stackoverflow.com/questions/6377535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475763/"
] | I see this old post not answered, so I thought I could post:
In Python:
Identify the name of cookie you are sending. mine is 'csrftoken' in header and same one in post as 'csrfmiddlewaretoken'> intially I get the value of cookie then pass the same in post for authentication. Example:
```
res = self.get ( server_... | I've found a bug in Funkload. Funkload isn't handling correctly the cookies with a leading '.' in the domain. At the moment all that cookies are being silently ignored.
Check this branch: <https://github.com/sbook/FunkLoad>
I've already send a pull request: <https://github.com/nuxeo/FunkLoad/pull/32> |
913,396 | I'm using swig to wrap a class from a C++ library with python. It works overall, but there is an exception that is thrown from within the library and I can't seem to catch it in the swig interface, so it just crashes the python application!
The class PyMonitor.cc describes the swig interface to the desired class, Moni... | 2009/05/27 | [
"https://Stackoverflow.com/questions/913396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75827/"
] | You have to forward the exceptions to Python if you want to parse them there.
See the [SWIG Documentation](http://www.swig.org/Doc1.3/Customization.html#exception).
In order to forward exceptions, you only have to add some code in the SWIG interface (.i) file. Basically, this can be anywhere in the .i file.
All types ... | I'm not familiar with swig, or with using C++ and Python together, but if this is under a recent version of Microsoft Visual C++, then the `Monitor` class is probably throwing a C structured exception, rather than a C++ typed exception. C structured exceptions aren't caught by C++ exception handlers, even the `catch(..... |
913,396 | I'm using swig to wrap a class from a C++ library with python. It works overall, but there is an exception that is thrown from within the library and I can't seem to catch it in the swig interface, so it just crashes the python application!
The class PyMonitor.cc describes the swig interface to the desired class, Moni... | 2009/05/27 | [
"https://Stackoverflow.com/questions/913396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75827/"
] | You have to forward the exceptions to Python if you want to parse them there.
See the [SWIG Documentation](http://www.swig.org/Doc1.3/Customization.html#exception).
In order to forward exceptions, you only have to add some code in the SWIG interface (.i) file. Basically, this can be anywhere in the .i file.
All types ... | It's possible that a function called directly or indirectly by the Monitor `constructor` is violating its exception specification and doesn't allow `std::bad_exception` to be thrown. If you haven't replaced the standard function for trapping this, then it would explain the behaviour that you are seeing.
To test this h... |
3,856,314 | After using C# for long time I finally decided to switch to Python.
The question I am facing for the moment has to do about auto-complete.
I guess I am spoiled by C# and especially from resharper and I was expecting something similar to exist for Python.
My editor of choice is emacs and after doing some research I fou... | 2010/10/04 | [
"https://Stackoverflow.com/questions/3856314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404984/"
] | I found this post
>
> [My Emacs Python environment](http://www.saltycrane.com/blog/2010/05/my-emacs-python-environment/)
>
>
>
to be the most useful and comprehensive list of instructions and references on how to setup a decent Python development environment in Emacs regardless of OS platform. It is still a bit ... | I find that [PyDev](http://pydev.org/) + Eclipse can meet most of my needs. There is also [PyCharm](http://www.jetbrains.com/pycharm/) from the Intellij team. PyCharm has the added advantage of smooth integration with git. |
3,856,314 | After using C# for long time I finally decided to switch to Python.
The question I am facing for the moment has to do about auto-complete.
I guess I am spoiled by C# and especially from resharper and I was expecting something similar to exist for Python.
My editor of choice is emacs and after doing some research I fou... | 2010/10/04 | [
"https://Stackoverflow.com/questions/3856314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404984/"
] | I find that [PyDev](http://pydev.org/) + Eclipse can meet most of my needs. There is also [PyCharm](http://www.jetbrains.com/pycharm/) from the Intellij team. PyCharm has the added advantage of smooth integration with git. | IMO, by far the easiest way to take advantage of the python tools available for emacs is to take advantage of the defaults that are all set up at:
<https://github.com/gabrielelanaro/emacs-for-python>
I actually took the time to get pymacs and ropemacs and python-mode all working independently before finding that littl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.