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 |
|---|---|---|---|---|---|
56,066,816 | I have several data frames (with equal # columns but different names). I'm trying to create one data frame with rows stacked below each other. I don't care now about the column names (I can always rename them later). I saw different SO links but they don't address this problem completely.
Note I've 21 data frames and... | 2019/05/09 | [
"https://Stackoverflow.com/questions/56066816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9473446/"
] | I will do it at the beginning adding `skiprows=1`
```
names=[0,1,2,3,4]# what every you want to call them ..
pd.concat([pd.read_csv(f, usecols = [0,1,2,3,4],skiprows=1,names=[0,1,2,3,4]) for f in files])
``` | Once you put all the data frames into a list, try this code.
```
import pandas as pd
df = [df1, df2, df3]
result = pd.DataFrame(columns=df1.columns)
for df in df:
result = pd.concat([result,df.rename(columns=df1.columns)], ignore_index=True)
``` |
6,774,561 | I have a python code treating a lot of apache logs (decompress, parse, crunching numbers, regexping etc). One parent process which takes a list of files (up to few millions), and sends a list of files to parse to workers, using multiprocess pool.
I wonder, if there is any guidelines / benchmarks / advices which can h... | 2011/07/21 | [
"https://Stackoverflow.com/questions/6774561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/129289/"
] | >
> I wonder, if there is any guidelines / benchmarks / advices which can help me to estimate ideal number of child process ?
>
>
>
No.
>
> having one process per core is better than launching few hundreds of them?
>
>
>
You can never know *in advance*.
There are too many degrees of freedom.
You can only... | I'll address the last question first. In CPython, it is next to impossible to make sizeable performance gains by distributing CPU-bound load across threads. This is due to the [Global Interpreter Lock](http://en.wikipedia.org/wiki/Global_Interpreter_Lock). In that respect [`multiprocessing`](http://docs.python.org/libr... |
6,774,561 | I have a python code treating a lot of apache logs (decompress, parse, crunching numbers, regexping etc). One parent process which takes a list of files (up to few millions), and sends a list of files to parse to workers, using multiprocess pool.
I wonder, if there is any guidelines / benchmarks / advices which can h... | 2011/07/21 | [
"https://Stackoverflow.com/questions/6774561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/129289/"
] | Multiple cores do not provide better performance if the program is I/O bound. The performance might even become worse if the disk is serving two or more masters. | I'll address the last question first. In CPython, it is next to impossible to make sizeable performance gains by distributing CPU-bound load across threads. This is due to the [Global Interpreter Lock](http://en.wikipedia.org/wiki/Global_Interpreter_Lock). In that respect [`multiprocessing`](http://docs.python.org/libr... |
6,774,561 | I have a python code treating a lot of apache logs (decompress, parse, crunching numbers, regexping etc). One parent process which takes a list of files (up to few millions), and sends a list of files to parse to workers, using multiprocess pool.
I wonder, if there is any guidelines / benchmarks / advices which can h... | 2011/07/21 | [
"https://Stackoverflow.com/questions/6774561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/129289/"
] | >
> I wonder, if there is any guidelines / benchmarks / advices which can help me to estimate ideal number of child process ?
>
>
>
No.
>
> having one process per core is better than launching few hundreds of them?
>
>
>
You can never know *in advance*.
There are too many degrees of freedom.
You can only... | I'm not sure if current OSes do this, but it used to be that I/O buffers were allocated per-process, so dividing one process' buffer among multiple threads would lead to buffer thrashing. You're far better off using multiple processes for I/O-heavy tasks. |
6,774,561 | I have a python code treating a lot of apache logs (decompress, parse, crunching numbers, regexping etc). One parent process which takes a list of files (up to few millions), and sends a list of files to parse to workers, using multiprocess pool.
I wonder, if there is any guidelines / benchmarks / advices which can h... | 2011/07/21 | [
"https://Stackoverflow.com/questions/6774561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/129289/"
] | Multiple cores do not provide better performance if the program is I/O bound. The performance might even become worse if the disk is serving two or more masters. | I'm not sure if current OSes do this, but it used to be that I/O buffers were allocated per-process, so dividing one process' buffer among multiple threads would lead to buffer thrashing. You're far better off using multiple processes for I/O-heavy tasks. |
28,191,221 | I used SQL to convert a social security number to MD5 hash. I am wondering if there is a module or function in python/pandas that can do the same thing.
My sql script is:
```
CREATE OR REPLACE FUNCTION MD5HASH(STR IN VARCHAR2) RETURN VARCHAR2 IS
V_CHECKSUM VARCHAR2(32);
BEGIN
V_CHECKSUM := LOWER(RAWTOHEX(UTL_RAW... | 2015/01/28 | [
"https://Stackoverflow.com/questions/28191221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2201603/"
] | Using the standard hashlib module:
```
import hashlib
hash = hashlib.md5()
hash.update('555555555')
print hash.hexdigest()
```
**output**
```
3665a76e271ada5a75368b99f774e404
```
As mentioned in timkofu's comment, you can also do this more simply, using
```
print hashlib.md5('555555555').hexdigest()
```
The ... | hashlib with `md5` might be of your interest.
```
import hashlib
hashlib.md5("Nobody inspects the spammish repetition").hexdigest()
```
output:
```
bb649c83dd1ea5c9d9dec9a18df0ffe9
```
Constructors for hash algorithms that are always present in this module are `md5(), sha1(), sha224(), sha256(), sha384(), and sh... |
39,361,496 | I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet.
Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wo... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39361496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2439540/"
] | The class is really not instantiating itself twice. Rather, the default constructor `ApplicationCreator()` (i.e. the one which takes no parameters), is simply calling the constructor which accepts an input string.
This ensures that an `ApplicationCreator` object will always have a type. When a type is not specified th... | Here this class has two constructor.
When class name "method" name are same you can understand those are constructor.
Here constructor is over loaded . Based on parameter classes will be instantiated. Here user have a choice based on need . |
39,361,496 | I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet.
Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wo... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39361496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2439540/"
] | 1) Why would the class instantiate itself inside the class?
>
> The class is not calling itself, it is proving a way for others to instantiate its object. Read about [constructor](https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html).
>
>
>
2) Why would it do so twice? Or is this a way to set cer... | It's not instantiating itself in the class, it's calling a different constructor in the class.
What these are are overloaded constructors. Constructors are somewhat method-like, but they are called on object creation. Consider this:
```
public class Example {
private int instanceVariable;
public Example() { ... |
39,361,496 | I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet.
Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wo... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39361496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2439540/"
] | These are two different constructors.
They have what is refered to as "different signatures.
Using it you can construct a `ApplicationCreator` object in two different ways :
```
ApplicationCreator ac = new ApplicationCreator();
```
Or
```
ApplicationCreator ac = new ApplicationCreator("A String");
```
For ... | The class is really not instantiating itself twice. Rather, the default constructor `ApplicationCreator()` (i.e. the one which takes no parameters), is simply calling the constructor which accepts an input string.
This ensures that an `ApplicationCreator` object will always have a type. When a type is not specified th... |
39,361,496 | I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet.
Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wo... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39361496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2439540/"
] | It's not instantiating itself in the class, it's calling a different constructor in the class.
What these are are overloaded constructors. Constructors are somewhat method-like, but they are called on object creation. Consider this:
```
public class Example {
private int instanceVariable;
public Example() { ... | The class is really not instantiating itself twice. Rather, the default constructor `ApplicationCreator()` (i.e. the one which takes no parameters), is simply calling the constructor which accepts an input string.
This ensures that an `ApplicationCreator` object will always have a type. When a type is not specified th... |
39,361,496 | I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet.
Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wo... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39361496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2439540/"
] | 1) Why would the class instantiate itself inside the class?
>
> The class is not calling itself, it is proving a way for others to instantiate its object. Read about [constructor](https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html).
>
>
>
2) Why would it do so twice? Or is this a way to set cer... | Here this class has two constructor.
When class name "method" name are same you can understand those are constructor.
Here constructor is over loaded . Based on parameter classes will be instantiated. Here user have a choice based on need . |
39,361,496 | I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet.
Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wo... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39361496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2439540/"
] | These are two different constructors.
They have what is refered to as "different signatures.
Using it you can construct a `ApplicationCreator` object in two different ways :
```
ApplicationCreator ac = new ApplicationCreator();
```
Or
```
ApplicationCreator ac = new ApplicationCreator("A String");
```
For ... | It's called a constructor. And it's not "called twice", one simply redirects to the other via `this()` with the given parameters.
Essentially the first way, without parameters, simply has a default value. Otherwise, you construct an instance with the given `String type` |
39,361,496 | I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet.
Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wo... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39361496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2439540/"
] | 1) Why would the class instantiate itself inside the class?
>
> The class is not calling itself, it is proving a way for others to instantiate its object. Read about [constructor](https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html).
>
>
>
2) Why would it do so twice? Or is this a way to set cer... | The class is really not instantiating itself twice. Rather, the default constructor `ApplicationCreator()` (i.e. the one which takes no parameters), is simply calling the constructor which accepts an input string.
This ensures that an `ApplicationCreator` object will always have a type. When a type is not specified th... |
39,361,496 | I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet.
Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wo... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39361496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2439540/"
] | 1) Why would the class instantiate itself inside the class?
>
> The class is not calling itself, it is proving a way for others to instantiate its object. Read about [constructor](https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html).
>
>
>
2) Why would it do so twice? Or is this a way to set cer... | These are two different constructors.
They have what is refered to as "different signatures.
Using it you can construct a `ApplicationCreator` object in two different ways :
```
ApplicationCreator ac = new ApplicationCreator();
```
Or
```
ApplicationCreator ac = new ApplicationCreator("A String");
```
For ... |
39,361,496 | I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet.
Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wo... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39361496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2439540/"
] | 1) Why would the class instantiate itself inside the class?
>
> The class is not calling itself, it is proving a way for others to instantiate its object. Read about [constructor](https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html).
>
>
>
2) Why would it do so twice? Or is this a way to set cer... | It's called a constructor. And it's not "called twice", one simply redirects to the other via `this()` with the given parameters.
Essentially the first way, without parameters, simply has a default value. Otherwise, you construct an instance with the given `String type` |
39,361,496 | I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet.
Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wo... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39361496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2439540/"
] | The class is really not instantiating itself twice. Rather, the default constructor `ApplicationCreator()` (i.e. the one which takes no parameters), is simply calling the constructor which accepts an input string.
This ensures that an `ApplicationCreator` object will always have a type. When a type is not specified th... | It's called a constructor. And it's not "called twice", one simply redirects to the other via `this()` with the given parameters.
Essentially the first way, without parameters, simply has a default value. Otherwise, you construct an instance with the given `String type` |
4,088,471 | I have a dictionary in the view layer, that I am passing to my templates. The dictionary values are (mostly) lists, although a few scalars also reside in the dictionary. The lists if present are initialized to None.
The None values are being printed as 'None' in the template, so I wrote this little function to clean o... | 2010/11/03 | [
"https://Stackoverflow.com/questions/4088471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461722/"
] | Have you looked at `defaultdict` within collections? You'd have a dictionary formed via
```
defaultdict(list)
```
which initializes an empty list when a key is queried and that key does not exist. | ```
filtered_dict = dict((k, v) for k, v in table.items() if v is not None)
```
or in Python 2.7+, use the dictionary comprehension syntax:
```
filtered_dict = {k: v for k, v in table.items() if v is not None}
``` |
45,125,441 | I have a dataframe that has a column of boroughs visited (among many other columns):
```
Index User Boroughs_visited
0 Eminem Manhattan, Bronx
1 BrSpears NaN
2 Elvis Brooklyn
3 Adele Queens, Brooklyn
```
**I want to create a third column that shows which User visited Brooklyn**, so I... | 2017/07/16 | [
"https://Stackoverflow.com/questions/45125441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8005777/"
] | Let use `.str` accessor with `contains` and `fillna`:
```
df['Brooklyn'] = (df.Boroughs_visited.str.contains('Brooklyn') * 1).fillna(0)
```
Or another format of the same statement:
```
df['Brooklyn'] = df.Boroughs_visited.str.contains('Brooklyn').mul(1, fill_value=0)
```
Output:
```
Index User Borou... | You can get all Boroughs for the price of one
```
df.join(df.Boroughs_visited.str.get_dummies(sep=', '))
Index User Boroughs_visited Bronx Brooklyn Manhattan Queens
0 0 Eminem Manhattan, Bronx 1 0 1 0
1 1 BrSpears NaN 0 0 0 ... |
13,409,559 | I'm trying to replace all single quotes with double quotes, but leave behind all escaped single quotes. Does anyone know a simple way to do this with python regexs?
```
Input:
"{ 'name': 'Skrillex', 'Genre':'Dubstep', 'Bass': 'Heavy', 'thoughts': 'this\'s ahmazing'}"
output:
"{ "name": "Skrillex", "Genre": "Dubstep"... | 2012/11/16 | [
"https://Stackoverflow.com/questions/13409559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1432960/"
] | This is kind of...odd, but it may work. Remember to preface your string with `r` to denote a raw string so that we can remove the backslashes:
```
In [19]: s = r"{ 'name': 'Skrillex', 'Genre':'Dubstep', 'Bass': 'Heavy', 'thoughts': 'this\'s ahmazing'}"
In [20]: s.replace("\\'", 'REPLACEMEOHYEAH').replace("'", '"').rep... | 1. replace all the \' into a magic word
2. replace all the ' into "
3. replace all the magic words back to \' |
68,570,102 | Basically, I'm trying to build a code to get the largest number from the user's inputs. This is my 1st time using a for loop and I'm pretty new to python. This is my code:
```
session_live = True
numbers = []
a = 0
def largest_num(arr, n):
#Create a variable to hold the max number
max = arr[0]
#Using for... | 2021/07/29 | [
"https://Stackoverflow.com/questions/68570102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16420917/"
] | The error in your `largest_num` function is that it returns in the first iteration -- hence it will only return the larger of the first two numbers.
Using the builtin `max()` function makes life quite a bit easier; any time you reimplement a function that already exists, you're creating work for yourself and (as you'v... | I made it without using the built-in function 'max'.
It is a way to update the 'maxNum' variable with the largest number by comparing through the for statement.
```py
numbers = []
while True:
print("Tell us a number")
numbers.append(int(input()))
print("Continue? (Y/N)")
confirm = input()
i... |
68,570,102 | Basically, I'm trying to build a code to get the largest number from the user's inputs. This is my 1st time using a for loop and I'm pretty new to python. This is my code:
```
session_live = True
numbers = []
a = 0
def largest_num(arr, n):
#Create a variable to hold the max number
max = arr[0]
#Using for... | 2021/07/29 | [
"https://Stackoverflow.com/questions/68570102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16420917/"
] | So, first things first,
* the use of `max` can be avoided, as it is a reserved keyword in python
And coming to your fix, you are comparing it with the value only once in the loop, and you are returning the number, the indentation is the key here. You will have to wait for the loop to complete its job then return the ... | I made it without using the built-in function 'max'.
It is a way to update the 'maxNum' variable with the largest number by comparing through the for statement.
```py
numbers = []
while True:
print("Tell us a number")
numbers.append(int(input()))
print("Continue? (Y/N)")
confirm = input()
i... |
5,633,067 | I have a pylons project where I need to update some in-memory structures periodically. This should be done on-demand. I decided to come up with a signal handler for this. User sends `SIGUSR1` to the main pylons thread and it is handled by the project.
This works except after handling the signal, the server crashes wi... | 2011/04/12 | [
"https://Stackoverflow.com/questions/5633067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/408426/"
] | Yes, it is possible, but not easy using the stock Python libraries. This is due to Python translating all OS errors to exceptions. However, EINTR should really cause a retry of the system call used. Whenever you start using signals in Python you will see this error sporadically.
I have [code that fixes this](http://co... | A fix, at least works for me, from an [12 year old python-dev list post](http://mail.python.org/pipermail/python-dev/2000-October/009671.html)
```
while True:
try:
readable, writable, exceptional = select.select(inputs, outputs, inputs, timeout)
except select.error, v:
if v[... |
57,507,832 | I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.
I am trying to allocate memory for a numpy array with shape `(156816, 36, 53806)`
with
```
np.zeros((156816, 36, 53806), dtype='uint8')
```
and while I'm getting an error on Ubuntu OS
```
>>> import num... | 2019/08/15 | [
"https://Stackoverflow.com/questions/57507832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123537/"
] | I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the [pagefile](https://whatis.techtarget.com/definition/pagefile) size, as it was a Memory overcommitment problem for me too.
Windows 8
1. On the Keyboard Press the... | change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8:
```
data['label'] = data['label'].astype(np.uint8)
``` |
57,507,832 | I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.
I am trying to allocate memory for a numpy array with shape `(156816, 36, 53806)`
with
```
np.zeros((156816, 36, 53806), dtype='uint8')
```
and while I'm getting an error on Ubuntu OS
```
>>> import num... | 2019/08/15 | [
"https://Stackoverflow.com/questions/57507832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123537/"
] | In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).
from
```
mask = np.zeros(edges.shape)
```
to
```
mask = np.zeros(edges.shape,dtype='uint8')
``` | I faced the same issue running pandas in a docker contain on EC2. I tried the above solution of allowing overcommit memory allocation via `sysctl -w vm.overcommit_memory=1` (more info on this [here](https://www.kernel.org/doc/Documentation/vm/overcommit-accounting)), however this still didn't solve the issue.
Rather t... |
57,507,832 | I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.
I am trying to allocate memory for a numpy array with shape `(156816, 36, 53806)`
with
```
np.zeros((156816, 36, 53806), dtype='uint8')
```
and while I'm getting an error on Ubuntu OS
```
>>> import num... | 2019/08/15 | [
"https://Stackoverflow.com/questions/57507832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123537/"
] | This is likely due to your system's [overcommit handling](https://www.kernel.org/doc/Documentation/vm/overcommit-accounting) mode.
In the default mode, `0`,
>
> Heuristic overcommit handling. Obvious overcommits of address space are refused. Used for a typical system. It ensures a seriously wild allocation fails whi... | I faced the same issue running pandas in a docker contain on EC2. I tried the above solution of allowing overcommit memory allocation via `sysctl -w vm.overcommit_memory=1` (more info on this [here](https://www.kernel.org/doc/Documentation/vm/overcommit-accounting)), however this still didn't solve the issue.
Rather t... |
57,507,832 | I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.
I am trying to allocate memory for a numpy array with shape `(156816, 36, 53806)`
with
```
np.zeros((156816, 36, 53806), dtype='uint8')
```
and while I'm getting an error on Ubuntu OS
```
>>> import num... | 2019/08/15 | [
"https://Stackoverflow.com/questions/57507832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123537/"
] | In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).
from
```
mask = np.zeros(edges.shape)
```
to
```
mask = np.zeros(edges.shape,dtype='uint8')
``` | I was having this issue with numpy by trying to have **image sizes of 600x600 (360K)**, I decided to **reduce to 224x224 (~50k)**, a reduction in memory usage by a factor of 7.
`X_set = np.array(X_set).reshape(-1 , 600 * 600 * 3)`
is now
`X_set = np.array(X_set).reshape(-1 , 224 * 224 * 3)`
hope this helps |
57,507,832 | I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.
I am trying to allocate memory for a numpy array with shape `(156816, 36, 53806)`
with
```
np.zeros((156816, 36, 53806), dtype='uint8')
```
and while I'm getting an error on Ubuntu OS
```
>>> import num... | 2019/08/15 | [
"https://Stackoverflow.com/questions/57507832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123537/"
] | I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the [pagefile](https://whatis.techtarget.com/definition/pagefile) size, as it was a Memory overcommitment problem for me too.
Windows 8
1. On the Keyboard Press the... | Sometimes, this error pops up because of the kernel has reached its limit. Try to restart the kernel redo the necessary steps. |
57,507,832 | I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.
I am trying to allocate memory for a numpy array with shape `(156816, 36, 53806)`
with
```
np.zeros((156816, 36, 53806), dtype='uint8')
```
and while I'm getting an error on Ubuntu OS
```
>>> import num... | 2019/08/15 | [
"https://Stackoverflow.com/questions/57507832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123537/"
] | I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the [pagefile](https://whatis.techtarget.com/definition/pagefile) size, as it was a Memory overcommitment problem for me too.
Windows 8
1. On the Keyboard Press the... | I came across this problem on Windows too. The solution for me was to **switch from a 32-bit to a 64-bit version of Python**. Indeed, a 32-bit software, like a 32-bit CPU, can adress a [maximum of 4 GB](https://techterms.com/help/difference_between_32-bit_and_64-bit_systems) of RAM (2^32). So if you have more than 4 GB... |
57,507,832 | I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.
I am trying to allocate memory for a numpy array with shape `(156816, 36, 53806)`
with
```
np.zeros((156816, 36, 53806), dtype='uint8')
```
and while I'm getting an error on Ubuntu OS
```
>>> import num... | 2019/08/15 | [
"https://Stackoverflow.com/questions/57507832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123537/"
] | Sometimes, this error pops up because of the kernel has reached its limit. Try to restart the kernel redo the necessary steps. | I faced the same issue running pandas in a docker contain on EC2. I tried the above solution of allowing overcommit memory allocation via `sysctl -w vm.overcommit_memory=1` (more info on this [here](https://www.kernel.org/doc/Documentation/vm/overcommit-accounting)), however this still didn't solve the issue.
Rather t... |
57,507,832 | I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.
I am trying to allocate memory for a numpy array with shape `(156816, 36, 53806)`
with
```
np.zeros((156816, 36, 53806), dtype='uint8')
```
and while I'm getting an error on Ubuntu OS
```
>>> import num... | 2019/08/15 | [
"https://Stackoverflow.com/questions/57507832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123537/"
] | I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the [pagefile](https://whatis.techtarget.com/definition/pagefile) size, as it was a Memory overcommitment problem for me too.
Windows 8
1. On the Keyboard Press the... | In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).
from
```
mask = np.zeros(edges.shape)
```
to
```
mask = np.zeros(edges.shape,dtype='uint8')
``` |
57,507,832 | I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.
I am trying to allocate memory for a numpy array with shape `(156816, 36, 53806)`
with
```
np.zeros((156816, 36, 53806), dtype='uint8')
```
and while I'm getting an error on Ubuntu OS
```
>>> import num... | 2019/08/15 | [
"https://Stackoverflow.com/questions/57507832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123537/"
] | I came across this problem on Windows too. The solution for me was to **switch from a 32-bit to a 64-bit version of Python**. Indeed, a 32-bit software, like a 32-bit CPU, can adress a [maximum of 4 GB](https://techterms.com/help/difference_between_32-bit_and_64-bit_systems) of RAM (2^32). So if you have more than 4 GB... | change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8:
```
data['label'] = data['label'].astype(np.uint8)
``` |
57,507,832 | I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.
I am trying to allocate memory for a numpy array with shape `(156816, 36, 53806)`
with
```
np.zeros((156816, 36, 53806), dtype='uint8')
```
and while I'm getting an error on Ubuntu OS
```
>>> import num... | 2019/08/15 | [
"https://Stackoverflow.com/questions/57507832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123537/"
] | I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the [pagefile](https://whatis.techtarget.com/definition/pagefile) size, as it was a Memory overcommitment problem for me too.
Windows 8
1. On the Keyboard Press the... | I faced the same issue running pandas in a docker contain on EC2. I tried the above solution of allowing overcommit memory allocation via `sysctl -w vm.overcommit_memory=1` (more info on this [here](https://www.kernel.org/doc/Documentation/vm/overcommit-accounting)), however this still didn't solve the issue.
Rather t... |
10,643,982 | Is there a way in python to truncate the decimal part at 5 or 7 digits?
If not, how can i avoid a float like e\*\*(-x) number to get too big in size?
Thanks | 2012/05/17 | [
"https://Stackoverflow.com/questions/10643982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1308318/"
] | Either catch the `OverflowError` or use the `decimal` module. Python is not going to assume you were okay with the overflow.
```
>>> 0.0000000000000000000000000000000000000000000000000000000000000001**-30
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')
>... | The "Result too large" doesn't refer to the number of characters in the decimal representation of the number, it means that the number that resulted from your exponential function is large enough to overflow whatever type python uses internally to store floating point values.
You need to either use a different type to... |
10,643,982 | Is there a way in python to truncate the decimal part at 5 or 7 digits?
If not, how can i avoid a float like e\*\*(-x) number to get too big in size?
Thanks | 2012/05/17 | [
"https://Stackoverflow.com/questions/10643982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1308318/"
] | Either catch the `OverflowError` or use the `decimal` module. Python is not going to assume you were okay with the overflow.
```
>>> 0.0000000000000000000000000000000000000000000000000000000000000001**-30
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')
>... | this seems to work
```
from decimal import *
getcontext().prec = 7
math.exp(- Decimal(x))
``` |
10,643,982 | Is there a way in python to truncate the decimal part at 5 or 7 digits?
If not, how can i avoid a float like e\*\*(-x) number to get too big in size?
Thanks | 2012/05/17 | [
"https://Stackoverflow.com/questions/10643982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1308318/"
] | The "Result too large" doesn't refer to the number of characters in the decimal representation of the number, it means that the number that resulted from your exponential function is large enough to overflow whatever type python uses internally to store floating point values.
You need to either use a different type to... | this seems to work
```
from decimal import *
getcontext().prec = 7
math.exp(- Decimal(x))
``` |
56,814,981 | the following code gives me the python error 'failed to parse' addon.xml:
(I've used an online checker and it says "error on line 33 at column 15: Opening and ending tag mismatch: description line 0 and extension" - which is the very end of the /extension end tag at the end of the document).
Any advice would be appre... | 2019/06/29 | [
"https://Stackoverflow.com/questions/56814981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11611598/"
] | Your "XML" file is not well-formed, so it cannot be parsed. Find out how it was created, correct the process so the problem does not occur again, and then regenerate the file.
Files that are vaguely XML-like but not well-formed are pretty well useless. Repair is sometimes possible if the errors are very systematic, bu... | Most of the time a "failed to parse" error msg is due to the XML File itself.
Check you're XML File for the correct formatting.
I once forgot the root tag and had the same error message. |
55,197,425 | Ok so here is what I am trying to archieve:
1. Call a URL with a list of dynamically filtered search results
2. Click on the first search result (5/page)
3. Scrape the headlines, paragraphs and images and store them as a json object in a a seperate file e.g.
{
"Title": "Headline element of the individual entry", ... | 2019/03/16 | [
"https://Stackoverflow.com/questions/55197425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4536968/"
] | You can use only `requests` and `BeautifulSoup` to scrape, without Selenium. It will be much faster and will consume much less resources:
```
import json
import requests
from bs4 import BeautifulSoup
# Get 1000 results
params = {"$filter": "TemplateName eq 'Application Article'", "$orderby": "ArticleDate desc", "$top... | You aren’t using your link variable anywhere in your loop, just telling the driver to find the top link and click it. (When you use the singular find\_element selector and there are multiple results selenium just grabs the first one). I think all you need to do is replace these lines
```
searchResult = driver.find_e... |
55,197,425 | Ok so here is what I am trying to archieve:
1. Call a URL with a list of dynamically filtered search results
2. Click on the first search result (5/page)
3. Scrape the headlines, paragraphs and images and store them as a json object in a a seperate file e.g.
{
"Title": "Headline element of the individual entry", ... | 2019/03/16 | [
"https://Stackoverflow.com/questions/55197425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4536968/"
] | You can use only `requests` and `BeautifulSoup` to scrape, without Selenium. It will be much faster and will consume much less resources:
```
import json
import requests
from bs4 import BeautifulSoup
# Get 1000 results
params = {"$filter": "TemplateName eq 'Application Article'", "$orderby": "ArticleDate desc", "$top... | I have one solutions for you.fetch `href` value of the link and then do `driver.get(url)`
Instead of this.
```
for link in soup_results_overview.findAll("a", class_="searchResults__detail"):
#Selenium visits each Search Result Page
searchResult = driver.find_element_by_class_name('searchResults__detail')
sear... |
55,197,425 | Ok so here is what I am trying to archieve:
1. Call a URL with a list of dynamically filtered search results
2. Click on the first search result (5/page)
3. Scrape the headlines, paragraphs and images and store them as a json object in a a seperate file e.g.
{
"Title": "Headline element of the individual entry", ... | 2019/03/16 | [
"https://Stackoverflow.com/questions/55197425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4536968/"
] | You can use only `requests` and `BeautifulSoup` to scrape, without Selenium. It will be much faster and will consume much less resources:
```
import json
import requests
from bs4 import BeautifulSoup
# Get 1000 results
params = {"$filter": "TemplateName eq 'Application Article'", "$orderby": "ArticleDate desc", "$top... | This solution navigates to each link, scrapes the title and paragraphs, stores the image urls, and downloads all the images to the machine as `.png`s:
```
from bs4 import BeautifulSoup as soup
import requests, re
from selenium import webdriver
def scrape_page(_d, _link):
_head, _paras = _d.find('h1', {'class':'head... |
55,197,425 | Ok so here is what I am trying to archieve:
1. Call a URL with a list of dynamically filtered search results
2. Click on the first search result (5/page)
3. Scrape the headlines, paragraphs and images and store them as a json object in a a seperate file e.g.
{
"Title": "Headline element of the individual entry", ... | 2019/03/16 | [
"https://Stackoverflow.com/questions/55197425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4536968/"
] | You can use only `requests` and `BeautifulSoup` to scrape, without Selenium. It will be much faster and will consume much less resources:
```
import json
import requests
from bs4 import BeautifulSoup
# Get 1000 results
params = {"$filter": "TemplateName eq 'Application Article'", "$orderby": "ArticleDate desc", "$top... | The following set the results count to 20 and calculate the number of results pages. It clicks next until all pages visited. Condition is added to ensure page has loaded. I print the articles just to show you different pages. You can use this structure to create your desired output.
```
from selenium import webdriver
... |
34,771,191 | I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message:
```
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is ... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34771191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497180/"
] | This worked for me on Ubuntu **16.04 LST** with **Python 3.5.2 | Anaconda 4.2.0 (64-bit)**. I deleted all of the files in `~/.cache/matplotlib/`.
```
sudo rm -r fontList.py3k.cache tex.cache
```
At first I thought it wouldn't work, because I got the warning afterward. But after the cache files were rebuilt the warn... | This worked for me:
```
sudo apt-get install libfreetype6-dev libxft-dev
``` |
34,771,191 | I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message:
```
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is ... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34771191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497180/"
] | I ran the python code w. sudo and it cured it...my guess was that there wasn't permission to write that table... good luck! | This worked for me on Ubuntu **16.04 LST** with **Python 3.5.2 | Anaconda 4.2.0 (64-bit)**. I deleted all of the files in `~/.cache/matplotlib/`.
```
sudo rm -r fontList.py3k.cache tex.cache
```
At first I thought it wouldn't work, because I got the warning afterward. But after the cache files were rebuilt the warn... |
34,771,191 | I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message:
```
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is ... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34771191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497180/"
] | As tom suggested in the comment above, deleting the files:
```
fontList.cache
fontList.py3k.cache
tex.cache
```
solve the problem.
In my case the files were under:
```
`~/.matplotlib`
```
EDITED
A couple of days ago the message appeared again, I deleted the files in the locations mention above without any su... | I ran the python code w. sudo and it cured it...my guess was that there wasn't permission to write that table... good luck! |
34,771,191 | I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message:
```
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is ... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34771191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497180/"
] | HI you must find this file : font\_manager.py in my case : C:\Users\gustavo\Anaconda3\Lib\site-packages\matplotlib\ font\_manager.py
and FIND def win32InstalledFonts(directory=None, fontext='ttf') and replace by :
def win32InstalledFonts(directory=None, fontext='ttf'):
"""
Search for fonts in the specified font dir... | This worked for me:
```
sudo apt-get install libfreetype6-dev libxft-dev
``` |
34,771,191 | I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message:
```
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is ... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34771191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497180/"
] | I ran the python code using sudo just once, and it resolved the warning for me.
Now it runs faster. Running without sudo gives no warning at all.
Cheers | HI you must find this file : font\_manager.py in my case : C:\Users\gustavo\Anaconda3\Lib\site-packages\matplotlib\ font\_manager.py
and FIND def win32InstalledFonts(directory=None, fontext='ttf') and replace by :
def win32InstalledFonts(directory=None, fontext='ttf'):
"""
Search for fonts in the specified font dir... |
34,771,191 | I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message:
```
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is ... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34771191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497180/"
] | As tom suggested in the comment above, deleting the files:
```
fontList.cache
fontList.py3k.cache
tex.cache
```
solve the problem.
In my case the files were under:
```
`~/.matplotlib`
```
EDITED
A couple of days ago the message appeared again, I deleted the files in the locations mention above without any su... | This worked for me on Ubuntu **16.04 LST** with **Python 3.5.2 | Anaconda 4.2.0 (64-bit)**. I deleted all of the files in `~/.cache/matplotlib/`.
```
sudo rm -r fontList.py3k.cache tex.cache
```
At first I thought it wouldn't work, because I got the warning afterward. But after the cache files were rebuilt the warn... |
34,771,191 | I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message:
```
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is ... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34771191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497180/"
] | Confirmed Hugo's approach works for Ubuntu 14.04 LTS/matplotlib 1.5.1:
* deleted ~/.cache/matplotlib/fontList.cache
* ran code, again the warning was issued (assumption: is rebuilding the cache correctly)
* ran code again, no more warning (finally) | HI you must find this file : font\_manager.py in my case : C:\Users\gustavo\Anaconda3\Lib\site-packages\matplotlib\ font\_manager.py
and FIND def win32InstalledFonts(directory=None, fontext='ttf') and replace by :
def win32InstalledFonts(directory=None, fontext='ttf'):
"""
Search for fonts in the specified font dir... |
34,771,191 | I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message:
```
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is ... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34771191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497180/"
] | Confirmed Hugo's approach works for Ubuntu 14.04 LTS/matplotlib 1.5.1:
* deleted ~/.cache/matplotlib/fontList.cache
* ran code, again the warning was issued (assumption: is rebuilding the cache correctly)
* ran code again, no more warning (finally) | This worked for me:
```
sudo apt-get install libfreetype6-dev libxft-dev
``` |
34,771,191 | I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message:
```
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is ... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34771191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497180/"
] | As tom suggested in the comment above, deleting the files:
```
fontList.cache
fontList.py3k.cache
tex.cache
```
solve the problem.
In my case the files were under:
```
`~/.matplotlib`
```
EDITED
A couple of days ago the message appeared again, I deleted the files in the locations mention above without any su... | Confirmed Hugo's approach works for Ubuntu 14.04 LTS/matplotlib 1.5.1:
* deleted ~/.cache/matplotlib/fontList.cache
* ran code, again the warning was issued (assumption: is rebuilding the cache correctly)
* ran code again, no more warning (finally) |
34,771,191 | I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message:
```
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is ... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34771191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497180/"
] | Confirmed Hugo's approach works for Ubuntu 14.04 LTS/matplotlib 1.5.1:
* deleted ~/.cache/matplotlib/fontList.cache
* ran code, again the warning was issued (assumption: is rebuilding the cache correctly)
* ran code again, no more warning (finally) | I ran the python code w. sudo and it cured it...my guess was that there wasn't permission to write that table... good luck! |
68,616,659 | I am trying to find all instance of a number within an equation. And for that, I wrote this python script:
```
re.findall(fr"([\-\+\*\/\(]|^)({val})([\-\+\*\/\)]|$)", equation)
```
Now, when I give it this: `20+5-20`, and search for `20`, the output is as expected: `[('', '20', '+'), ('-', '20', '')]`
But, when I si... | 2021/08/02 | [
"https://Stackoverflow.com/questions/68616659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8754028/"
] | The reason your pattern initially does not work for `20+20-5` is that the character class after matching the first occurrence of 20 actually consumes the `+`
After consuming it, for the second occurrence of 20 right after it, this part of the pattern `[\-\+\*\/\(]|^)` can not match as there is no character to match wi... | I suggest just searching for all numbers (integer + decimal) in your expression, and then filtering for certain values:
```py
inp = "20+5-20*3.20"
matches = re.findall(r'\d+(?:\.\d+)?', inp)
matches = [x for x in matches if x == '20']
print(matches) # ['20', '20']
```
Every number in your formula should *only* be s... |
68,616,659 | I am trying to find all instance of a number within an equation. And for that, I wrote this python script:
```
re.findall(fr"([\-\+\*\/\(]|^)({val})([\-\+\*\/\)]|$)", equation)
```
Now, when I give it this: `20+5-20`, and search for `20`, the output is as expected: `[('', '20', '+'), ('-', '20', '')]`
But, when I si... | 2021/08/02 | [
"https://Stackoverflow.com/questions/68616659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8754028/"
] | The reason your pattern initially does not work for `20+20-5` is that the character class after matching the first occurrence of 20 actually consumes the `+`
After consuming it, for the second occurrence of 20 right after it, this part of the pattern `[\-\+\*\/\(]|^)` can not match as there is no character to match wi... | I think I found an answer, still not sure how correct it is or why it's working and mine doesn't :/
```
re.findall(fr"(?:(?<=[\=\-\+\*\/\(])|^)({val})(?:(?=[\=\-\+\*\/\)])|$)", equation
```
basically, performing backward lookup and forward lookup to see if the value is between operations |
51,132,025 | I want to create a folder after an hour of the current time in python. I know how to get the current time and date and to create a folder. But how to create a folder at a time specified by me. Any help would be appreciated.
```
from datetime import datetime
from datetime import timedelta
import os
while True:
now... | 2018/07/02 | [
"https://Stackoverflow.com/questions/51132025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10020438/"
] | Try this simple code
```
import os
import time
while True:
time.sleep(3600) # pending for 1 hour (3600 seconds)
os.makedirs(your directory) # create the directory
```
EDIT (using parallel programming)
```
import os
import time
from datetime import datetime
from multiprocessing import Pool
def create_folde... | check this post for better explanation,you can create a function which will run after given time and you can use this function for creating a folder by simple one line code
os.makedirs("path\directory name")
[Python - Start a Function at Given Time](https://stackoverflow.com/questions/11523918/python-start-a-function-a... |
51,132,025 | I want to create a folder after an hour of the current time in python. I know how to get the current time and date and to create a folder. But how to create a folder at a time specified by me. Any help would be appreciated.
```
from datetime import datetime
from datetime import timedelta
import os
while True:
now... | 2018/07/02 | [
"https://Stackoverflow.com/questions/51132025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10020438/"
] | Try this simple code
```
import os
import time
while True:
time.sleep(3600) # pending for 1 hour (3600 seconds)
os.makedirs(your directory) # create the directory
```
EDIT (using parallel programming)
```
import os
import time
from datetime import datetime
from multiprocessing import Pool
def create_folde... | to create multiple folders after every 60 sec, folders like New1, New2,...
```
import time
while True:
time_Begin = time.time()
print("Creating Folder....")
# CODE FOR CREATING FOLDER AND CONDITION
time_End = time.time()
time_Elapsed = time_End - time_Begin
tim... |
42,696,635 | I am trying to use the owlready library in Python. I downloaded the file from link(<https://pypi.python.org/pypi/Owlready>) but when I am importing owlready I am getting following error:
```
>>> from owlready import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named '... | 2017/03/09 | [
"https://Stackoverflow.com/questions/42696635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5879314/"
] | Try installing it using `pip` instead.
Run the command `pip install <module name here>` to do so. If you are using python3, run `pip3 install <module name here>`.
If neither of these work you may also try:
`python -m pip install <module name here>`
or
`python3 -m pip install <module name here>`
If you don't yet ... | You need installed library:
```
C:\PythonX.X\Scripts
pip install owlready
Successfully installed Owlready-0.3
``` |
69,969,792 | So, I have to write a code in python that will draw four squares under a function called draw\_square that will take four arguments: the canvas on which the square will be drawn, the color of the square, the side length of the square, and the position of the center of the square. This function should draw the square an... | 2021/11/15 | [
"https://Stackoverflow.com/questions/69969792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17414982/"
] | Use `my_canvas.create_rectangle(...)`.
You were calling a draw rectangle from your function rather than the canvas itself.
Extra info: [Tkinter Canvas creating rectangle](https://stackoverflow.com/questions/42039564/tkinter-canvas-creating-rectangle) | you need to do following:
my\_canvas.create\_rectangle(...)
my\_canvas.pack()
...
...
after you finish for all 4 squares drawing and packing you need to call function like following:
draw\_square()
root.mainloop() |
50,505,067 | I have a simple DAG
```
from airflow import DAG
from airflow.contrib.operators.bigquery_operator import BigQueryOperator
with DAG(dag_id='my_dags.my_dag') as dag:
start = DummyOperator(task_id='start')
end = DummyOperator(task_id='end')
sql = """
SELECT *
FROM 'another_dataset... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50505067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5715610/"
] | You first need to create an Empty partitioned destination table. Follow instructions here: [link](https://cloud.google.com/bigquery/docs/creating-column-partitions#creating_an_empty_partitioned_table_with_a_schema_definition) to create an empty partitioned table
and then run below airflow pipeline again.
You can try c... | The main issue here is that I don't have access to the new version of google cloud python API, the prod is using version [0.27.0](https://gcloud-python.readthedocs.io/en/stable/bigquery/usage.html).
So, to get the job done, I made something bad and dirty:
* saved the query result in a sharded table, let it be `table_... |
50,505,067 | I have a simple DAG
```
from airflow import DAG
from airflow.contrib.operators.bigquery_operator import BigQueryOperator
with DAG(dag_id='my_dags.my_dag') as dag:
start = DummyOperator(task_id='start')
end = DummyOperator(task_id='end')
sql = """
SELECT *
FROM 'another_dataset... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50505067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5715610/"
] | You first need to create an Empty partitioned destination table. Follow instructions here: [link](https://cloud.google.com/bigquery/docs/creating-column-partitions#creating_an_empty_partitioned_table_with_a_schema_definition) to create an empty partitioned table
and then run below airflow pipeline again.
You can try c... | Using BigQueryOperator you can pass time\_partitioning parameter which will create ingestion-time partitioned tables
```
bq_cmd = BigQueryOperator (
task_id= "task_id",
sql= [query],
destination_dataset_table= destination_tbl,
u... |
50,505,067 | I have a simple DAG
```
from airflow import DAG
from airflow.contrib.operators.bigquery_operator import BigQueryOperator
with DAG(dag_id='my_dags.my_dag') as dag:
start = DummyOperator(task_id='start')
end = DummyOperator(task_id='end')
sql = """
SELECT *
FROM 'another_dataset... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50505067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5715610/"
] | You first need to create an Empty partitioned destination table. Follow instructions here: [link](https://cloud.google.com/bigquery/docs/creating-column-partitions#creating_an_empty_partitioned_table_with_a_schema_definition) to create an empty partitioned table
and then run below airflow pipeline again.
You can try c... | ```
from datetime import datetime,timedelta
from airflow import DAG
from airflow.models import Variable
from airflow.contrib.operators.bigquery_operator import BigQueryOperator
from airflow.operators.dummy_operator import DummyOperator
DEFAULT_DAG_ARGS = {
'owner': 'airflow',
'depends_on_past': False,
'ret... |
69,795,302 | I am a beginner in python so please be gentle and if you do have an answer please provide details.
I just installed the most recent python version 3.10 after making sure to delete all previous installations (including anaconda). I am positive my system is clear of any prior installation.
after installing python 3.10 ... | 2021/11/01 | [
"https://Stackoverflow.com/questions/69795302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5159404/"
] | You can refer to this answer solution with the highest upvotes - [Windows reports error when trying to install package using pipenv](https://stackoverflow.com/questions/46041719/windows-reports-error-when-trying-to-install-package-using-pipenv/46041892#46041892)
Or refer to this GitHub issue on pipenv - <https://githu... | Did follow the suggested steps, but did not work,
Later, set the `C:\Users\xxxxxxx\AppData\Roaming\Python\Python310\Scripts` to "PATH" environment variable and relaunched the cmd.
It worked like a charm...
Note: During the installation itself it warns to set the `C:\Users\xxxxxxx\AppData\Roaming\Python\Python310\Scri... |
69,795,302 | I am a beginner in python so please be gentle and if you do have an answer please provide details.
I just installed the most recent python version 3.10 after making sure to delete all previous installations (including anaconda). I am positive my system is clear of any prior installation.
after installing python 3.10 ... | 2021/11/01 | [
"https://Stackoverflow.com/questions/69795302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5159404/"
] | You can refer to this answer solution with the highest upvotes - [Windows reports error when trying to install package using pipenv](https://stackoverflow.com/questions/46041719/windows-reports-error-when-trying-to-install-package-using-pipenv/46041892#46041892)
Or refer to this GitHub issue on pipenv - <https://githu... | 1. Go to Advanced System Settings in Control Panel
2. Click on Environmental Variables
3. Under System Variables Look for PATH (If you don't see it then you can click on New and create one).
4. Click on Edit and in Variable Value Paste Link Which Look Like This C:\Users\xxxxxxx\AppData\Roaming\Python\Python310\Scripts
... |
69,795,302 | I am a beginner in python so please be gentle and if you do have an answer please provide details.
I just installed the most recent python version 3.10 after making sure to delete all previous installations (including anaconda). I am positive my system is clear of any prior installation.
after installing python 3.10 ... | 2021/11/01 | [
"https://Stackoverflow.com/questions/69795302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5159404/"
] | You can refer to this answer solution with the highest upvotes - [Windows reports error when trying to install package using pipenv](https://stackoverflow.com/questions/46041719/windows-reports-error-when-trying-to-install-package-using-pipenv/46041892#46041892)
Or refer to this GitHub issue on pipenv - <https://githu... | Search for Environmental Variables on your search and go on it
Click on the "Environmental Variables" Button
Under System Variables Look for PATH (If you don't see it then you can click on New and create one):
Click on Edit and in Variable Value Paste Link Which Look Like This C:\Users\xxxxxxx\AppData\Roaming\Python... |
69,795,302 | I am a beginner in python so please be gentle and if you do have an answer please provide details.
I just installed the most recent python version 3.10 after making sure to delete all previous installations (including anaconda). I am positive my system is clear of any prior installation.
after installing python 3.10 ... | 2021/11/01 | [
"https://Stackoverflow.com/questions/69795302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5159404/"
] | 1. Go to Advanced System Settings in Control Panel
2. Click on Environmental Variables
3. Under System Variables Look for PATH (If you don't see it then you can click on New and create one).
4. Click on Edit and in Variable Value Paste Link Which Look Like This C:\Users\xxxxxxx\AppData\Roaming\Python\Python310\Scripts
... | Did follow the suggested steps, but did not work,
Later, set the `C:\Users\xxxxxxx\AppData\Roaming\Python\Python310\Scripts` to "PATH" environment variable and relaunched the cmd.
It worked like a charm...
Note: During the installation itself it warns to set the `C:\Users\xxxxxxx\AppData\Roaming\Python\Python310\Scri... |
69,795,302 | I am a beginner in python so please be gentle and if you do have an answer please provide details.
I just installed the most recent python version 3.10 after making sure to delete all previous installations (including anaconda). I am positive my system is clear of any prior installation.
after installing python 3.10 ... | 2021/11/01 | [
"https://Stackoverflow.com/questions/69795302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5159404/"
] | 1. Go to Advanced System Settings in Control Panel
2. Click on Environmental Variables
3. Under System Variables Look for PATH (If you don't see it then you can click on New and create one).
4. Click on Edit and in Variable Value Paste Link Which Look Like This C:\Users\xxxxxxx\AppData\Roaming\Python\Python310\Scripts
... | Search for Environmental Variables on your search and go on it
Click on the "Environmental Variables" Button
Under System Variables Look for PATH (If you don't see it then you can click on New and create one):
Click on Edit and in Variable Value Paste Link Which Look Like This C:\Users\xxxxxxx\AppData\Roaming\Python... |
20,590,331 | On my local PC I can do "python manage.py runserver" and the site runs perfectly, CSS and all. I just deployed the site to a public server and while most things work, CSS (and the images) are not loading into the templates.
I found some other questions with a similar issue, but my code did not appear to suffer from an... | 2013/12/15 | [
"https://Stackoverflow.com/questions/20590331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1803100/"
] | In Winforms(or even in WPF) only the thread who create the component can update it you should make your code thread-safe.
For this reason the debugger raises an InvalidOperationException with the message, "Control control name accessed from a thread other than the thread it was created on." which is encapsulated as Agg... | Another option to use a Task result within the calling thread is using `async/await` key word. This way compiler do the work of capture the right `TaskScheduler` for you. Look code below. You need to add `try/catch` statements for Exceptions handling.
This way, code is still asynchronous but looks like a synchronous o... |
20,590,331 | On my local PC I can do "python manage.py runserver" and the site runs perfectly, CSS and all. I just deployed the site to a public server and while most things work, CSS (and the images) are not loading into the templates.
I found some other questions with a similar issue, but my code did not appear to suffer from an... | 2013/12/15 | [
"https://Stackoverflow.com/questions/20590331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1803100/"
] | By default continuation runs on default scheduler which is Threadpool Scheduler. Threadpool threads are always background threads so they can't update the UI components (as UI components always run on foreground thread). So your code won't work.
**Fix: Get the scheduler from UI thread.This will ensure that the contin... | Another option to use a Task result within the calling thread is using `async/await` key word. This way compiler do the work of capture the right `TaskScheduler` for you. Look code below. You need to add `try/catch` statements for Exceptions handling.
This way, code is still asynchronous but looks like a synchronous o... |
69,628,226 | I have made an browser with python. I converted it into exe file with pyinstaller. But it's size is 109,426kb!!! I need to upload it to some places and it is showing "Please try to upload files under 25md". What will I do? How to change this big exe file 24mb file? | 2021/10/19 | [
"https://Stackoverflow.com/questions/69628226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15622728/"
] | If you have task that is re-run with the same "Execution Date", using Airflow Variables is your best choice. XCom will be deleted by definition when you re-run the same task with the same execution date and it won't change.
Basically what you want to do is to store the "state" of task execution and it's kinda "against... | You could use XComs with `include_prior_dates` parameter. [Docs](https://airflow.apache.org/docs/apache-airflow/stable/_api/airflow/models/taskinstance/index.html#airflow.models.taskinstance.TaskInstance.xcom_pull) state the following:
>
> **include\_prior\_dates** (bool) -- If False, only XComs from the current exec... |
68,653,388 | I want to replace the values in manifest.json. My manifest.json file looks like
```
{
"uat1": {
"database": {
"artifact_version": "0.0.1",
"date": "sysdate"
},
"services1": {
"artifact_version": "0.0.1",
"date": "sysdate"
},
"p_database": {
"artifact_version": "0.... | 2021/08/04 | [
"https://Stackoverflow.com/questions/68653388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4632240/"
] | Just parse it, update the necessary value, and write it back to the file.
```
with open("manifest.json") as f:
d = json.load(f)
d[env][script] = {"artifact_version": ..., "date": ...}
with tempfile.NamedTemporaryFile(delete=False) as f:
try:
json.dump(d, f)
except Exception:
raise
els... | No, to 'edit' a `json` file, you have to load the whole file in with: `data = json.load(f1)`, then perform the transform, then write the write the whole lot out again:
```py
with open("C:/Users/lohapri/PycharmProjects/RFOS/manifest.json", "r") as f1:
data = json.load(f1)
#no close needed
#print(data)
for k1, v1 i... |
68,653,388 | I want to replace the values in manifest.json. My manifest.json file looks like
```
{
"uat1": {
"database": {
"artifact_version": "0.0.1",
"date": "sysdate"
},
"services1": {
"artifact_version": "0.0.1",
"date": "sysdate"
},
"p_database": {
"artifact_version": "0.... | 2021/08/04 | [
"https://Stackoverflow.com/questions/68653388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4632240/"
] | You have dict and there is no need to iterate through it
And you need to dump json just once
```py
data[env][script].update(
artifact_version = version,
date = sdate
)
with open("C:/Users/lohapri/PycharmProjects/RFOS/manifest.json", "w") as f2:
json.dump(data, f2, indent=4)
``` | No, to 'edit' a `json` file, you have to load the whole file in with: `data = json.load(f1)`, then perform the transform, then write the write the whole lot out again:
```py
with open("C:/Users/lohapri/PycharmProjects/RFOS/manifest.json", "r") as f1:
data = json.load(f1)
#no close needed
#print(data)
for k1, v1 i... |
68,653,388 | I want to replace the values in manifest.json. My manifest.json file looks like
```
{
"uat1": {
"database": {
"artifact_version": "0.0.1",
"date": "sysdate"
},
"services1": {
"artifact_version": "0.0.1",
"date": "sysdate"
},
"p_database": {
"artifact_version": "0.... | 2021/08/04 | [
"https://Stackoverflow.com/questions/68653388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4632240/"
] | You have dict and there is no need to iterate through it
And you need to dump json just once
```py
data[env][script].update(
artifact_version = version,
date = sdate
)
with open("C:/Users/lohapri/PycharmProjects/RFOS/manifest.json", "w") as f2:
json.dump(data, f2, indent=4)
``` | Just parse it, update the necessary value, and write it back to the file.
```
with open("manifest.json") as f:
d = json.load(f)
d[env][script] = {"artifact_version": ..., "date": ...}
with tempfile.NamedTemporaryFile(delete=False) as f:
try:
json.dump(d, f)
except Exception:
raise
els... |
59,939,819 | I am trying to run Django unit tests in the VSCode Test Explorer, also, I want the CodeLens 'Run Tests' button to appear above each test.
[enter image description here](https://i.stack.imgur.com/kTTjN.png)
However, in the Test Explorer, When I press the Play button, an error displays:
"No Tests were Ran" [No Tests were... | 2020/01/27 | [
"https://Stackoverflow.com/questions/59939819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12064691/"
] | Please consider the following checks:
1. you should have `__init__.py` in your test directory
2. in vscode on test configuration use pytest framework
3. use: `pip install pytest-django`
4. copy `pytest.ini` in the root with this content:
```
# -- FILE: pytest.ini (or tox.ini)
[pytest]
DJANGO_SETTINGS_MODULE = <your-w... | I've been looking into this as well. The thing is that python unittest pytest and nose are not alternative to Django tests, because they would not be able to load everything Django tests do.
Django Test Runner might work for you:
<https://marketplace.visualstudio.com/items?itemName=Pachwenko.django-test-runner>
-- I ... |
59,939,819 | I am trying to run Django unit tests in the VSCode Test Explorer, also, I want the CodeLens 'Run Tests' button to appear above each test.
[enter image description here](https://i.stack.imgur.com/kTTjN.png)
However, in the Test Explorer, When I press the Play button, an error displays:
"No Tests were Ran" [No Tests were... | 2020/01/27 | [
"https://Stackoverflow.com/questions/59939819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12064691/"
] | I've been looking into this as well. The thing is that python unittest pytest and nose are not alternative to Django tests, because they would not be able to load everything Django tests do.
Django Test Runner might work for you:
<https://marketplace.visualstudio.com/items?itemName=Pachwenko.django-test-runner>
-- I ... | Here is generic way to get Django tests to run with **full** vscode support
1. Configure python tests
1. Choose unittest
2. Root Directory
3. `test*.py`
2. Then each test case will need to look like the following:
```
from django.test import TestCase
class views(TestCase):
@classmethod
def setUpClass(cls... |
59,939,819 | I am trying to run Django unit tests in the VSCode Test Explorer, also, I want the CodeLens 'Run Tests' button to appear above each test.
[enter image description here](https://i.stack.imgur.com/kTTjN.png)
However, in the Test Explorer, When I press the Play button, an error displays:
"No Tests were Ran" [No Tests were... | 2020/01/27 | [
"https://Stackoverflow.com/questions/59939819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12064691/"
] | Please consider the following checks:
1. you should have `__init__.py` in your test directory
2. in vscode on test configuration use pytest framework
3. use: `pip install pytest-django`
4. copy `pytest.ini` in the root with this content:
```
# -- FILE: pytest.ini (or tox.ini)
[pytest]
DJANGO_SETTINGS_MODULE = <your-w... | Here is generic way to get Django tests to run with **full** vscode support
1. Configure python tests
1. Choose unittest
2. Root Directory
3. `test*.py`
2. Then each test case will need to look like the following:
```
from django.test import TestCase
class views(TestCase):
@classmethod
def setUpClass(cls... |
33,551,878 | I'm having a problem to read partitioned parquet files generated by Spark in Hive. I'm able to create the external table in hive but when I try to select a few lines, hive returns only an "OK" message with no rows.
I'm able to read the partitioned parquet files correctly in Spark, so I'm assuming that they were genera... | 2015/11/05 | [
"https://Stackoverflow.com/questions/33551878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5529573/"
] | I finally found the problem. When you create tables in Hive, where partitioned data already exists in S3 or HDFS, you need to run a command to update the Hive Metastore with the table's partition structure. Take a look here:
<https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-RecoverP... | Even though this Question was answered already, the following point may also help the users who are still not able to solve the issue just by `MSCK REPAIR TABLE table_name;`
I have an hdfs file system which is partitioned as below:
`<parquet_file>/<partition1>/<partition2>`
eg: `my_file.pq/column_5=test/column_6=5`
... |
12,177,405 | Dear python 3 experts,
with python2, one could do the following (I know this is a bit hairy, but that's not the point here :p):
```
class A(object):
def method(self, other):
print self, other
class B(object): pass
B.method = types.MethodType(A().method, None, B)
B.method() # print both A and B instances
```
... | 2012/08/29 | [
"https://Stackoverflow.com/questions/12177405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/853679/"
] | ```
B.method = lambda o: A.method(o,A())
b = B()
b.method()
```
the line `b.method()` then calls `A.method(b,A())`. This means a A is initialized each time. To avoid this:
```
a = A()
B.method = lambda o: A.method(o,a)
```
now every time you call b.method() on any instance of B the same instance of A is passed as... | Well, your code doesn't work in Python 2 either, but I get what you are trying to do. And you can use lambda, as in Sheena's answer, or functools.partial.
```
>>> import types
>>> from functools import partial
>>> class A(object):
... def method(self, other):
... print self, other
...
>>> class B(object): pass... |
46,395,273 | First post here at stack overflow. Please forgive my posting errors.
I have spent a lot of time at this. I started with the 500 server error.
This long is stating python not found. My app is JS, CSS, and HTML only. (at this point) I have included the yaml, because I cant rule out for myself if I have errors there ... | 2017/09/24 | [
"https://Stackoverflow.com/questions/46395273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4907940/"
] | If your app is only HTML, CSS, and JS, you can remove the catch-all pointer to the Python script all together and instead use an `app.yaml` format like the one shown in the [Hosting a Static Website on App Engine tutorial](https://cloud.google.com/appengine/docs/standard/python/getting-started/hosting-a-static-website#... | Your `script: main.py` statement in the `handlers` section of the `app.yaml` file is wrong, it should be `script: main.app`.
From the `script` row in the [Handlers element](https://cloud.google.com/appengine/docs/standard/python/config/appref#handlers_element) table (sadly not properly formatted, including the quote ... |
61,206,895 | the python script does execute well manually through the terminal:
```
sudo python3 /home/pi/Documents/AlarmClock/alarm.py
```
but it does not work automatically by the crontab. Here is the cronjob (crontab -e) in the /tmp/crontab.iGf7md/crontab file:
```
32 13 2 * * sudo python3 /home/pi/Documents/AlarmClock/alarm... | 2020/04/14 | [
"https://Stackoverflow.com/questions/61206895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use `array_keys` with search value [PHP Doc](https://www.php.net/manual/en/function.array-keys.php)
[Demo](https://3v4l.org/kfTZH)
```
array_keys($arr,3)
```
---
>
> `array_keys()` returns the keys, numeric and string, from the array.
>
>
> If a search\_value is specified, then only the keys for that va... | With that solution you can create complex filters. In this case we compare every value to be the number three (=== operator). The filter returns the index, when the comparision true, else it will be dropped.
```
$a = [1,2,3,4,3,3,5,6];
$threes = array_filter($a, function($v, $k) {
return $v === 3 ? $k : false; },
... |
61,206,895 | the python script does execute well manually through the terminal:
```
sudo python3 /home/pi/Documents/AlarmClock/alarm.py
```
but it does not work automatically by the crontab. Here is the cronjob (crontab -e) in the /tmp/crontab.iGf7md/crontab file:
```
32 13 2 * * sudo python3 /home/pi/Documents/AlarmClock/alarm... | 2020/04/14 | [
"https://Stackoverflow.com/questions/61206895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use `array_keys` with search value [PHP Doc](https://www.php.net/manual/en/function.array-keys.php)
[Demo](https://3v4l.org/kfTZH)
```
array_keys($arr,3)
```
---
>
> `array_keys()` returns the keys, numeric and string, from the array.
>
>
> If a search\_value is specified, then only the keys for that va... | you can use array\_keys:
```
foreach (array_keys($arr) as $key) if ($arr[$key] == 3) $result[] = $key;
``` |
43,967,051 | What is an alternative to firebase for user management/auth for python apps. I know I can use node.js w/ firebase but, I would rather authenticate users through a managed 3rd party API in python using HTTPS requests,if possible. Appery.io has this feature but, I do not need all that comes with appery.io | 2017/05/14 | [
"https://Stackoverflow.com/questions/43967051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7317396/"
] | Check out [Amazon Cognito](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjphrjN7-PXAhUEhuAKHSABA14QFggnMAA&url=https%3A%2F%2Faws.amazon.com%2Fcognito%2F&usg=AOvVaw0IxXy-fQjM_msyj67tH2wG) . They offer a quite nice package for small projects. [Backendless](http://backendless.co... | You could try using [Auth0](https://auth0.com/) for pure authentication management. The Auth0 python package can be found [here](https://github.com/auth0/auth0-python). |
43,967,051 | What is an alternative to firebase for user management/auth for python apps. I know I can use node.js w/ firebase but, I would rather authenticate users through a managed 3rd party API in python using HTTPS requests,if possible. Appery.io has this feature but, I do not need all that comes with appery.io | 2017/05/14 | [
"https://Stackoverflow.com/questions/43967051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7317396/"
] | Check out [Amazon Cognito](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjphrjN7-PXAhUEhuAKHSABA14QFggnMAA&url=https%3A%2F%2Faws.amazon.com%2Fcognito%2F&usg=AOvVaw0IxXy-fQjM_msyj67tH2wG) . They offer a quite nice package for small projects. [Backendless](http://backendless.co... | If you're looking for a self-hosted solution, [Keycloak](https://www.keycloak.org/) is a pretty robust option. If you want a service, [Auth0](https://auth0.com/) and [Okta](https://okta.com/) have quite a lot of features. They also offer a free tier with reasonable limits. |
43,967,051 | What is an alternative to firebase for user management/auth for python apps. I know I can use node.js w/ firebase but, I would rather authenticate users through a managed 3rd party API in python using HTTPS requests,if possible. Appery.io has this feature but, I do not need all that comes with appery.io | 2017/05/14 | [
"https://Stackoverflow.com/questions/43967051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7317396/"
] | If you're looking for a self-hosted solution, [Keycloak](https://www.keycloak.org/) is a pretty robust option. If you want a service, [Auth0](https://auth0.com/) and [Okta](https://okta.com/) have quite a lot of features. They also offer a free tier with reasonable limits. | You could try using [Auth0](https://auth0.com/) for pure authentication management. The Auth0 python package can be found [here](https://github.com/auth0/auth0-python). |
16,973,236 | I recently installed Emacs 24.3 and try to use it coding for Python (v3.3.2 x86-64 MSI installer). (I'm new to Emacs). Then i try to install emacs-for-python by unpack the zip to
```
"C:\Users\mmsc\AppData\Roaming\.emacs.d\emacs-for-python"
```
folder and add
```
: (load-file "~/.emacs.d/emacs-for-python/epy-ini... | 2013/06/06 | [
"https://Stackoverflow.com/questions/16973236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118555/"
] | This was a little too much for a comment:
```
(let ((process
(apply 'start-process "pymacs" buffer
(let ((python (getenv "PYMACS_PYTHON")))
(if (or (null python) (equal python ""))
pymacs-python-command
python))
... | I had the same symptoms but what my problem turned out to be was an old pymacs.el and a new Pymacs. Evidently Pymacs changed the module interface and I had to go hunt down the stray pymacs.el. So the pymacs.el was installed by apt-get in an odd location. You have to make sure the byte code file is gone too. |
55,784,213 | Noob, trying to create a simple form, and validate the inputs on same. However, I don't know how to properly select each input in js, so nothing is happening. I am just learning html, bootstrap and javascript, so simpler (pythonic) answers are preferred to more complex ones.
I've read the documentation, and a number ... | 2019/04/21 | [
"https://Stackoverflow.com/questions/55784213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8519006/"
] | The reason for partial match is that engine doesn't know exactly where it should start from regarding your requirements. You tell engine by including `\d` in character class:
```
(?<![[:space:][:punct:]\d])\d+
^^
``` | [This RegEx](https://regex101.com/r/ruSstp/1/) might help you to divide your string input into two groups, where the second group (`$2`) is the target number and group one (`$1`) is the non-digit behind it:
```
([A-Za-z_+-]+)([0-9]+)
```
[](https://i.stack.imgur.com/ubaKl... |
58,211,638 | I want to connect to Twitch server. But Godot adds binary characters in front of my data as you can see in the pictures. This happens everytime no matter the data type. Why is this happenning and how can I prevent this happening?
[](https://i.s... | 2019/10/03 | [
"https://Stackoverflow.com/questions/58211638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10558295/"
] | You can use shapes as well with your background modifier instead using a Color.
Change
```
}.overlay(
RoundedRectangle(cornerRadius: 40)
.stroke(Color.green, lineWidth: 1)
).background(Color.gray)
```
to
```
}.overlay(
RoundedRectangle(cornerRadius: 40)
.stroke(Color.green, lineWidth: 1)... | What you need is one more modifier to cut off anything outside the thin green outline, add this after `.background`:
```
.clipShape(RoundedRectangle(cornerRadius: 40))
```
**EDIT**
Capsule is a better shape to use in place of RoundedRectangle to achieve matching curves:
```
var body: some View {
HStack {
... |
31,154,087 | I am developing flask app. I made one table which will populate with JSON data. For Front end I am using Angularjs and for back-end I am using flask. But I am not able to populate the table and getting error like "**UndefinedError: 'task' is undefined.**"
**Directory of flask project**
flask\_project/
rest-server.... | 2015/07/01 | [
"https://Stackoverflow.com/questions/31154087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4884941/"
] | i think it's because you have two ng-app definitions in your index.html
remove the definition in your html tag and try again
```
<html ng-app="tableJson">
```
into
```
<html>
``` | Try this
```
$scope.tasks = data;
```
it works for me |
31,154,087 | I am developing flask app. I made one table which will populate with JSON data. For Front end I am using Angularjs and for back-end I am using flask. But I am not able to populate the table and getting error like "**UndefinedError: 'task' is undefined.**"
**Directory of flask project**
flask\_project/
rest-server.... | 2015/07/01 | [
"https://Stackoverflow.com/questions/31154087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4884941/"
] | i think it's because you have two ng-app definitions in your index.html
remove the definition in your html tag and try again
```
<html ng-app="tableJson">
```
into
```
<html>
``` | You should use an Angular service to get the data from the server. |
14,129,983 | I need a script that updates my copy of a repository. When I type "svn up" I usually am forced to enter a password, how do I automate the password entry?
What I've tried:
```
import pexpect, sys, re
pexpect.run("svn cleanup")
child = pexpect.spawn('svn up')
child.logfile = sys.stdout
child.expect("Enter passphrase... | 2013/01/02 | [
"https://Stackoverflow.com/questions/14129983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/424631/"
] | If you don't want to type password many times, but still have a secure solution you can use **ssh-agent** to keep your key passphrases for a while. If you use your default private key simply type `ssh-add` and give your passphrase when asked.
More details on `ssh-add` command usage are here: [linux.die.net/man/1/ssh-a... | You should really just use ssh with public keys.
In the absence of that, you can simply create a new file in `~/.subversion/auth/svn.simple/` with the contents:
```
K 8
passtype
V 6
simple
K 999
password
V 7
password_goes_here
K 15
svn:realmstring
V 999
<url> real_identifier
K 8
username
V 999
username_goes_here
END
... |
23,390,397 | So i've been at this one for a little while and cant seem to get it. Im trying to execute a python script via terminal and want to pass a string value with it. That way, when the script starts, it can check that value and act accordingly. Like this:
```
sudo python myscript.py mystring
```
How can i go about doing t... | 2014/04/30 | [
"https://Stackoverflow.com/questions/23390397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1661607/"
] | Try the following inside ur script:
```
import sys
arg1 = str(sys.argv[1])
print(arg1)
``` | Since you are passing a string, you need to pass it in quotes:
```
sudo python myscript.py 'mystring'
```
Also, you shouldn't have to run it with sudo. |
57,809,780 | I'm trying to convert a .tif image in python using the module skimage.
It's not working properly.
```
from skimage import io
img = io.imread('/content/IMG_0007_4.tif')
io.imsave('/content/img.jpg', img)
```
Here is the error:
```
/usr/local/lib/python3.6/dist-packages/imageio/core/functions.py in get_writer(uri, fo... | 2019/09/05 | [
"https://Stackoverflow.com/questions/57809780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8229169/"
] | 1. I don't think HAVING will work without GROUP.
2. I would move the having clause outside the include section and use the AS aliases.
So, roughly:
`group: ['id'], // and whatever else you need
having : { 'documents.total_balance_due' : {$eq : 0 }}`
(Making some guesses vis the aliases) | >
> To filter the date from joined table which uses groupby as well, you can make use of HAVING Property, which is accepted by Sequelize.
>
>
>
So with respect to your question, I am providing the answer.
You can make use of this code:
```
const Sequelize = require('sequelize');
let searchQuery = {
attribut... |
26,290,871 | How can I build a python distribution RPM that is only dependent on an *earlier* version of python?
**Why?** I'm trying to build a distribution RPMs for RHEL6/CentOS 6, which only includes Python 2.6, but I am building usually on machines with Python 2.7.
This is an open source project, and I have already ensured t... | 2014/10/10 | [
"https://Stackoverflow.com/questions/26290871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95122/"
] | Re-organized the answer.
Actually, there's no "rpm-package". There're rpm-packages for RHEL6, rpm-packages for FedoraNN, rpm-packagse for OpenSUSE-X.Y and so on. And besides there're Debian, Ubuntu, Arch and Gentoo :)
You have the following possibilities with your Python package:
1. You may completely avoid rpm-, de... | I do not do very much python work but have done some RPM packaging. You probably need to somehow do what one would normally do in the RPM's spec file and specify and require a particular release of your python package like so ...
```
# this would be in your spec file
requires: python <= 2.6
```
Take a look here for ... |
31,910,680 | I installed the networking module **Scapy**.
When I import scapy (`import scapy`) everything works fine. When I import all from scapy (`from scapy.all import *`), it brings up this error:
```
Traceback (most recent call last):
File "/Users/***/Downloads/test.py", line 5, in <module>
from scapy.all import *
File "/Libr... | 2015/08/10 | [
"https://Stackoverflow.com/questions/31910680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4844191/"
] | **You can now install this easily** with [Homebrew](http://brew.sh) by using the command:
```
brew install libdnet
```
after you've installed Homebrew. | **Up-to-date edit: this issue has been fixed on recent versions of scapy, simply update your scapy version using `pip install scapy>=2.4.0`**
You have to install libdnet. Not the python library (which does not work on python3 as you mentioned), but the library itself. There has to be library file libdnet.so somewhere ... |
31,910,680 | I installed the networking module **Scapy**.
When I import scapy (`import scapy`) everything works fine. When I import all from scapy (`from scapy.all import *`), it brings up this error:
```
Traceback (most recent call last):
File "/Users/***/Downloads/test.py", line 5, in <module>
from scapy.all import *
File "/Libr... | 2015/08/10 | [
"https://Stackoverflow.com/questions/31910680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4844191/"
] | **Up-to-date edit: this issue has been fixed on recent versions of scapy, simply update your scapy version using `pip install scapy>=2.4.0`**
You have to install libdnet. Not the python library (which does not work on python3 as you mentioned), but the library itself. There has to be library file libdnet.so somewhere ... | You can try the following:
```
git clone https://github.com/secdev/scapy
cd scapy
./run_scapy
``` |
31,910,680 | I installed the networking module **Scapy**.
When I import scapy (`import scapy`) everything works fine. When I import all from scapy (`from scapy.all import *`), it brings up this error:
```
Traceback (most recent call last):
File "/Users/***/Downloads/test.py", line 5, in <module>
from scapy.all import *
File "/Libr... | 2015/08/10 | [
"https://Stackoverflow.com/questions/31910680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4844191/"
] | **You can now install this easily** with [Homebrew](http://brew.sh) by using the command:
```
brew install libdnet
```
after you've installed Homebrew. | You can try the following:
```
git clone https://github.com/secdev/scapy
cd scapy
./run_scapy
``` |
73,920,457 | How for I get the "rest of the list" after the the current element for an iterator in a loop?
I have a list:
`[ "a", "b", "c", "d" ]`
They are not actually letters, they are words, but the letters are there for illustration, and there is no reason to expect the list to be small.
For each member of the list, I need ... | 2022/10/01 | [
"https://Stackoverflow.com/questions/73920457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1783593/"
] | Seems like there are plenty of answers here, but another way to solve your given problem:
```py
def f(depth, l):
for idx, item in enumerate(l):
step = f"{depth * ' '} {depth} {item[0]}"
print(step)
f(depth + 1, l[idx + 1:])
f(0,[ "a", "b", "c", "d" ])
``` | ```
def f(depth, alist):
# you dont need this if you only care about first
# for i in list:
print(f"{depth} {alist[0]}")
next_depth = depth + 1
rest_list = alist[1:]
f(next_depth,rest_list)
```
this doesnt seem like a very useful method though
```
def f(depth, alist):
# if you actually want to iterate... |
73,920,457 | How for I get the "rest of the list" after the the current element for an iterator in a loop?
I have a list:
`[ "a", "b", "c", "d" ]`
They are not actually letters, they are words, but the letters are there for illustration, and there is no reason to expect the list to be small.
For each member of the list, I need ... | 2022/10/01 | [
"https://Stackoverflow.com/questions/73920457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1783593/"
] | Seems like there are plenty of answers here, but another way to solve your given problem:
```py
def f(depth, l):
for idx, item in enumerate(l):
step = f"{depth * ' '} {depth} {item[0]}"
print(step)
f(depth + 1, l[idx + 1:])
f(0,[ "a", "b", "c", "d" ])
``` | I guess this code is what you're looking for
```
def f(depth, lst):
for e,i in enumerate(lst):
print(f"{depth} {i}")
f(depth+1, lst[e+1:])
f(0,[ "a", "b", "c", "d" ])
``` |
48,535,962 | My data has a feature called level, and the data may have levels(-1,0,1,2,3) but my data now has only 2 levels 0 and -1. I'm using python for binary classification. How to do one-hot-encoding with all levels? What is the right approach to deal with this problem? Can I include all levels as I may expect them in test dat... | 2018/01/31 | [
"https://Stackoverflow.com/questions/48535962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9186358/"
] | Currently it is assigning the last value as all parameter have same name.
You can use `[]` after variable name , it will create newcoach array with all values within it.
```
$test = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
echo '<pre>';
parse_str($test,$result);
print_r($result);
```
... | Use this function
```
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
... |
48,535,962 | My data has a feature called level, and the data may have levels(-1,0,1,2,3) but my data now has only 2 levels 0 and -1. I'm using python for binary classification. How to do one-hot-encoding with all levels? What is the right approach to deal with this problem? Can I include all levels as I may expect them in test dat... | 2018/01/31 | [
"https://Stackoverflow.com/questions/48535962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9186358/"
] | Since you set your argument **newcoach** multiple times, parse\_str will only return the last one. If you want parse\_str to parse your variable as an array you need to supply it in this format with a '**[ ]**' suffix:
```
$newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
```
**Exam... | Use this function
```
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
... |
48,535,962 | My data has a feature called level, and the data may have levels(-1,0,1,2,3) but my data now has only 2 levels 0 and -1. I'm using python for binary classification. How to do one-hot-encoding with all levels? What is the right approach to deal with this problem? Can I include all levels as I may expect them in test dat... | 2018/01/31 | [
"https://Stackoverflow.com/questions/48535962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9186358/"
] | Since you set your argument **newcoach** multiple times, parse\_str will only return the last one. If you want parse\_str to parse your variable as an array you need to supply it in this format with a '**[ ]**' suffix:
```
$newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
```
**Exam... | Currently it is assigning the last value as all parameter have same name.
You can use `[]` after variable name , it will create newcoach array with all values within it.
```
$test = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
echo '<pre>';
parse_str($test,$result);
print_r($result);
```
... |
39,303,710 | I am new to Python and machine learning and i am trying to work out how to fix this issue with date time. next\_unix is 13148730, because that is how many seconds are in five months, which is the time in between my dates. I have searched and i can't seem to find anything that works.
```
last_date = df.iloc[1,0]
last_u... | 2016/09/03 | [
"https://Stackoverflow.com/questions/39303710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770803/"
] | If my understanding is correct then you can get desired result with the following:
```
SELECT i.*,
CASE WHEN prop1.PROPERTY_ID = 1 THEN prop1.VALUE ELSE '' END AS PROPERTY_ONE,
CASE WHEN prop1.PROPERTY_ID = 2 THEN prop1.VALUE ELSE '' END AS PROPERTY_TWO
FROM ITEM i
LEFT JOIN ITEM_PROPERTY prop1 on i.ITEM_I... | ```
Select i.*, GROUP_CONCAT(prop.VALUE) as PROPERTY_VALUE
From ITEM i
Left Join ITEM_PROPERTY prop on i.ITEM_ID = prop.ITEM_D
``` |
39,303,710 | I am new to Python and machine learning and i am trying to work out how to fix this issue with date time. next\_unix is 13148730, because that is how many seconds are in five months, which is the time in between my dates. I have searched and i can't seem to find anything that works.
```
last_date = df.iloc[1,0]
last_u... | 2016/09/03 | [
"https://Stackoverflow.com/questions/39303710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770803/"
] | Old style:
```
Select i.*,
max(decode(prop.PROPERTY_ID,1,prop.VALUE,NULL)) as PROPERTY_ONE,
max(decode(prop.PROPERTY_ID,2,prop.VALUE,NULL)) as PROPERTY_TWO
From ITEM i
Left Join ITEM_PROPERTY prop on i.ITEM_ID = prop.ITEM_D and prop.PROPERTY_ID in(1,2)
group by there_will_have_to_list_all_the_fields... | ```
Select i.*, GROUP_CONCAT(prop.VALUE) as PROPERTY_VALUE
From ITEM i
Left Join ITEM_PROPERTY prop on i.ITEM_ID = prop.ITEM_D
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.