qid
int64 469
74.7M
| question
stringlengths 36
37.8k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 5
31.5k
| response_k
stringlengths 10
31.6k
|
---|---|---|---|---|---|
37,891,954 | I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use `models.predict()`?
Do I have to prepare this text in a special way?
I tried it with
```
import keras.preprocessing.text
text = np.array(['this is just some random, stupid text'])
print(text.shape)
tk = keras.preprocessing.text.Tokenizer(
nb_words=2000,
filters=keras.preprocessing.text.base_filter(),
lower=True,
split=" ")
tk.fit_on_texts(text)
pred = tk.texts_to_sequences(text)
print(pred)
model.predict(pred)
```
But I always get
```
(1L,)
[[2, 4, 1, 6, 5, 7, 3]]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-83-42d744d811fb> in <module>()
7 print(pred)
8
----> 9 model.predict(pred)
C:\Users\bkey\Anaconda2\lib\site-packages\keras\models.pyc in predict(self, x, batch_size, verbose)
457 if self.model is None:
458 self.build()
--> 459 return self.model.predict(x, batch_size=batch_size, verbose=verbose)
460
461 def predict_on_batch(self, x):
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in predict(self, x, batch_size, verbose)
1132 x = standardize_input_data(x, self.input_names,
1133 self.internal_input_shapes,
-> 1134 check_batch_dim=False)
1135 if self.stateful:
1136 if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in standardize_input_data(data, names, shapes, check_batch_dim, exception_prefix)
79 for i in range(len(names)):
80 array = arrays[i]
---> 81 if len(array.shape) == 1:
82 array = np.expand_dims(array, 1)
83 arrays[i] = array
AttributeError: 'list' object has no attribute 'shape'
```
Do you have any recommendations as to how to make predictions with a trained model? | 2016/06/18 | [
"https://Stackoverflow.com/questions/37891954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5931447/"
] | Your can use your tokenizer and pad sequencing for a new piece of text. This is followed by model prediction. This will return the prediction as a numpy array plus the label itself.
For example:
```
new_complaint = ['Your service is not good']
seq = tokenizer.texts_to_sequences(new_complaint)
padded = pad_sequences(seq, maxlen=maxlen)
pred = model.predict(padded)
print(pred, labels[np.argmax(pred)])
``` | I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.
```
fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
recreatedModel.load_weights(fname)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
standard_scalerX.fit(X_test)
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)
``` |
37,891,954 | I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use `models.predict()`?
Do I have to prepare this text in a special way?
I tried it with
```
import keras.preprocessing.text
text = np.array(['this is just some random, stupid text'])
print(text.shape)
tk = keras.preprocessing.text.Tokenizer(
nb_words=2000,
filters=keras.preprocessing.text.base_filter(),
lower=True,
split=" ")
tk.fit_on_texts(text)
pred = tk.texts_to_sequences(text)
print(pred)
model.predict(pred)
```
But I always get
```
(1L,)
[[2, 4, 1, 6, 5, 7, 3]]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-83-42d744d811fb> in <module>()
7 print(pred)
8
----> 9 model.predict(pred)
C:\Users\bkey\Anaconda2\lib\site-packages\keras\models.pyc in predict(self, x, batch_size, verbose)
457 if self.model is None:
458 self.build()
--> 459 return self.model.predict(x, batch_size=batch_size, verbose=verbose)
460
461 def predict_on_batch(self, x):
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in predict(self, x, batch_size, verbose)
1132 x = standardize_input_data(x, self.input_names,
1133 self.internal_input_shapes,
-> 1134 check_batch_dim=False)
1135 if self.stateful:
1136 if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in standardize_input_data(data, names, shapes, check_batch_dim, exception_prefix)
79 for i in range(len(names)):
80 array = arrays[i]
---> 81 if len(array.shape) == 1:
82 array = np.expand_dims(array, 1)
83 arrays[i] = array
AttributeError: 'list' object has no attribute 'shape'
```
Do you have any recommendations as to how to make predictions with a trained model? | 2016/06/18 | [
"https://Stackoverflow.com/questions/37891954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5931447/"
] | [`model.predict()`](http://keras.io/models/model/#predict) expects the first parameter to be a numpy array. You supply a list, which does not have the `shape` attribute a numpy array has.
Otherwise your code looks fine, except that you are doing nothing with the prediction. Make sure you store it in a variable, for example like this:
```
prediction = model.predict(np.array(tk.texts_to_sequences(text)))
print(prediction)
``` | Your can use your tokenizer and pad sequencing for a new piece of text. This is followed by model prediction. This will return the prediction as a numpy array plus the label itself.
For example:
```
new_complaint = ['Your service is not good']
seq = tokenizer.texts_to_sequences(new_complaint)
padded = pad_sequences(seq, maxlen=maxlen)
pred = model.predict(padded)
print(pred, labels[np.argmax(pred)])
``` |
37,891,954 | I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use `models.predict()`?
Do I have to prepare this text in a special way?
I tried it with
```
import keras.preprocessing.text
text = np.array(['this is just some random, stupid text'])
print(text.shape)
tk = keras.preprocessing.text.Tokenizer(
nb_words=2000,
filters=keras.preprocessing.text.base_filter(),
lower=True,
split=" ")
tk.fit_on_texts(text)
pred = tk.texts_to_sequences(text)
print(pred)
model.predict(pred)
```
But I always get
```
(1L,)
[[2, 4, 1, 6, 5, 7, 3]]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-83-42d744d811fb> in <module>()
7 print(pred)
8
----> 9 model.predict(pred)
C:\Users\bkey\Anaconda2\lib\site-packages\keras\models.pyc in predict(self, x, batch_size, verbose)
457 if self.model is None:
458 self.build()
--> 459 return self.model.predict(x, batch_size=batch_size, verbose=verbose)
460
461 def predict_on_batch(self, x):
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in predict(self, x, batch_size, verbose)
1132 x = standardize_input_data(x, self.input_names,
1133 self.internal_input_shapes,
-> 1134 check_batch_dim=False)
1135 if self.stateful:
1136 if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in standardize_input_data(data, names, shapes, check_batch_dim, exception_prefix)
79 for i in range(len(names)):
80 array = arrays[i]
---> 81 if len(array.shape) == 1:
82 array = np.expand_dims(array, 1)
83 arrays[i] = array
AttributeError: 'list' object has no attribute 'shape'
```
Do you have any recommendations as to how to make predictions with a trained model? | 2016/06/18 | [
"https://Stackoverflow.com/questions/37891954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5931447/"
] | [`model.predict()`](http://keras.io/models/model/#predict) expects the first parameter to be a numpy array. You supply a list, which does not have the `shape` attribute a numpy array has.
Otherwise your code looks fine, except that you are doing nothing with the prediction. Make sure you store it in a variable, for example like this:
```
prediction = model.predict(np.array(tk.texts_to_sequences(text)))
print(prediction)
``` | You can just "call" your model with an array of the correct shape:
```
model(np.array([[6.7, 3.3, 5.7, 2.5]]))
```
Full example:
```
from sklearn.datasets import load_iris
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import numpy as np
X, y = load_iris(return_X_y=True)
model = Sequential([
Dense(16, activation='relu'),
Dense(32, activation='relu'),
Dense(1)])
model.compile(loss='mean_absolute_error', optimizer='adam')
history = model.fit(X, y, epochs=10, verbose=0)
print(model(np.array([[6.7, 3.3, 5.7, 2.5]])))
```
```
<tf.Tensor: shape=(1, 1), dtype=float64, numpy=array([[1.92517677]])>
``` |
37,891,954 | I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use `models.predict()`?
Do I have to prepare this text in a special way?
I tried it with
```
import keras.preprocessing.text
text = np.array(['this is just some random, stupid text'])
print(text.shape)
tk = keras.preprocessing.text.Tokenizer(
nb_words=2000,
filters=keras.preprocessing.text.base_filter(),
lower=True,
split=" ")
tk.fit_on_texts(text)
pred = tk.texts_to_sequences(text)
print(pred)
model.predict(pred)
```
But I always get
```
(1L,)
[[2, 4, 1, 6, 5, 7, 3]]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-83-42d744d811fb> in <module>()
7 print(pred)
8
----> 9 model.predict(pred)
C:\Users\bkey\Anaconda2\lib\site-packages\keras\models.pyc in predict(self, x, batch_size, verbose)
457 if self.model is None:
458 self.build()
--> 459 return self.model.predict(x, batch_size=batch_size, verbose=verbose)
460
461 def predict_on_batch(self, x):
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in predict(self, x, batch_size, verbose)
1132 x = standardize_input_data(x, self.input_names,
1133 self.internal_input_shapes,
-> 1134 check_batch_dim=False)
1135 if self.stateful:
1136 if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in standardize_input_data(data, names, shapes, check_batch_dim, exception_prefix)
79 for i in range(len(names)):
80 array = arrays[i]
---> 81 if len(array.shape) == 1:
82 array = np.expand_dims(array, 1)
83 arrays[i] = array
AttributeError: 'list' object has no attribute 'shape'
```
Do you have any recommendations as to how to make predictions with a trained model? | 2016/06/18 | [
"https://Stackoverflow.com/questions/37891954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5931447/"
] | You can just "call" your model with an array of the correct shape:
```
model(np.array([[6.7, 3.3, 5.7, 2.5]]))
```
Full example:
```
from sklearn.datasets import load_iris
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import numpy as np
X, y = load_iris(return_X_y=True)
model = Sequential([
Dense(16, activation='relu'),
Dense(32, activation='relu'),
Dense(1)])
model.compile(loss='mean_absolute_error', optimizer='adam')
history = model.fit(X, y, epochs=10, verbose=0)
print(model(np.array([[6.7, 3.3, 5.7, 2.5]])))
```
```
<tf.Tensor: shape=(1, 1), dtype=float64, numpy=array([[1.92517677]])>
``` | Your can use your tokenizer and pad sequencing for a new piece of text. This is followed by model prediction. This will return the prediction as a numpy array plus the label itself.
For example:
```
new_complaint = ['Your service is not good']
seq = tokenizer.texts_to_sequences(new_complaint)
padded = pad_sequences(seq, maxlen=maxlen)
pred = model.predict(padded)
print(pred, labels[np.argmax(pred)])
``` |
37,891,954 | I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use `models.predict()`?
Do I have to prepare this text in a special way?
I tried it with
```
import keras.preprocessing.text
text = np.array(['this is just some random, stupid text'])
print(text.shape)
tk = keras.preprocessing.text.Tokenizer(
nb_words=2000,
filters=keras.preprocessing.text.base_filter(),
lower=True,
split=" ")
tk.fit_on_texts(text)
pred = tk.texts_to_sequences(text)
print(pred)
model.predict(pred)
```
But I always get
```
(1L,)
[[2, 4, 1, 6, 5, 7, 3]]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-83-42d744d811fb> in <module>()
7 print(pred)
8
----> 9 model.predict(pred)
C:\Users\bkey\Anaconda2\lib\site-packages\keras\models.pyc in predict(self, x, batch_size, verbose)
457 if self.model is None:
458 self.build()
--> 459 return self.model.predict(x, batch_size=batch_size, verbose=verbose)
460
461 def predict_on_batch(self, x):
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in predict(self, x, batch_size, verbose)
1132 x = standardize_input_data(x, self.input_names,
1133 self.internal_input_shapes,
-> 1134 check_batch_dim=False)
1135 if self.stateful:
1136 if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in standardize_input_data(data, names, shapes, check_batch_dim, exception_prefix)
79 for i in range(len(names)):
80 array = arrays[i]
---> 81 if len(array.shape) == 1:
82 array = np.expand_dims(array, 1)
83 arrays[i] = array
AttributeError: 'list' object has no attribute 'shape'
```
Do you have any recommendations as to how to make predictions with a trained model? | 2016/06/18 | [
"https://Stackoverflow.com/questions/37891954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5931447/"
] | [`model.predict()`](http://keras.io/models/model/#predict) expects the first parameter to be a numpy array. You supply a list, which does not have the `shape` attribute a numpy array has.
Otherwise your code looks fine, except that you are doing nothing with the prediction. Make sure you store it in a variable, for example like this:
```
prediction = model.predict(np.array(tk.texts_to_sequences(text)))
print(prediction)
``` | You must use the same Tokenizer you used to build your model!
Else this will give different vector to each word.
Then, I am using:
```
phrase = "not good"
tokens = myTokenizer.texts_to_matrix([phrase])
model.predict(np.array(tokens))
``` |
37,891,954 | I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use `models.predict()`?
Do I have to prepare this text in a special way?
I tried it with
```
import keras.preprocessing.text
text = np.array(['this is just some random, stupid text'])
print(text.shape)
tk = keras.preprocessing.text.Tokenizer(
nb_words=2000,
filters=keras.preprocessing.text.base_filter(),
lower=True,
split=" ")
tk.fit_on_texts(text)
pred = tk.texts_to_sequences(text)
print(pred)
model.predict(pred)
```
But I always get
```
(1L,)
[[2, 4, 1, 6, 5, 7, 3]]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-83-42d744d811fb> in <module>()
7 print(pred)
8
----> 9 model.predict(pred)
C:\Users\bkey\Anaconda2\lib\site-packages\keras\models.pyc in predict(self, x, batch_size, verbose)
457 if self.model is None:
458 self.build()
--> 459 return self.model.predict(x, batch_size=batch_size, verbose=verbose)
460
461 def predict_on_batch(self, x):
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in predict(self, x, batch_size, verbose)
1132 x = standardize_input_data(x, self.input_names,
1133 self.internal_input_shapes,
-> 1134 check_batch_dim=False)
1135 if self.stateful:
1136 if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in standardize_input_data(data, names, shapes, check_batch_dim, exception_prefix)
79 for i in range(len(names)):
80 array = arrays[i]
---> 81 if len(array.shape) == 1:
82 array = np.expand_dims(array, 1)
83 arrays[i] = array
AttributeError: 'list' object has no attribute 'shape'
```
Do you have any recommendations as to how to make predictions with a trained model? | 2016/06/18 | [
"https://Stackoverflow.com/questions/37891954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5931447/"
] | ```
model.predict_classes(<numpy_array>)
```
Sample <https://gist.github.com/alexcpn/0683bb940cae510cf84d5976c1652abd> | I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.
```
fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
recreatedModel.load_weights(fname)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
standard_scalerX.fit(X_test)
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)
``` |
37,891,954 | I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use `models.predict()`?
Do I have to prepare this text in a special way?
I tried it with
```
import keras.preprocessing.text
text = np.array(['this is just some random, stupid text'])
print(text.shape)
tk = keras.preprocessing.text.Tokenizer(
nb_words=2000,
filters=keras.preprocessing.text.base_filter(),
lower=True,
split=" ")
tk.fit_on_texts(text)
pred = tk.texts_to_sequences(text)
print(pred)
model.predict(pred)
```
But I always get
```
(1L,)
[[2, 4, 1, 6, 5, 7, 3]]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-83-42d744d811fb> in <module>()
7 print(pred)
8
----> 9 model.predict(pred)
C:\Users\bkey\Anaconda2\lib\site-packages\keras\models.pyc in predict(self, x, batch_size, verbose)
457 if self.model is None:
458 self.build()
--> 459 return self.model.predict(x, batch_size=batch_size, verbose=verbose)
460
461 def predict_on_batch(self, x):
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in predict(self, x, batch_size, verbose)
1132 x = standardize_input_data(x, self.input_names,
1133 self.internal_input_shapes,
-> 1134 check_batch_dim=False)
1135 if self.stateful:
1136 if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in standardize_input_data(data, names, shapes, check_batch_dim, exception_prefix)
79 for i in range(len(names)):
80 array = arrays[i]
---> 81 if len(array.shape) == 1:
82 array = np.expand_dims(array, 1)
83 arrays[i] = array
AttributeError: 'list' object has no attribute 'shape'
```
Do you have any recommendations as to how to make predictions with a trained model? | 2016/06/18 | [
"https://Stackoverflow.com/questions/37891954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5931447/"
] | [`model.predict()`](http://keras.io/models/model/#predict) expects the first parameter to be a numpy array. You supply a list, which does not have the `shape` attribute a numpy array has.
Otherwise your code looks fine, except that you are doing nothing with the prediction. Make sure you store it in a variable, for example like this:
```
prediction = model.predict(np.array(tk.texts_to_sequences(text)))
print(prediction)
``` | I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.
```
fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
recreatedModel.load_weights(fname)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
standard_scalerX.fit(X_test)
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)
``` |
37,891,954 | I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use `models.predict()`?
Do I have to prepare this text in a special way?
I tried it with
```
import keras.preprocessing.text
text = np.array(['this is just some random, stupid text'])
print(text.shape)
tk = keras.preprocessing.text.Tokenizer(
nb_words=2000,
filters=keras.preprocessing.text.base_filter(),
lower=True,
split=" ")
tk.fit_on_texts(text)
pred = tk.texts_to_sequences(text)
print(pred)
model.predict(pred)
```
But I always get
```
(1L,)
[[2, 4, 1, 6, 5, 7, 3]]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-83-42d744d811fb> in <module>()
7 print(pred)
8
----> 9 model.predict(pred)
C:\Users\bkey\Anaconda2\lib\site-packages\keras\models.pyc in predict(self, x, batch_size, verbose)
457 if self.model is None:
458 self.build()
--> 459 return self.model.predict(x, batch_size=batch_size, verbose=verbose)
460
461 def predict_on_batch(self, x):
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in predict(self, x, batch_size, verbose)
1132 x = standardize_input_data(x, self.input_names,
1133 self.internal_input_shapes,
-> 1134 check_batch_dim=False)
1135 if self.stateful:
1136 if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in standardize_input_data(data, names, shapes, check_batch_dim, exception_prefix)
79 for i in range(len(names)):
80 array = arrays[i]
---> 81 if len(array.shape) == 1:
82 array = np.expand_dims(array, 1)
83 arrays[i] = array
AttributeError: 'list' object has no attribute 'shape'
```
Do you have any recommendations as to how to make predictions with a trained model? | 2016/06/18 | [
"https://Stackoverflow.com/questions/37891954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5931447/"
] | You must use the same Tokenizer you used to build your model!
Else this will give different vector to each word.
Then, I am using:
```
phrase = "not good"
tokens = myTokenizer.texts_to_matrix([phrase])
model.predict(np.array(tokens))
``` | I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.
```
fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
recreatedModel.load_weights(fname)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
standard_scalerX.fit(X_test)
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)
``` |
37,891,954 | I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use `models.predict()`?
Do I have to prepare this text in a special way?
I tried it with
```
import keras.preprocessing.text
text = np.array(['this is just some random, stupid text'])
print(text.shape)
tk = keras.preprocessing.text.Tokenizer(
nb_words=2000,
filters=keras.preprocessing.text.base_filter(),
lower=True,
split=" ")
tk.fit_on_texts(text)
pred = tk.texts_to_sequences(text)
print(pred)
model.predict(pred)
```
But I always get
```
(1L,)
[[2, 4, 1, 6, 5, 7, 3]]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-83-42d744d811fb> in <module>()
7 print(pred)
8
----> 9 model.predict(pred)
C:\Users\bkey\Anaconda2\lib\site-packages\keras\models.pyc in predict(self, x, batch_size, verbose)
457 if self.model is None:
458 self.build()
--> 459 return self.model.predict(x, batch_size=batch_size, verbose=verbose)
460
461 def predict_on_batch(self, x):
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in predict(self, x, batch_size, verbose)
1132 x = standardize_input_data(x, self.input_names,
1133 self.internal_input_shapes,
-> 1134 check_batch_dim=False)
1135 if self.stateful:
1136 if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
C:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.pyc in standardize_input_data(data, names, shapes, check_batch_dim, exception_prefix)
79 for i in range(len(names)):
80 array = arrays[i]
---> 81 if len(array.shape) == 1:
82 array = np.expand_dims(array, 1)
83 arrays[i] = array
AttributeError: 'list' object has no attribute 'shape'
```
Do you have any recommendations as to how to make predictions with a trained model? | 2016/06/18 | [
"https://Stackoverflow.com/questions/37891954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5931447/"
] | ```
model.predict_classes(<numpy_array>)
```
Sample <https://gist.github.com/alexcpn/0683bb940cae510cf84d5976c1652abd> | You can just "call" your model with an array of the correct shape:
```
model(np.array([[6.7, 3.3, 5.7, 2.5]]))
```
Full example:
```
from sklearn.datasets import load_iris
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import numpy as np
X, y = load_iris(return_X_y=True)
model = Sequential([
Dense(16, activation='relu'),
Dense(32, activation='relu'),
Dense(1)])
model.compile(loss='mean_absolute_error', optimizer='adam')
history = model.fit(X, y, epochs=10, verbose=0)
print(model(np.array([[6.7, 3.3, 5.7, 2.5]])))
```
```
<tf.Tensor: shape=(1, 1), dtype=float64, numpy=array([[1.92517677]])>
``` |
46,829,684 | I am trying to adapt the example retrain script ( <https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/image_retraining/retrain.py> ) to use the Inception V4 model.
The script already supports the retraining of Inception V3 (2015) as well as different versions of Mobilenets.
What I've done so far:
Since the script uses protobuf (.pb) files and not checkpoints (.ckpt), I downloaded the `inception_v4.pb` from here: <https://deepdetect.com/models/tf/inception_v4.pb>. As far as I understand, one could also have loaded the checkpoint and used the freeze graph tool to obtain the same file.
Then, I viewed the graph in tensorboard using the tensorflow python tool `import_pb_to_tensorboard.py` which can be found in the tensorflow github repository.
From there (correct me if I am not wrong) I found that the `resized_input_tensor_name` is called `InputImage` whereas the `bottleneck_tensor_name` is `InceptionV4/Logits/Logits/MatMul` with `bottleneck_tensor_size` is `1001`.
Having this information I tried to adapt the `create_model_info(architecture)` function of the retrain script by adding:
```
elif architecture == 'inception_v4':
data_url = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz' #this won't make any difference
bottleneck_tensor_name = 'InceptionV4/Logits/Logits/MatMul'
bottleneck_tensor_size = 1001
input_width = 299
input_height = 299
input_depth = 3
resized_input_tensor_name = 'InputImage'
model_file_name = 'inception_v4.pb'
input_mean = 128
input_std = 128
```
I run the script using the following command:
```
python retrain.py --architecture=inception_v4 --bottleneck_dir=test2/bottlenecks --model_dir=inception_v4 --summaries_dir=test2/summaries/basic --output_graph=test2/graph_flowers.pb --output_labels=test2/labels_flowers.txt --image_dir=datasets/flowers/flower_photos --how_many_training_steps 100
```
and I am getting the following error:
>
> File "retrain.py", line 373, in create\_bottleneck\_file str(e)))
> RuntimeError: Error during processing file datasets/flowers/flower\_photos/tulips/4546299243\_23cd58eb43.jpg (Cannot interpret feed\_dict key as Tensor: Can not convert a Operation into a Tensor.)
>
>
> | 2017/10/19 | [
"https://Stackoverflow.com/questions/46829684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8320701/"
] | I'm working through the same thing currently.
Try to add `:0` to the end of your `bottleneck_tensor_name` and your `resized_input_tensor_name`.
If you'll notice in [`retrain.py`](https://github.com/tensorflow/hub/blob/master/examples/image_retraining/retrain.py), Google also uses this `:0` nomenclature.
My suspicion is that, for you, `InceptionV4/Logits/Logits/MatMul` is just an operation, which you're not trying to get for this script, while `InceptionV4/Logits/Logits/MatMul:0` is the first tensor instantiated from that operation, which you are trying to get for this script. | Add this modification to your script then InputImage is viewed as a Tensor:
```
resized_input_tensor_name = 'InputImage:0'
``` |
47,104,930 | As in the title, when running the appserver I get a DistributionNotFound exception for `google-cloud-storage`:
>
> File "/home/[me]/Desktop/apollo/lib/pkg\_resources/**init**.py", line 867, in resolve
> raise DistributionNotFound(req, requirers)
> DistributionNotFound: The 'google-cloud-storage' distribution was not found and is required by the application
>
>
>
Running `pip show google-cloud-storage` finds it just fine, in the site packages dir of my venv. Everything seems to be in order with `python -c "import sys; print('\n'.join(sys.path))"` too; the cloud SDK dir is in there too, if that matters.
Not sure what to do next. | 2017/11/03 | [
"https://Stackoverflow.com/questions/47104930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8883056/"
] | First off, many thanks to @Sam for the localStorage suggestion. I should have thought of that. So, in the end, all I needed to do was make use of RouterStateSnapshot from my `canActivate()` function in my AuthGuardService, and save that value to localStorage. Then I just retrieve that value to plugin in on re-authentication and re-login:
```
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
{
// Get route content id
let contentId = Object.getPropertyValueAtPath(route, 'data.contentId');
// Store last active URL prior to logout, so user can be redirected on re-login
localStorage.setItem('returnUrl', JSON.stringify(state.url));
// DO OTHER STUFF...
}
```
In my login component I just get that value to pass in...
```
login(response)
{
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password, function (results)
{
if (results.data && results.ok === true)
{
this.returnUrl = JSON.parse(localStorage.getItem('returnUrl'));
this.router.navigate([this.returnUrl || '/']);
console.log('ReturnURL Value is: ', this.returnUrl);
this.reset();
}
else
{
this.alertService.error(null, response);
this.loading = false;
}
}.bind(this));
}
``` | It is happening synchronously. However, you are logging an object pointer. By the time you look at the object in the console, it has changed because the route has changed.
I suggest using local storage to store the router snapshot. This will not have the same pointer issue that you see in the console. |
469 | I am using the Photoshop's javascript API to find the fonts in a given PSD.
Given a font name returned by the API, I want to find the actual physical font file that font name corresponds to on the disc.
This is all happening in a python program running on OSX so I guess I'm looking for one of:
* Some Photoshop javascript
* A Python function
* An OSX API that I can call from python | 2008/08/02 | [
"https://Stackoverflow.com/questions/469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147/"
] | Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef.
Cocoa doesn't have any native support, at least as of 10.5, for getting the location of a font. | open up a terminal (Applications->Utilities->Terminal) and type this in:
```
locate InsertFontHere
```
This will spit out every file that has the name you want.
Warning: there may be alot to wade through. |
469 | I am using the Photoshop's javascript API to find the fonts in a given PSD.
Given a font name returned by the API, I want to find the actual physical font file that font name corresponds to on the disc.
This is all happening in a python program running on OSX so I guess I'm looking for one of:
* Some Photoshop javascript
* A Python function
* An OSX API that I can call from python | 2008/08/02 | [
"https://Stackoverflow.com/questions/469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147/"
] | Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef.
Cocoa doesn't have any native support, at least as of 10.5, for getting the location of a font. | I haven't been able to find anything that does this directly. I think you'll have to iterate through the various font folders on the system: `/System/Library/Fonts`, `/Library/Fonts`, and there can probably be a user-level directory as well `~/Library/Fonts`. |
469 | I am using the Photoshop's javascript API to find the fonts in a given PSD.
Given a font name returned by the API, I want to find the actual physical font file that font name corresponds to on the disc.
This is all happening in a python program running on OSX so I guess I'm looking for one of:
* Some Photoshop javascript
* A Python function
* An OSX API that I can call from python | 2008/08/02 | [
"https://Stackoverflow.com/questions/469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147/"
] | Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef.
Cocoa doesn't have any native support, at least as of 10.5, for getting the location of a font. | There must be a method in Cocoa to get a list of fonts, then you would have to use the PyObjC bindings to call it..
Depending on what you need them for, you could probably just use something like the following..
```
import os
def get_font_list():
fonts = []
for font_path in ["/Library/Fonts", os.path.expanduser("~/Library/Fonts")]:
if os.path.isdir(font_path):
fonts.extend(
[os.path.join(font_path, cur_font)
for cur_font in os.listdir(font_path)
]
)
return fonts
``` |
53,624,529 | I am new to slack API and I am trying to implement interactive messages using slash command with the help of flask and python.
I am stuck at the last step where I want to update the original message instead of replacing it.
Every time I send a response on button click, the original message is replaced.
I am able to retrieve original\_message from payload but not sure how to append a user response to that message. Here is my code:
```
@application.route("/summarize", methods=['POST'])
def hello():
attach_json = {
"response_type": "in_channel",
"text": "Interested in outing?",
"attachments": [
{
"text": "Response",
"fallback": "You are unable to choose any option",
"callback_id": "confirmation",
"color": "#3AA3E3",
"attachment_type": "default",
"actions": [
{
"name": "confirm_btn",
"text": "Yes",
"type": "button",
"value": "yes"
},
{
"name": "confirm_btn",
"text": "No",
"type": "button",
"value": "No"
},
{
"name": "confirm_btn",
"text": "Can't decide",
"type": "button",
"value": "unavailable"
}
]
}
]
}
print(request.get_data())
#return Response("test", status=200)
return Response(response=json.dumps(attach_json), status=200, mimetype="application/json")
@application.route("/actions", methods=['POST'])
def actions():
statement = None
slack_req = json.loads(request.form.get('payload'))
response = '{"text": "Hi, <@' + slack_req["user"]["id"] + '>"}'
user = slack_req["user"]["name"]
user_response = slack_req["actions"][0]["value"]
orig_message = slack_req["original_message"]
if user_response == "yes":
statement = user + "chose " + user_response
print(slack_req)
return Response(response=statement, status=200, mimetype="application/json")
if __name__ == "__main__":
application.run(debug=True)
```
Will really appreciate any help! | 2018/12/05 | [
"https://Stackoverflow.com/questions/53624529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2960158/"
] | There are several options to get the modified data across. You *could* have the function return the results of the manipulated variable, or you *could* just use the `ref` keyword, but I would argue that a [`public virtual` method is an anti-pattern](http://www.gotw.ca/publications/mill18.htm) and advise you avoid that entirely.
Instead I'd suggest separating the public exposure of the class's methods from the classes ability to override its behavior:
```
public class DemoInheritance : MonoBehaviour
{
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
float damage = 10;
OnTakeDamage(damage);
}
}
public void OnTakeDamage(float damage)
{
Debug.Log("Base Damage: " + damage);
damage -= 5;
Debug.Log("New Damage: " + damage);
PostDamageResolved(damage);
}
protected virtual void PostDamageResolved(float postResolutionDamage);
}
public class DemoInheritanceChild : DemoInheritance
{
protected override void PostDamageResolved(float postResolutionDamage)
{
Debug.Log("Child Damage: " + postResolutionDamage);
}
}
```
Further, if `OnTakeDamage` is only ever called buy `Update()` in the base class, it should not be `public`:
```
public class DemoInheritance : MonoBehaviour
{
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
float damage = 10;
OnTakeDamage(damage);
}
}
private void OnTakeDamage(float damage)
{
Debug.Log("Base Damage: " + damage);
damage -= 5;
Debug.Log("New Damage: " + damage);
PostDamageResolved(damage);
}
protected virtual void PostDamageResolved(float postResolutionDamage);
}
public class DemoInheritanceChild : DemoInheritance
{
protected override void PostDamageResolved(float postResolutionDamage)
{
Debug.Log("Child Damage: " + postResolutionDamage);
}
}
``` | u not need to use ref as keyword,it will be worked like this
```
public class DemoInheritanceChild : DemoInheritance
{
public override void OnTakeDamage(float damage)
{
base.OnTakeDamage(damage);
Debug.Log("Child Damage: " + damage);
}
}
``` |
67,392,930 | Well, I'm really new to python and basically just messing around and trying to learn how to be more efficient and effective when I code. I made this piece of code to fill a list of grades with the top 150 scoring students. I stopped right at 90% since I didn't need to go lower.
I also wanted everything to be randomized (including the amount of students that got each grade). The reason I wanted to do it with "for" loops was because I needed the students grades to be high rather than just completely random. Think of this as a controlled amount of random. I also reversed each list and sorted it so that the higher grades can have more students. I got the code working but I have no idea how to make it smaller.
Is there any way that I can do what this code does, but less code? Is there anyway I can shift through the variables so that I can use just 1 "for" loop? Instead of assigning 20 variables to the list.
The code should output a list from 1-150 of the highest scoring students.
```
import random
#lists for the three groups
randomlist = []
testlist = []
testlist2 = []
#Both "for" loops here get 10 numbers. Each of them randomized between 0 -> (any number of choice)
#These are then put into a list, sorted, reversed to be used to randomize the number of students getting each grade
for i in range(0,10):
z = random.randint(0, 25)
testlist.append(z)
testlist.sort(reverse = True)
for i in range(0,10):
z = random.randint(0, 30)
testlist2.append(z)
testlist2.sort(reverse = True)
#Each "y" is mapped to one of the numbers in the list
y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,= testlist
y11,y12,y13,y14,y15,y16,y17,y18,y19,y20 = testlist2
#randomizes an amount of students scoring a grade between 0.5 of each number
for i in range(0,y1):
n = round(random.uniform(99.5, 100), 1)
randomlist.append(n)
for i in range(0,y2):
n = round(random.uniform(99.0, 99.5), 1)
randomlist.append(n)
for i in range(0,y3):
n = round(random.uniform(98.5, 99.0), 1)
randomlist.append(n)
for i in range(0,y4):
n = round(random.uniform(98.0, 98.5), 1)
randomlist.append(n)
for i in range(0,y5):
n = round(random.uniform(97.5, 98.0), 1)
randomlist.append(n)
for i in range(0,y6):
n = round(random.uniform(97.0, 97.5), 1)
randomlist.append(n)
for i in range(0,y7):
n = round(random.uniform(96.5, 97.0), 1)
randomlist.append(n)
for i in range(0,y8):
n = round(random.uniform(96.0, 96.5), 1)
randomlist.append(n)
for i in range(0,y9):
n = round(random.uniform(95.5, 96.0), 1)
randomlist.append(n)
for i in range(0,y10):
n = round(random.uniform(95.0, 95.5), 1)
randomlist.append(n)
for i in range(0,y11):
n = round(random.uniform(94.5, 95.0), 1)
randomlist.append(n)
for i in range(0,y12):
n = round(random.uniform(94.0, 94.5), 1)
randomlist.append(n)
for i in range(0,y13):
n = round(random.uniform(93.5, 94.0), 1)
randomlist.append(n)
for i in range(0,y14):
n = round(random.uniform(93.0, 93.5), 1)
randomlist.append(n)
for i in range(0,y15):
n = round(random.uniform(92.5, 93.0), 1)
randomlist.append(n)
for i in range(0,y16):
n = round(random.uniform(92.0, 92.5), 1)
randomlist.append(n)
for i in range(0,y17):
n = round(random.uniform(91.5, 92.0), 1)
randomlist.append(n)
for i in range(0,y18):
n = round(random.uniform(91.0, 91.5), 1)
randomlist.append(n)
for i in range(0,y19):
n = round(random.uniform(90.5, 91.0), 1)
randomlist.append(n)
for i in range(0,y20):
n = round(random.uniform(90.0, 90.5), 1)
randomlist.append(n)
randomlist.sort(reverse = True)
print(randomlist[0:150]) #Grabs the first 150 from the sorted reversed list
``` | 2021/05/04 | [
"https://Stackoverflow.com/questions/67392930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15309845/"
] | Consider the following code :
```
#lists for the two groups
randomlist = []
testlist = [] # no need to define two separate test lists
for i in range(0,10):
z = random.randint(0, 25)
testlist.append(z)
for i in range(0,10):
z = random.randint(0, 30)
testlist.append(z)
testlist.sort(reverse = True)
upper_bound = 100 # your upper bound starts at 100 and decreases by 0.5 after each y variable is dealt with
for y in testlist: # avoids defining all of the y1, y2, y3... variables
for i in range(0,y):
n = round(random.uniform(upper_bound - 0.5, upper_bound), 1)
randomlist.append(n)
upper_bound -= 0.5
randomlist.sort(reverse = True)
print(randomlist[0:150]) #Grabs the first 150 from the sorted reversed list
```
You could further "compactify" the code that populates `testlist` using list comprehensions :
```
testlist = [random.randint(0, 25) for i in range(0, 10)] + [random.randint(0, 30) for i in range(0, 10)]
testlist.sort(reverse = True)
```
The `+` sign between the two lists **concatenates** them into a single list. | Python offers a syntax called [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). It allows a shorter syntax for looping trough list and other iterables. Instead of
```py
my_list = []
for i in range(10):
my_list.append(i)
```
you can just write
```py
my_list = [i for i in range(10)]
```
There are also some built-in functions for working with iterables like [sorted](https://docs.python.org/3/library/functions.html#sorted) that returns a modified (sorted) list you can work with. Instead of
```py
my_list.sort(reverse=True)
print(my_list)
```
it is sometimes better to write
```py
print(sorted(my_list))
```
These ideas inspired me to push list comprehension to its limits by rewriting your code into a one-liner (but for a better representation it's spread over 11 lines).
```py
print(
sorted([ # sort the resulting list
round(random.uniform(i/10-0.5, i/10), 1) # generate the grades,
for y, i2 in zip( # zip() turns our to iterable into an iterable of two-tuples
sorted([random.randint(0, 25) # generate the 'testlist'
for _ in range(10)], reverse=True) # '_' is used for variables we don't care about
+ sorted([random.randint(0, 30)
for _ in range(10)], reverse=True),
range(1000, 900, -5), # range() only allows integer steps, so we multiply everything by ten
) for i in (i2, ) * y # second loop takes arguments from first loop
], reverse=True)[:150])
```
This code is neither easy to read nor to understand and debugging is a disaster. But I hope it demonstrates how compact code can be written with list comprehension. |
60,155,062 | **The problem**
I start a flask app, which works fine when I use "run" or "debug." However, I got the error when use "profile," here is the log message
```
In folder C:/Users/Myname/PycharmProjects/ProjectName
"C:\Users\Myname\Anaconda3\envs\ProjectName\python.exe" "C:\Program Files\JetBrains\PyCharm
Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py" 127.0.0.1 12055 -m flask run
Starting cProfile profiler
Traceback (most recent call last):
Snapshot saved to C:\Users\Myname/.PyCharm2019.2/system\snapshots\ProjectName1.pstat
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 173, in <module>
profiler.run(file)
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 89, in run
execfile(file, globals, globals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\prof_util.py", line 30, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:\Users\Myname\Anaconda3\envs\ProjectName\lib\site-packages\flask\__init__.py", line 19, in <module>
from . import json
ImportError: attempted relative import with no known parent package
```
**What I have tried**
I google it and found that it is an old problem.
[Can't profile module using relative imports](https://youtrack.jetbrains.com/issue/PY-28509?_ga=2.61806444.1370666243.1581348130-2098848986.1573709040)
[Pycharm profile is not working](https://intellij-support.jetbrains.com/hc/en-us/community/posts/360003937020-Pcharm-profile-is-not-working)
**How to reproduce it**
If you would like to reproduce it, you can create a flask app using pycharm, and then click "profile."
The default code for flask app is as follows. But I don't think it matters.
```
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
```
The error message can be different due to the change of the flask version or Pycharm version, but the reason is the same: `File "xxx\lib\site-packages\flask\__init__.py", line 19, in <module>` use relative import and cause the ImportError
**My question**
My question is, is there a way to make it work? Any hacks or tricks are also appreciated. I just want to use the profile now. Thank you | 2020/02/10 | [
"https://Stackoverflow.com/questions/60155062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9068344/"
] | Apparently this is a long-standing issue with PyCharm's profiler, it does not run *packages* correctly resulting in sys.path being wonky and relative imports failing: <https://youtrack.jetbrains.com/issue/PY-28509>
I guess an option would be to make your own "launcher script" simply copying [what `flask.__main__` does](https://github.com/pallets/flask/blob/master/src/flask/__main__.py).
Though things *might* also work out if you run `-m flask.cli` instead of just `-m flask` (I don't know, I didn't test it): it does the same thing but does not invoke a `__main__` file so it could behave better. | [New solution]
--------------
Thanks to @Masklinn, use `-m flask.cli` instread of `-m flask` could solve this problem. However, the configuration in `pycharm flask` use `-m flask` by default and I cannot find out a way to modify it. Therefore, I suggest to use `pycharm python`. The `script path` should be set to your `FLASK_APP`, and add `-m flask.cli` in `addtional options`.
[Obsolete solution]
-------------------
One solution is that directly modify the `__init__.py` to make it work. For example, change
```
from . import json
from .app import Flask
```
to
```
from flask import json
from flask.app import Flask
``` |
69,924,998 | So I am going over a tutorial in python where I need to find x and y by given hypotenuse = 40 and the angle = 45 deg. Can anyone explain how to find the x and y?
[![triangle](https://i.stack.imgur.com/iUOD3.png)](https://i.stack.imgur.com/iUOD3.png)
Here is the code in python. Look at the movePlayer function. Finding the new x and y is done differently. The angle is first subtracted from 180 and then divided by 2 which doesn't make sense yet it work.
```
import pygame, math
pygame.init()
def movePlayer(direction, radius, absRot):
yChange = 5
# how many degrees to move in either side
deltaTheta = int(90/(radius / yChange))
if direction == 'left':
deltaTheta *= -1
# convert degrees to radians
finalRot = (absRot + deltaTheta) * math.pi / 180
hypotenuse = (radius * math.sin(finalRot) / (math.sin((math.pi - finalRot) / 2)))
# why these work
newX = hypotenuse * math.cos(math.pi/2-(math.pi - finalRot)/2)
newY = hypotenuse * math.sin(math.pi/2-(math.pi - finalRot)/2)
# these don't work
#newX = hypotenuse * math.cos(math.pi/2-finalRot)
#newY = hypotenuse * math.sin(math.pi/2-finalRot)
return newX, newY,absRot + deltaTheta
WIDTH = 900
HEIGHT = 700
SCREEN_SIZE = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(SCREEN_SIZE)
player = pygame.Surface((64,64))
playerStart = player
currentRotation = 0
ball = pygame.Surface((32,32))
ball.fill('red')
playerX = WIDTH // 2
playerY = 530
playerXOriginal = playerX
playerYOriginal = playerY
ballX = WIDTH // 2 - ball.get_rect().width // 2
ballY = 450 - ball.get_rect().height // 2
radius = playerY - ballY
FPS = 30
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
pressedKeys = pygame.key.get_pressed()
if pressedKeys[pygame.K_LEFT]:
changeX, changeY, currentRotation = movePlayer('left', radius, currentRotation)
playerX = playerXOriginal + changeX
playerY = playerYOriginal - changeY
print('left')
elif pressedKeys[pygame.K_RIGHT]:
changeX, changeY, currentRotation = movePlayer('right', radius, currentRotation)
playerX = playerXOriginal + changeX
playerY = playerYOriginal - changeY
print('right')
screen.fill('white')
screen.blit(ball, (ballX,ballY))
screen.blit(player, (playerX - player.get_rect().width //2,playerY - player.get_rect().height // 2))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
``` | 2021/11/11 | [
"https://Stackoverflow.com/questions/69924998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3452362/"
] | `Person().walk` is a function - `(Int) -> Void`, and `10` is an `Int`. What `<*>` does is *function application* - it applies the left operand to the function that is the right operand. In other words, it calls the function on its right with the thing on its left as an argument. It's just that both the function and its argument can be optional (note the `?`s in the signature). This is kind of like Haskell's `<*>`, but specifically for `Maybe` (`Optional`'s Haskell counterpart).
If you remove all the optional-handling:
```
public func <*> <A, B>(f : ((A) -> B), a : A) -> B {
return f(a)
}
```
Yep, that's what it does (plus handling the optionals)!
The optional handling isn't that hard to understand either. `$0 <^> a` just means `a.map($0)`. Both `flatMap`. These are built in Swift functions. If you don't understand how they work, read [this](https://stackoverflow.com/questions/29556656/map-and-flatmap-difference-in-optional-unwrapping-in-swift-1-2). Ultimately what it does is if either `f` or `a` is nil, `<*>` returns nil too.
Now you might be wondering why we need this function at all. Well, making "apply this function" itself a function means that we can pass it around to other functions, compose it with other functions!
However, I don't think this works in Swift as well as it does in Haskell. In Swift, the compiler needs to be able to infer every type parameter to a known type, which can make many things that you can easily do in Haskell, difficult and cumbersome. | <\*> is an operator defined in this library.
<A, B> means the operator definition has two types as parameters, referred to as A and B.
The operator has two arguments f and a for the left hand and right hand side. In your example, f is Person().walk, and a is 10. And it returns an optional B, where B is the type that Person.walk would return if you call it.
f is an optional function taking A as a parameter and returning B. In your case, walk takes an Int parameter and returns Void, so A is Int and B is Void. And the right hand side was supposed to be A?, which is fine since 10 is of type Int.
And then it calls another operator that you need to examine. Important is: That operator takes any function on the left hand side that has one argument of type A, and a value on the right hand side with type A?, and returns whatever the function would have returned. |
62,052,268 | I have a lot of words in a text file, each word is not separated by any delimiter, but we can tell the different words because each individual word begins with a capital letter. I want to extract all the words and store them in a list: My python script:
```
words = ''
with open("words.txt",'r') as mess:
for l in mess.read():
if l.isupper():
words += ','+l
else:
words += l
words = [word.strip() for word in words.split(',') if word]
print(words)
```
Output:
```
['Apple', 'Banana', 'Grape', 'Kiwi', 'Raspberry', 'Pineapple', 'Orange', 'Watermelon', 'Mango', 'Leechee', 'Coconut', 'Grapefruit', 'Blueberry', 'Pear', 'Passionfruit']
```
Inside words.txt *(note that there are newlines, and this is only an example of the actual text)*:
```
AppleBananaGrapeKiwiRaspberry
PineappleOrangeWatermelonMangoLeecheeCoconutGrapefruit
BlueberryPear
Passionfruit
```
My code works fine, but I'm wondering if there is a special method python can split a text without a delimiter, only by the capitals.
If not, can someone show me more practical way? | 2020/05/27 | [
"https://Stackoverflow.com/questions/62052268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13552470/"
] | Use regular expressions:
```
import re
test = 'HelloWorldExample'
r_capital = re.compile(r'[A-Z][a-z]*')
r_capital.findall(test) # ['Hello', 'World', 'Example']
```
Compiling the regular expression will speed up execution when you use it multiple times, i.e. when iterating over a lot of lines of input. | With the new f-strings since python 3.6 you could use
```py
words = "".join([f" {s}" if s.isupper() else s for s in yorufile.read() if s.strip()]).split(" ")[1:]
```
This is the final version of my attempt but as I go on it becomes uglier and uglier.
(sorry for messing around with deleting posts and making tons of mistakes) |
72,481,720 | I have a pandas dataframe, one of the columns has a series in there. The structure is as follows:
```
Date Col1
2022-01-02 'Amt_Mean 2022.0\nAmt_Med 5.0\nAmt_Std 877.0\ndtype: float64'
2022-01-03 'Amt_Mean 2025.0\nAmt_Med 75.0\nAmt_Std 27.0\ndtype: float64'
```
I want to reshape this such that I get the following output
```
Date Amt_Mean Amt_Med Amt_Std
2022-01-02 2022.0 5.0 877.0
2022-01-03 2025.0 75.0 27.0
```
How can I achieve this? I tried `df['Col1'][0][1]` which gives me the first amount and I can potentially for loop it, but seems there should be a more easy (pythonic) way of doing this.
Thanks! | 2022/06/02 | [
"https://Stackoverflow.com/questions/72481720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6075349/"
] | Some string processing to convert each string into a dict, convert those to a dataframe, and concatenate that with the original:
```
new_df = pd.DataFrame([dict(re.split(r'\s+', y) for y in x.split('\n')[:-1]) for x in df['Col1']])
df = pd.concat([df.drop('Col1', axis=1), new_df], axis=1)
```
Output:
```
>>> df
Date Amt_Mean Amt_Med Amt_Std
0 2022-01-02 2022.0 5.0 877.0
1 2022-01-03 2025.0 75.0 27.0
``` | Assuming you have `pd.Series` objects, I would concatenate them using a chained `pd.concat`:
```
>>> pd.concat([df.Date, pd.concat([x for x in df.Col1], axis=1).T], axis=1)
```
```
Date Amt_Mean Amt_Med Amt_Std
0 2022-01-02 2022 5 877
1 2022-01-03 2025 75 27
```
This assumes your data is as follows:
```
df = pd.DataFrame([{'Date':'2022-01-02',
'Col1': pd.Series({'Amt_Mean': 2022, "Amt_Med": 5, "Amt_Std":877})},
{'Date':'2022-01-03',
'Col1': pd.Series({'Amt_Mean': 2025, "Amt_Med": 75, "Amt_Std":27})
}])
``` |
33,858,968 | For my python program I am asked to calculate resistor values that the user inputs. In the program I am asked to demonstrate Data handling, Loops, Lists and Validation.
I have 7 resistor values to be inputted into the program. For each resistor input I have created a loop like so:
```
#Loop for Resistor 2:
while True :
try:
R2 = float(input( 'Resistor Value R2: ' ))
except ValueError:
print( 'Sorry, Invalid Input! Try Inputing A Number' )
continue
if R2 < 0 :
print( 'Sorry, Invalid Input! Try A Positive Number ' )
continue
else :
break
```
As I have 7 resistors I have 7 of these loops typed out for the program. This works completely fine. However I would like to have these all in a list. So for example, instead of writing this loop out 7 different times for 7 resistors, is to create a list and have this written once and repeat for all 7 inputs.
would anybody know how I could do this? I am quite new to python and quite confused. | 2015/11/22 | [
"https://Stackoverflow.com/questions/33858968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5592149/"
] | Figured it out
```
$html = file_get_contents('result.html');
$dom = new DOMDocument;
$dom->loadHTML($html);
$tr = $dom->getElementsByTagName('tr');
foreach ($tr as $row){
$td = $row->getElementsByTagName('td');
$td1 = $td->item(1);
$td2 = $td->item(2);
$title = $td1->childNodes->item(0)->textContent;
$firstURL = $td1->getElementsByTagName('a')->item(0)->getAttribute('href');
$type = $td2->childNodes->item(0)->textContent;
$imageURL = $td2->getElementsByTagName('img')->item(0)->getAttribute('src');
}
``` | I have used following class.
<http://sourceforge.net/projects/simplehtmldom/>
This is very simple and easy to use class.
You can use
```
$html->find('#RosterReport > tbody', 0);
```
to find specific table
```
$html->find('tr')
$html->find('td')
```
to find table rows or columns
Note $html is variable have full html dom content. |
72,594,700 | I would like to sort one list based on another list.
Example: below I would like to sort `list_sec` based on `key` in this list and the order would be from `list_main`.
```
list_main = [3, 33, 2]
list_sec = [{'key': 2, 'rocket': 'mark11'}, {'key': 332, 'rocket': 'mark23'}, {'key': 3, 'rocket': 'mark1'} ]
```
Output would be as below. (explanation: first element in `list_main` is 3, so `key` : 3 should come to index = 0, second value is 33 but this key is missing in `list_sec` so will discard this. third key is 2, so this will come next.
```
output = [{'key': 3, 'rocket': 'mark1'}, {'key': 2, 'rocket': 'mark11'}]
```
I have read couple of answers on similar lines:
[Python, sort a list by another list](https://stackoverflow.com/questions/23069055/python-sort-a-list-by-another-list) ,
[Python 3.x -- sort one list based on another list and then return both lists sorted](https://stackoverflow.com/questions/61024568/python-3-x-sort-one-list-based-on-another-list-and-then-return-both-lists-sor)
But stuck without attempt. Any way this can be done. | 2022/06/12 | [
"https://Stackoverflow.com/questions/72594700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17925252/"
] | ```r
library(nycflights13)
library(tidyverse)
f <- flights %>%
select(hour, dep_delay, arr_delay) %>%
filter(hour > 4) %>%
pivot_longer(!hour)
```
Replicate the calculation that `stat_summary()` does internally, applying the `mean_sdl` function to each hour/name combination:
```r
fs <- (f
## partition data
%>% group_by(hour, name)
## convert value to a list-column
%>% nest()
## summarise each entry
%>% mutate(across(data, map, \(x) mean_sdl(x, mult = 0.2)))
## collapse back to a vector
%>% unnest(cols = c(data))
)
```
Now create the plot:
```r
ggplot(fs) +
aes(hour, y = y, ymin = ymin, ymax = ymax, color = name) +
geom_point(size = 3) +
geom_line(size = 1.1) +
geom_ribbon(alpha = 0.3) +
theme_bw()
```
The order of the elements affects the colours of the lines — i.e. if `geom_ribbon` is last, it covers the lines with one or two layers of "black/alpha=0.3" (depending on whether the lines are overlapped by one or both confidence regions). I might recommend drawing the lines and points *after* you draw the ribbon, so that the colours are closer to the originally specified values/more predictable (but there's no need to do that if you like the way your plot looks). | You need to add `name` as a grouping variable. The natural way to do this is to map it to the `color` aesthetic:
```r
flights %>%
select(hour, dep_delay, arr_delay) %>%
filter(hour > 4) %>%
pivot_longer(!hour) %>%
group_by(hour, name) %>%
summarise(mean = mean(value, na.rm = T),
high = mean(value, na.rm = T) + 0.2 * sd(value, na.rm= T),
low = mean(value, na.rm = T) - 0.2 * sd(value, na.rm= T)) %>%
ggplot() +
geom_point(aes(hour, mean, color = name), size = 3) +
geom_line(aes(hour, mean, color = name), size = 1.1) +
geom_ribbon(aes(x = hour, ymax = high, ymin = low, color = name), alpha = 0.3) +
theme_bw()
```
[![enter image description here](https://i.stack.imgur.com/Izk62.png)](https://i.stack.imgur.com/Izk62.png) |
9,212,548 | I want to implement a hash table in python. On the table a class object will be associated with the key value. The problem is I want to use the key value to find the index of the class and update it (which of course is not a problem). But what can I do if I want to sort the table using a particular value of the class.
For example, let us consider, we have three value: document\_id, score and rank. There is a class "document" which consists of "score" and "rank". "document\_id" will be the key of the table.
I want to update the "score" of various entries of the table, using the key: "document\_id". But when updating of the scores are done, I want to sort the list/table using the score and assign rank value to the "rank" variable based on updated score.
Can someone kindly give me some guideline about how can I proceed? Or maybe I should simply make it a list?
The maximum number of item of the table might be upto 25000-30000.
Thanks. | 2012/02/09 | [
"https://Stackoverflow.com/questions/9212548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | Python's dict is already a hash table.
```
doc_hash = {}
doc_hash[doc.id] = doc
```
To assign rank:
```
docs = sorted(doc_hash.itervalues(), key=operator.attrgetter('score'), reverse=True)
for i, doc in enumerate(docs):
doc.rank = i
``` | Something like this?
```
sorted_keys = sorted(d.keys(), key=lambda element: element['score'])
for i in range(len(sorted_keys)):
d[sorted_keys[i]]['rank'] = i
```
assigns to each element in `d` (elements are implied to be dictionaries as well) a rank based on its score. |
9,212,548 | I want to implement a hash table in python. On the table a class object will be associated with the key value. The problem is I want to use the key value to find the index of the class and update it (which of course is not a problem). But what can I do if I want to sort the table using a particular value of the class.
For example, let us consider, we have three value: document\_id, score and rank. There is a class "document" which consists of "score" and "rank". "document\_id" will be the key of the table.
I want to update the "score" of various entries of the table, using the key: "document\_id". But when updating of the scores are done, I want to sort the list/table using the score and assign rank value to the "rank" variable based on updated score.
Can someone kindly give me some guideline about how can I proceed? Or maybe I should simply make it a list?
The maximum number of item of the table might be upto 25000-30000.
Thanks. | 2012/02/09 | [
"https://Stackoverflow.com/questions/9212548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | Python's dict is already a hash table.
```
doc_hash = {}
doc_hash[doc.id] = doc
```
To assign rank:
```
docs = sorted(doc_hash.itervalues(), key=operator.attrgetter('score'), reverse=True)
for i, doc in enumerate(docs):
doc.rank = i
``` | Why not use a `OrderedDict`?
```
>>> from collections import OrderedDict
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
``` |
9,212,548 | I want to implement a hash table in python. On the table a class object will be associated with the key value. The problem is I want to use the key value to find the index of the class and update it (which of course is not a problem). But what can I do if I want to sort the table using a particular value of the class.
For example, let us consider, we have three value: document\_id, score and rank. There is a class "document" which consists of "score" and "rank". "document\_id" will be the key of the table.
I want to update the "score" of various entries of the table, using the key: "document\_id". But when updating of the scores are done, I want to sort the list/table using the score and assign rank value to the "rank" variable based on updated score.
Can someone kindly give me some guideline about how can I proceed? Or maybe I should simply make it a list?
The maximum number of item of the table might be upto 25000-30000.
Thanks. | 2012/02/09 | [
"https://Stackoverflow.com/questions/9212548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | Why not use a `OrderedDict`?
```
>>> from collections import OrderedDict
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
``` | Something like this?
```
sorted_keys = sorted(d.keys(), key=lambda element: element['score'])
for i in range(len(sorted_keys)):
d[sorted_keys[i]]['rank'] = i
```
assigns to each element in `d` (elements are implied to be dictionaries as well) a rank based on its score. |
65,165,864 | Edit:
See answer but "-" in MySQL table names causes problems.
I tried this: <https://stackoverflow.com/a/37730334/14767913>
My code:
```
import pandas as pd
table_name = 'calcium-foods'
df = pd.read_sql('SELECT * FROM calcium-foods', con=engine )
```
The table is there:
[imgfromme](https://i.stack.imgur.com/IVzZE.png)
I connected properly and can get a list of tables using `engine.table_names()`
This did not work either;
```
import pandas as pd
table_name = 'calcium-foods'
sql = "SELECT * from " + table_name
print(sql)
df = pd.read_sql_query(sql, engine)
```
I am working in Jupyter Notebooks, Python 3.7 or 3.8,
and here is the Traceback
```
--------------------------------------------------
ProgrammingError Traceback (most recent call last)
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/sqlalchemy/engine/base.py in _execute_context(self, dialect, constructor, statement, parameters, *args)
1266 self.dialect.do_execute_no_params(
-> 1267 cursor, statement, context
1268 )
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/sqlalchemy/engine/default.py in do_execute_no_params(self, cursor, statement, context)
595 def do_execute_no_params(self, cursor, statement, context=None):
--> 596 cursor.execute(statement)
597
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/cursors.py in execute(self, query, args)
162
--> 163 result = self._query(query)
164 self._executed = query
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/cursors.py in _query(self, q)
320 self._clear_result()
--> 321 conn.query(q)
322 self._do_get_result()
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/connections.py in query(self, sql, unbuffered)
504 self._execute_command(COMMAND.COM_QUERY, sql)
--> 505 self._affected_rows = self._read_query_result(unbuffered=unbuffered)
506 return self._affected_rows
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/connections.py in _read_query_result(self, unbuffered)
723 result = MySQLResult(self)
--> 724 result.read()
725 self._result = result
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/connections.py in read(self)
1068 try:
-> 1069 first_packet = self.connection._read_packet()
1070
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/connections.py in _read_packet(self, packet_type)
675 self._result.unbuffered_active = False
--> 676 packet.raise_for_error()
677 return packet
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/protocol.py in raise_for_error(self)
222 if DEBUG: print("errno =", errno)
--> 223 err.raise_mysql_exception(self._data)
224
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/err.py in raise_mysql_exception(data)
106 errorclass = InternalError if errno < 1000 else OperationalError
--> 107 raise errorclass(errno, errval)
ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-foods' at line 1")
The above exception was the direct cause of the following exception:
ProgrammingError Traceback (most recent call last)
<ipython-input-16-7e7208d94a8a> in <module>
3 sql = "SELECT * from " + table_name
4 print(sql)
----> 5 df = pd.read_sql_query(sql, engine)
6 #conn = engine.connect()
7 #table_name = 'calcium-foods'
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pandas/io/sql.py in read_sql_query(sql, con, index_col, coerce_float, params, parse_dates, chunksize)
381 coerce_float=coerce_float,
382 parse_dates=parse_dates,
--> 383 chunksize=chunksize,
384 )
385
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pandas/io/sql.py in read_query(self, sql, index_col, coerce_float, parse_dates, params, chunksize)
1293 args = _convert_params(sql, params)
1294
-> 1295 result = self.execute(*args)
1296 columns = result.keys()
1297
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
1160 """Simple passthrough to SQLAlchemy connectable"""
1161 return self.connectable.execution_options(no_parameters=True).execute(
-> 1162 *args, **kwargs
1163 )
1164
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/sqlalchemy/engine/base.py in execute(self, statement, *multiparams, **params)
2233
2234 connection = self._contextual_connect(close_with_result=True)
-> 2235 return connection.execute(statement, *multiparams, **params)
2236
2237 def scalar(self, statement, *multiparams, **params):
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/sqlalchemy/engine/base.py in execute(self, object_, *multiparams, **params)
1001 """
1002 if isinstance(object_, util.string_types[0]):
-> 1003 return self._execute_text(object_, multiparams, params)
1004 try:
1005 meth = object_._execute_on_connection
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/sqlalchemy/engine/base.py in _execute_text(self, statement, multiparams, params)
1176 parameters,
1177 statement,
-> 1178 parameters,
1179 )
1180 if self._has_events or self.engine._has_events:
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/sqlalchemy/engine/base.py in _execute_context(self, dialect, constructor, statement, parameters, *args)
1315 except BaseException as e:
1316 self._handle_dbapi_exception(
-> 1317 e, statement, parameters, cursor, context
1318 )
1319
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/sqlalchemy/engine/base.py in _handle_dbapi_exception(self, e, statement, parameters, cursor, context)
1509 elif should_wrap:
1510 util.raise_(
-> 1511 sqlalchemy_exception, with_traceback=exc_info[2], from_=e
1512 )
1513 else:
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/sqlalchemy/util/compat.py in raise_(***failed resolving arguments***)
180
181 try:
--> 182 raise exception
183 finally:
184 # credit to
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/sqlalchemy/engine/base.py in _execute_context(self, dialect, constructor, statement, parameters, *args)
1265 if not evt_handled:
1266 self.dialect.do_execute_no_params(
-> 1267 cursor, statement, context
1268 )
1269 else:
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/sqlalchemy/engine/default.py in do_execute_no_params(self, cursor, statement, context)
594
595 def do_execute_no_params(self, cursor, statement, context=None):
--> 596 cursor.execute(statement)
597
598 def is_disconnect(self, e, connection, cursor):
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/cursors.py in execute(self, query, args)
161 query = self.mogrify(query, args)
162
--> 163 result = self._query(query)
164 self._executed = query
165 return result
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/cursors.py in _query(self, q)
319 self._last_executed = q
320 self._clear_result()
--> 321 conn.query(q)
322 self._do_get_result()
323 return self.rowcount
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/connections.py in query(self, sql, unbuffered)
503 sql = sql.encode(self.encoding, 'surrogateescape')
504 self._execute_command(COMMAND.COM_QUERY, sql)
--> 505 self._affected_rows = self._read_query_result(unbuffered=unbuffered)
506 return self._affected_rows
507
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/connections.py in _read_query_result(self, unbuffered)
722 else:
723 result = MySQLResult(self)
--> 724 result.read()
725 self._result = result
726 if result.server_status is not None:
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/connections.py in read(self)
1067 def read(self):
1068 try:
-> 1069 first_packet = self.connection._read_packet()
1070
1071 if first_packet.is_ok_packet():
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/connections.py in _read_packet(self, packet_type)
674 if self._result is not None and self._result.unbuffered_active is True:
675 self._result.unbuffered_active = False
--> 676 packet.raise_for_error()
677 return packet
678
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/protocol.py in raise_for_error(self)
221 errno = self.read_uint16()
222 if DEBUG: print("errno =", errno)
--> 223 err.raise_mysql_exception(self._data)
224
225 def dump(self):
~/anaconda3/envs/gamechangers/lib/python3.7/site-packages/pymysql/err.py in raise_mysql_exception(data)
105 if errorclass is None:
106 errorclass = InternalError if errno < 1000 else OperationalError
--> 107 raise errorclass(errno, errval)
ProgrammingError: (pymysql.err.ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-foods' at line 1")
[SQL: SELECT * from calcium-foods]
(Background on this error at: http://sqlalche.me/e/13/f405)
```
As an aside, when I click on the SQL Alchemy error URL, it seems like they all take me to the same page rather than error-specific. Is this normal? | 2020/12/06 | [
"https://Stackoverflow.com/questions/65165864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14767913/"
] | It feels like your approach is correct - it is the role of the Authorization Server (AS) to deal with SAML login integration for you. Only configuration changes should be needed, though of course you need to use an AS that supports SAML integration.
Your UIs and APIs will not need to know anything about SAML and will just use OAuth tokens. There should be zero code changes needed.
Most companies use an off the shelf AS - eg from a low cost cloud provider. My [Federated Logins Blog Post](https://authguidance.com/2020/05/23/federation-logins/) summarises the process of integrating an IDP. The walkthrough uses AWS Cognito as the AS - and the IDP could be a SAML one. | I maintain a microservice that sounds like it could help you - <https://github.com/enterprise-oss/osso>
Osso handles SAML configuration against a handful of IDP providers, normalizes payloads, and makes user resources available to you in an oauth 2.0 authorization code grant flow.
Osso mainly acts as an authentication server though - we don't currently have a way for your API gateway to verify an access token is (still) valid, but that would be pretty trivial for us to add, we'd be happy to consider it. |
70,395,396 | My PC is 64 bit and python version is 3.7.9. I installed tensorflow as following. Does anyone know how to solve it? Let me know if further information is needed.
[![enter image description here](https://i.stack.imgur.com/L1tzz.png)](https://i.stack.imgur.com/L1tzz.png)
**Edit:**
I also tried anaconda as follow:
<https://www.tutorialspoint.com/tensorflow/tensorflow_installation.htm>
But the problem is that in anaconda prompt, I can import tensorflow. I use python in visual studio 2017. When I open python file in VS, it seems different with anaconda prompt. Do you know how to make it also work in VS? | 2021/12/17 | [
"https://Stackoverflow.com/questions/70395396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6703592/"
] | The version of Python your using is too new for the version of TensorFlow your using.
If you go here: <https://pypi.org/project/tensorflow/1.13.1/>, and look on the left hand side and scroll down to "Programming Language", you will see the latest python version on that list is Python 3.6.
That is the cause of error your getting. You can either:
* Switch to Python 3.6 or
* Use TensorFlow 1.14.0 or above which supports Python 3.7
Also make sure your using the 64-bit version of Python. TensorFlow will not install if you have the 32-bit version of Python installed. | Could you try:
pip install --upgrade tensorflow |
67,734,105 | It seems that many people struggle with this problem, but I can't find any answer that works.
I think that I am doing everything right but it still doesn't work.
I've built my own package and installed it in my conda environment.
When I do `conda list`, it turns up in the list, at the end (I've called it zzpackagerps):
```
...
zlib 1.2.11 h62dcd97_1010 conda-forge
zstd 1.4.9 h6255e5f_0 conda-forge
zzpackagerps 0.0.1 dev_0 <develop>
```
Now when I run python, in this environment (py39), and try to import the package, I get the infamous ModuleNotFoundError:
```
(py39) s:\Sources>python
Python 3.9.4 | packaged by conda-forge | (default, May 10 2021, 22:10:34) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import zzpackagerps
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'zzpackagerps'
>>>
```
How is this possible? Or, more importantly, how do I get this to work?
(by the way: running on Windows) | 2021/05/28 | [
"https://Stackoverflow.com/questions/67734105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266967/"
] | One possible issue is that the package name may not be identical to the module name. If you locate the `site-packages` where the package is installed, you can try looking at the folder structure and where there are `__init__.py` files defined. | Cannot comment so asking here.
Did you install the package as root? If yes, execute the following:
```
sudo chmod -R a+rX /home/deeplearning/anaconda3/envs/
```
If not, then it can be a Potential Path Problem:
Your python command might refer to a different python than the python which is in your active conda environment folder. Check this by running in the terminal `which conda` and `which python`.
Alternatively, reinstall conda. |
67,734,105 | It seems that many people struggle with this problem, but I can't find any answer that works.
I think that I am doing everything right but it still doesn't work.
I've built my own package and installed it in my conda environment.
When I do `conda list`, it turns up in the list, at the end (I've called it zzpackagerps):
```
...
zlib 1.2.11 h62dcd97_1010 conda-forge
zstd 1.4.9 h6255e5f_0 conda-forge
zzpackagerps 0.0.1 dev_0 <develop>
```
Now when I run python, in this environment (py39), and try to import the package, I get the infamous ModuleNotFoundError:
```
(py39) s:\Sources>python
Python 3.9.4 | packaged by conda-forge | (default, May 10 2021, 22:10:34) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import zzpackagerps
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'zzpackagerps'
>>>
```
How is this possible? Or, more importantly, how do I get this to work?
(by the way: running on Windows) | 2021/05/28 | [
"https://Stackoverflow.com/questions/67734105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266967/"
] | One possible issue is that the package name may not be identical to the module name. If you locate the `site-packages` where the package is installed, you can try looking at the folder structure and where there are `__init__.py` files defined. | I had a similar problem. I discovered that my Conda env was not activated at the time that I installed the module. So I did "conda activate myenv", before doing "conda install " again. And this time it was picked up correctly. If you are not sure which virtual env are available, use "conda env list" to list them. The one with the asterisk beside it is the currently active env. |
50,811,619 | I have the following code which grabs some data from the Marketo system
```
from marketorestpython.client import MarketoClient
munchkin_id = "xxx-xxx-xxx"
client_id = "00000000-0000-0000-0000-00000000000"
client_secret= "secret"
mc = MarketoClient(munchkin_id, client_id, client_secret)
mc.execute(method='get_multiple_leads_by_filter_type', filterType='email', filterValues=['email@domain.com'],
fields=['BG__c','email','company','createdAt'], batchSize=None)
```
This returns me the following data
```
[{'BG__c': 'ABC',
'company': 'MCS',
'createdAt': '2016-10-25T14:04:15Z',
'id': 4,
'email': 'email@domain.com'},
{'BG__c': 'CDE',
'company': 'MSC',
'createdAt': '2018-03-28T16:41:06Z',
'id': 10850879,
'email': 'email@domain.com'}]
```
What i want to do is, to save this returned to a Parquet file. But when i try this with the following code, i receive an error message.
```
from marketorestpython.client import MarketoClient
munchkin_id = "xxx-xxx-xxx"
client_id = "00000000-0000-0000-0000-00000000000"
client_secret= "secret"
mc = MarketoClient(munchkin_id, client_id, client_secret)
data = mc.execute(method='get_multiple_leads_by_filter_type', filterType='email', filterValues=['email@domain.com'],
fields=['BG__c','email','company','createdAt'], batchSize=None)
sqlContext.read.json(data)
data.write.parquet("adl://subscription.azuredatalakestore.net/folder1/Marketo/marketo_data")
java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.String
---------------------------------------------------------------------------
Py4JJavaError Traceback (most recent call last)
<command-1431708582476650> in <module>()
7 fields=['BG__c','email','company','createdAt'], batchSize=None)
8
----> 9 sqlContext.read.json(data)
10 data.write.parquet("adl://subscription.azuredatalakestore.net/folder1/Marketo/marketo_data")
/databricks/spark/python/pyspark/sql/readwriter.py in json(self, path, schema, primitivesAsString, prefersDecimal, allowComments, allowUnquotedFieldNames, allowSingleQuotes, allowNumericLeadingZero, allowBackslashEscapingAnyCharacter, mode, columnNameOfCorruptRecord, dateFormat, timestampFormat, multiLine, allowUnquotedControlChars, charset)
261 path = [path]
262 if type(path) == list:
--> 263 return self._df(self._jreader.json(self._spark._sc._jvm.PythonUtils.toSeq(path)))
264 elif isinstance(path, RDD):
265 def func(iterator):
/databricks/spark/python/lib/py4j-0.10.6-src.zip/py4j/java_gateway.py in __call__(self, *args)
1158 answer = self.gateway_client.send_command(command)
1159 return_value = get_return_value(
-> 1160 answer, self.gateway_client, self.target_id, self.name)
1161
```
What am i doing wrong? | 2018/06/12 | [
"https://Stackoverflow.com/questions/50811619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1595350/"
] | You have the following data
```
data = [{'BG__c': 'ABC',
'company': 'MCS',
'createdAt': '2016-10-25T14:04:15Z',
'id': 4,
'email': 'email@domain.com'},
{'BG__c': 'CDE',
'company': 'MSC',
'createdAt': '2018-03-28T16:41:06Z',
'id': 10850879,
'email': 'email@domain.com'}]
```
In order to save it to a parquet file, I would suggest creating a DataFrame to then save it as a parquet.
```
from pyspark.sql.types import *
df = spark.createDataFrame(data,
schema = StructType([
StructField("BC_g", StringType(), True),
StructField("company", StringType(), True),
StructField("createdAt", StringType(), True),
StructField("email", StringType(), True),
StructField("id", IntegerType(), True)]))
```
This would give the following types :
```
df.dtypes
[('BC_g', 'string'),
('company', 'string'),
('createdAt', 'string'),
('email', 'string'),
('id', 'int')]
```
You can then save the dataframe as a parquet file
```
df.show()
+-----+-------+--------------------+----------------+--------+
|BG__c|company| createdAt| email| id|
+-----+-------+--------------------+----------------+--------+
| ABC| MCS|2016-10-25T14:04:15Z|email@domain.com| 4|
| CDE| MSC|2018-03-28T16:41:06Z|email@domain.com|10850879|
+-----+-------+--------------------+----------------+--------+
df.write.format('parquet').save(parquet_path_in_hdfs)
```
Where parquet\_path\_in\_hdfs is the path and name of the desired parquet file | As per below statement in your code you are directly writing data. You have to first create dataframe. You can convert json to df using val df = sqlContext.read.json("path/to/json/file").Then do df.write
```
data.write.parquet("adl://subscription.azuredatalakestore.net/folder1/Marketo/marketo_data")
``` |
14,984,136 | I've found something very strange. See this short code below.
```
import os
class Logger(object):
def __init__(self):
self.pid = os.getpid()
print "os: %s." %os
def __del__(self):
print "os: %s." %os
def temp_test_path():
return "./[%d].log" %(os.getpid())
logger = Logger()
```
This is intended for illustrative purposes. It just prints the imported module `os`, on the construstion and destruction of a class (never mind the name `Logger`). However, when I run this, the module `os` seems to "disappear" to `None` in the class destructor. The following is the output.
```
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
os: None.
```
Where is said `os: None.` is my problem. It should be identical to the first output line. However, look back at the python code above, at the function `temp_test_path()`. If I alter the name of this function slightly, to say `temp_test_pat()`, and keep all of the rest of the code exactly the same, and run it, I get the expected output (below).
```
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
```
I can't find any explanation for this except that it's a bug. Can you? By the way I'm using Windows 7 64 bit. | 2013/02/20 | [
"https://Stackoverflow.com/questions/14984136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/948655/"
] | If you are relying on the interpreter shutdown to call your `__del__` it could very well be that the `os` module has already been deleted before your `__del__` gets called. Try explicitly doing a `del logger` in your code and sleep for a bit. This should show it clearly that the code functions as you expect.
I also want to link you to this note in the [official documentation](http://docs.python.org/2/reference/datamodel.html#object.__del__) that `__del__` is not guaranteed to be called in the CPython implementation. | This is to be expected. From the The [Python Language Reference](http://docs.python.org/2/reference/datamodel.html):
>
> Also, when **del**() is invoked in response to a module being deleted
> (e.g., when execution of the program is done), other globals
> referenced by the **del**() method may already have been deleted or in
> the process of being torn down (e.g. the import machinery shutting
> down).
>
>
>
in big red warning box :-) |
14,984,136 | I've found something very strange. See this short code below.
```
import os
class Logger(object):
def __init__(self):
self.pid = os.getpid()
print "os: %s." %os
def __del__(self):
print "os: %s." %os
def temp_test_path():
return "./[%d].log" %(os.getpid())
logger = Logger()
```
This is intended for illustrative purposes. It just prints the imported module `os`, on the construstion and destruction of a class (never mind the name `Logger`). However, when I run this, the module `os` seems to "disappear" to `None` in the class destructor. The following is the output.
```
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
os: None.
```
Where is said `os: None.` is my problem. It should be identical to the first output line. However, look back at the python code above, at the function `temp_test_path()`. If I alter the name of this function slightly, to say `temp_test_pat()`, and keep all of the rest of the code exactly the same, and run it, I get the expected output (below).
```
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
```
I can't find any explanation for this except that it's a bug. Can you? By the way I'm using Windows 7 64 bit. | 2013/02/20 | [
"https://Stackoverflow.com/questions/14984136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/948655/"
] | If you are relying on the interpreter shutdown to call your `__del__` it could very well be that the `os` module has already been deleted before your `__del__` gets called. Try explicitly doing a `del logger` in your code and sleep for a bit. This should show it clearly that the code functions as you expect.
I also want to link you to this note in the [official documentation](http://docs.python.org/2/reference/datamodel.html#object.__del__) that `__del__` is not guaranteed to be called in the CPython implementation. | I've reproduced this. Interesting behavior for sure. One thing that you need to realize is that `__del__` isn't guaranteed to even be called when the interpreter exits -- Also there is no specified order for finalizing objects at interpreter exit.
Since you're exiting the interpreter, there is no guarantee that `os` hasn't been deleted first. In this case, it seems that `os` is in fact being finalized before your `Logger` object. These things *probably* happen depending on the order in the `globals` dictionary.
If we just print the keys of the globals dictionary right before we exit:
```
for k in globals().keys():
print k
```
you'll see:
```
temp_test_path
__builtins__
__file__
__package__
__name__
Logger
os
__doc__
logger
```
or:
```
logger
__builtins__
__file__
__package__
temp_test_pat
__name__
Logger
os
__doc__
```
Notice where your `logger` sits, particularly compared to where `os` sits in the list. With `temp_test_pat`, `logger` actually gets finalized **First**, so `os` is still bound to something meaningful. However, it gets finalize **Last** in the case where you use `temp_test_path`.
If you plan on having an object live until the interpreter is exiting, and you have some cleanup code that you want to run, you could always register a function to be run using `atexit.register`. |
14,984,136 | I've found something very strange. See this short code below.
```
import os
class Logger(object):
def __init__(self):
self.pid = os.getpid()
print "os: %s." %os
def __del__(self):
print "os: %s." %os
def temp_test_path():
return "./[%d].log" %(os.getpid())
logger = Logger()
```
This is intended for illustrative purposes. It just prints the imported module `os`, on the construstion and destruction of a class (never mind the name `Logger`). However, when I run this, the module `os` seems to "disappear" to `None` in the class destructor. The following is the output.
```
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
os: None.
```
Where is said `os: None.` is my problem. It should be identical to the first output line. However, look back at the python code above, at the function `temp_test_path()`. If I alter the name of this function slightly, to say `temp_test_pat()`, and keep all of the rest of the code exactly the same, and run it, I get the expected output (below).
```
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
```
I can't find any explanation for this except that it's a bug. Can you? By the way I'm using Windows 7 64 bit. | 2013/02/20 | [
"https://Stackoverflow.com/questions/14984136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/948655/"
] | If you are relying on the interpreter shutdown to call your `__del__` it could very well be that the `os` module has already been deleted before your `__del__` gets called. Try explicitly doing a `del logger` in your code and sleep for a bit. This should show it clearly that the code functions as you expect.
I also want to link you to this note in the [official documentation](http://docs.python.org/2/reference/datamodel.html#object.__del__) that `__del__` is not guaranteed to be called in the CPython implementation. | Others have given you the answer, it is undefined the order in which global variables (such as `os`, `Logger` and `logger`) are deleted from the module's namespace during shutdown.
However, if you want a workaround, just import `os` into the finaliser's local namespace:
```
def __del__(self):
import os
print "os: %s." %os
```
The `os` module will still be around at this point, it's just that you've lost your global reference to it. |
47,359,475 | I'm trying to teach myself about OOP in python and am really struggling.
I have the following:
```
def __init__(self, quantity):
''' '''
self.switchboard = []
self.state = False
self.quantity = quantity
for i in range(quantity):
self.switchboard.append(i)
def __str__(self):
self.on_list = []
for i in range(self.quantity):
if i == True:
self.on_list.append(i)
return("The following switches are on " + str(self.on_list))
def which_switch(self):
for i in range(len(self.switchboard)):
self.on_list = []
if self.switchboard[i] == True:
on_list.append(i)
print(on_list)
def flip(self, n):
if self.switchboard[n] == True:
self.switchboard[n] = False
else:
self.switchboard[n] = True
```
When I print it, I get `The following switches are on [1]`. Even though I put `10` in the parameters. I want it to display all the switches that are on which in this case should be zero since their initial state is 'off'. | 2017/11/17 | [
"https://Stackoverflow.com/questions/47359475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In `__str__` modify the line:
```
if i == True:
```
to:
```
if self.switchboard[i]:
```
Remember: `i` is just an index, what you want is to access the i-th item in switchboard!
There is also another bug, in method `which_switch()`:
```
on_list.append(i)
```
should be:
```
self.on_list.append(i)
```
and same goes to the print line below it.
Output after the change:
```
The following switches are on [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
Now, I can only guess that what you actually wanted to do in the constructor is:
```
def __init__(self, quantity):
''' '''
self.switchboard = []
self.state = False
self.quantity = quantity
for i in range(quantity):
self.switchboard.append(LightSwitch('off')) # create light-switch and set it to 'off'
```
and then, when you print them - print only the ones that are on:
```
def __str__(self):
self.on_list = []
for i in range(self.quantity):
if self.switchboard[i].state: # check state
self.on_list.append(i)
return("The following switches are on " + str(self.on_list))
``` | Also the reason it's printing 1 as true, is because out of all the elements in list, it's just seeing everything as false and 1 as true (as in 0 == False, 1 == True). |
47,359,475 | I'm trying to teach myself about OOP in python and am really struggling.
I have the following:
```
def __init__(self, quantity):
''' '''
self.switchboard = []
self.state = False
self.quantity = quantity
for i in range(quantity):
self.switchboard.append(i)
def __str__(self):
self.on_list = []
for i in range(self.quantity):
if i == True:
self.on_list.append(i)
return("The following switches are on " + str(self.on_list))
def which_switch(self):
for i in range(len(self.switchboard)):
self.on_list = []
if self.switchboard[i] == True:
on_list.append(i)
print(on_list)
def flip(self, n):
if self.switchboard[n] == True:
self.switchboard[n] = False
else:
self.switchboard[n] = True
```
When I print it, I get `The following switches are on [1]`. Even though I put `10` in the parameters. I want it to display all the switches that are on which in this case should be zero since their initial state is 'off'. | 2017/11/17 | [
"https://Stackoverflow.com/questions/47359475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In `__str__` modify the line:
```
if i == True:
```
to:
```
if self.switchboard[i]:
```
Remember: `i` is just an index, what you want is to access the i-th item in switchboard!
There is also another bug, in method `which_switch()`:
```
on_list.append(i)
```
should be:
```
self.on_list.append(i)
```
and same goes to the print line below it.
Output after the change:
```
The following switches are on [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
Now, I can only guess that what you actually wanted to do in the constructor is:
```
def __init__(self, quantity):
''' '''
self.switchboard = []
self.state = False
self.quantity = quantity
for i in range(quantity):
self.switchboard.append(LightSwitch('off')) # create light-switch and set it to 'off'
```
and then, when you print them - print only the ones that are on:
```
def __str__(self):
self.on_list = []
for i in range(self.quantity):
if self.switchboard[i].state: # check state
self.on_list.append(i)
return("The following switches are on " + str(self.on_list))
``` | You can shorten
```
def flip(self):
''' Sets switch to opposite position.'''
if self.state == True:
self.state = False
elif self.state == False:
self.state = True
```
to
```
def flip(self):
''' Sets switch to opposite position.'''
self.state = not self.state
```
and on your switchboard for
```
def flip_every(self, n):
for i in range(0, len(self.switchboard), n):
if self.switchboard[n] == True:
self.switchboard[n] = False
else:
self.switchboard[n] = True
```
to
```
def flip_every(self, n):
for i in range(0, self.quantity, n):
self.switchboard[n] = not self.switchboard[n]
# you could also just use self.flip(n) instead
```
and
```
def flip(self, n):
self.switchboard[n] = not self.switchboard[n]
```
As a nice touch: you use kind-of the same iteration in `which_switch(self)` and `__str__(self):` that operates on the indexes of switches that are `on`. I built a small `def getOnIndexes(self): ...` that returns you an int list of those indexes, and call this in both methods (DRY - dont repeat yourself principle) using a shorthand to create indexes based on a list comprehension.
```
def getOnIndexes(self):
return [i for i in range(self.quantity) if self.switchboard[i] == True]
```
In total a really nice small OOP example.
What had me stumped though, is why a Switchboard IS\_A LightSwitch - I would model it slightly different, saying a SwitchBoard HAS LightSwitch'es, coming to this:
*Your base class*
```
class LightSwitch():
def __init__(self, default_state):
'''
default_state can only be 'on' or 'off'.
'''
if default_state == 'on':
self.state = True
elif default_state == 'off':
self.state = False
def turn_on(self):
self.state = True
def turn_off(self):
self.state = False
def flip(self):
self.state = not self.state
def __str__(self):
if self.state == True:
return 'I am on'
if self.state == False:
return 'I am off'
def isOn(self):
return self.state
def isOff(self):
return not self.isOn()
```
My alternative switch board:
```
class AlternateSwitchBoard():
''' '''
def __init__(self, quantity, default_state):
''' '''
self.default_state = default_state
self.switchboard = [LightSwitch(default_state) for x in range(quantity)]
self.state = False
self.quantity = quantity
def __str__(self):
retVal = ""
for i in range(self.quantity):
if self.switchboard[i].isOn():
retVal += ", On"
else:
retVal += ", Off"
return "Switchboard: " + retVal[1:].strip()
def which_switch(self):
print(self.getOnIndexes())
def flip(self, n):
self.switchboard[n].flip()
def flip_every(self,stride):
for i in range(0, self.quantity, stride):
self.switchboard[i].flip()
def reset(self):
self.switchboard = [LightSwitch(default_state) for x in range(quantity)]
def getOnIndexes(self):
return [i for i in range(self.quantity) if self.switchboard[i].isOn()]
s2 = AlternateSwitchBoard(10, "off")
s2.flip(2)
s2.flip(7)
print(str(s2))
s2.flip_every(2)
print(str(s2))
s2.which_switch()
```
Output:
```
Switchboard: Off, Off, On, Off, Off, Off, Off, On, Off, Off
Switchboard: On, Off, Off, Off, On, Off, On, On, On, Off
[0, 4, 6, 7, 8]
``` |
42,407,894 | I am previously running python 2.7.11 on Windows 10.
Today, I downloaded and installed python 2.7.13, but the PowerShell version is still at 2.7.11:
```
python --version
Python 2.7.11
```
1. How do I check all installed python versions on my PC?
2. How do I uninstall python 2.7.11?
3. How do i set python 2.7.13 as default python version to launch in PowerShell? | 2017/02/23 | [
"https://Stackoverflow.com/questions/42407894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7378537/"
] | In PowerShell, `Get-Command python | fl *` will tell you which Python executable it's finding and show you details about where it is.
1. You can check *Settings -> Apps and Features*, or *Control Panel -> Programs and Features*. They will show you distinct versions of Python you installed, but that might not be enough if Python is installed as part of some other toolkit or program.
2. If Python 2.7.11 is there, select it and click uninstall. If it's not there, see if you can tell what it's installed with, from the output of `Get-Command` earlier, and decide if you want to remove that.
3. How PowerShell chooses what to run when you type a command is explained in help [about\_Command\_Precedence](https://msdn.microsoft.com/powershell/reference/5.1/Microsoft.PowerShell.Core/about/about_Command_Precedence), and is:
1. Alias
2. Function
3. Cmdlet
4. Native Windows commands
At the point of "Native Windows commands", it goes to the `PATH` environment variable, a semi-colon separated list of path names, which get searched in order, looking for a matching executable file.
You can see the folders with:
```
$Env:PATH -split ';'
```
And you can watch PowerShell identify what to run for 'python' with the command
```
Trace-Command –Name CommandDiscovery –Expression {get-command python} -PSHost
```
So, to make Python 2.7.13 the one to launch, you could:
* make it the only Python version available.
* move its folder to the front of the PATH list, ahead of any other version. See: [What are path and other environment variables, and how can I set or use them - question on SuperUser.com](https://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them)
* make a batch file to launch it called python.bat in a folder in the PATH ahead of other versions.
* make an alias (in your PS Profile) named python to launch the one you want (`New-Alias -name python -Value C:\Python27\python.exe` , etc). | I execute the powershell command line statement in python3.8,
```
import subprocess
subprocess.call('powershell.exe Get-WmiObject Win32_PnPSignedDriver| select DeviceName, Manufacturer, DriverVersion', shell=True)
```
The running result is:
```
'select' is not an internal or external command, nor an executable program or batch file.
``` |
9,680,461 | I've been using Django for a couple of days & setup a basic blog from a [tutorial](http://brenelz.com/blog/a-detailed-django-tutorial-blog-basics-part-iii/#base) with django comments.
I've got a totally separate python script that generates screenshots and uploads them to Amazon S3, now I'd like my django app to display all the images in the bucket and use a comment system on the images. Preferably I'd do this by just storing the URLs in my sqlite db, which I've got hard-coded currently to display all images in the db and has comments enabled on these.
My model:
(Does this need a foreign key to the django comments or is that just part of the Django Magic?!)
```
class Image(models.Model):
imgUrl=models.CharField(max_length=200)
meta=models.CharField(max_length=300)
def __unicode__(self):
return self.imgUrl
```
My bucket structure:
`https://s3-eu-west-1.amazonaws.com/bucket/revision/process/images.png`
Almost all the tutorials and packages I'm finding are based on upload/download rather than a simple `for keys in bucket` type approach that I want.
One of my problems is understanding how I can integrate my Boto functions with Django if I'm using Base.html. In an earlier tutorial I had an index page which had a view and could call functions from there. But base doesn't need that so I'm starting to get a little lost. | 2012/03/13 | [
"https://Stackoverflow.com/questions/9680461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199464/"
] | haven't looked up if boto api changed, but this is how it worked last time i looked
```
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import s3config
conn = S3Connection(s3config.passwd, s3config.secret)
bucket = conn.get_bucket(s3config.bucket)
s3_path = '/some/path/in/your/bucket'
keys = bucket.list(s3_path)
# or if you want all keys:
# keys = bucket.get_all_keys()
for key in keys:
print key
# here you can download or do other stuff
# with the keys like get some metadata
print key.name
print key.etag
print key.size
print key.last_modified
```
---
```
#s3config.py
passwd = 'BLABALBALABALA'
secret = 'xvdwv3efefefefefef'
bucket = 'name-of-your-bucket'
```
---
**Update:**
Amazon s3 is a key value store, where key is a string. So nothing prevents you from putting in keys like:
```
/this/string/key/looks/like/a/unix/path
/folder/images/fileA.jpg
/folder/images/fileB.jpg
/folder/images/folderX/fileX1.jpg
```
now `bucket.list(prefix="/folder/images/")` would yield the latter three.
Look here for further details:
* <http://readthedocs.org/docs/boto/en/latest/ref/s3.html#boto-s3-bucket>
* <http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGET.html?r=8270> | This is my code to store result from s3 to mysql by boto, django.
```
from demo.models import Movies
import boto
from boto.s3.key import Key
import string
from django.db import connection, transaction
def movietitle(b):
key = b.get_key('netflix/movie_titles.txt')
content = key.get_contents_as_string()
line = content.split('\n')
args = []
for imovie in line:
if len(imovie) > 0:
imovie = imovie.split(',')
movieid = imovie[0]
year = imovie[1]
title = imovie[2]
iargs = [string.atoi(movieid),title,year]
args.append(iargs)
cursor = connection.cursor()
sql = "insert into demo_movies(MovieID,MovieName,ReleaseYear) values(%s,%s,%s)"
cursor.executemany(sql,args)
transaction.commit_unless_managed()
cursor.close()
``` |
68,882,049 | ```
import re
word ="sad"
sadwords=[]
with open('emotions.txt','r') as file :
for line in file :
if word in file:
sadwords.append(word)
print(sadwords)
```
**From a text file consisting words and their emotions , i tried to print only the words for sad emotions using python. Someone please help me.**
[This is the emotion text file](https://i.stack.imgur.com/Huh6p.png) | 2021/08/22 | [
"https://Stackoverflow.com/questions/68882049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14870439/"
] | Note in the example, `sadwords.append(word)` adds the word 'sad' to the list for each match and not the emotion.
Try:
```
word ="sad"
sadwords = []
with open('emotions.txt','r') as file :
for line in file :
if word in line:
sadwords.append(line.split(':')[0])
print(sadwords)
```
If you want to strip out the quotes around the emotion then a regex can be used to extract just the emotion.
```python
import re
sadwords = []
with open('emotions.txt','r') as file :
for line in file :
m = re.search("'(.*?)': 'sad'", line)
if m:
sadwords.append(m.group(1))
print(sadwords)
```
**Output:**
```
['afflicted', 'agonized', 'anguished', ...]
``` | Two tiny mistakes:
```
word = "sad"
sadwords=[]
with open('emotions.txt','r') as file :
for line in file :
# check if in line, not in file.
if word in line:
# append the line not the word.
sadwords.append(line.split(":")[0].split("'")[1])
#this gets the word and removes the ''.
``` |
43,576,608 | I have 50 states and capitals. The game is where the user is given the 50 states in a random order and must input the correct capital for each state.
I want to create a dictionary with all the states and capitals, but I don't know how to make the program check if the user put in the correct capital.
```
# Game Start
import random
states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']
random.shuffle(states)
for state in states:
answer = raw_input ("%s" % state)
# DICTIONARY
Dict = {'Alabama':Montgomery, 'Alaska':Juneau, 'Arizona':Phoenix, 'Arkansas':Little_Rock, 'California':Sacramento, 'Colorado':Denver, 'Connecticut':Hartford, 'Delaware':Dover, 'Florida':Tallahassee, 'Georgia':Atlanta, 'Hawaii':Honolulu, 'Idaho':Boise, 'Illinois':Springfield, 'Indiana':Indianapolis, 'Iowa':Des_Moines, 'Kansas':Topeka, 'Kentucky':Frankfort, 'Louisiana':Baton_Rouge, 'Maine':Augusta, 'Maryland':Annapolis, 'Massachusetts':Boston, 'Michigan':Lansing, 'Minnesota':Saint_Paul, 'Mississippi':Jackson, 'Missouri':Jefferson_City, 'Montana':Helena, 'Nebraska':Lincoln, 'Nevada':Carson_City, 'New Hampshire':Concord, 'New Jersey':Trenton, 'New Mexico':Sante_Fe, 'New York':Albany, 'North Carolina':Raleigh, 'North Dakota':Bismarck, 'Ohio':Columbus, 'Oklahoma':Oklahoma_City, 'Oregon':Salem, 'Pennsylvania':Harrisburg, 'Rhode Island':Providence, 'South Carolina':Columbia, 'South Dakota':Pierre, 'Tennessee':Nashville, 'Texas':Austin, 'Utah':Salt_Lake_City, 'Vermont':Montpelier, 'Virginia':Richmond, 'Washington':Olympia, 'West Virginia':Charleston, 'Wisconsin':Madison, 'Wyoming':Cheyenne}
```
How do I check if the answer is in the dictionary? Also, python tells me that name 'Dict" is not defined | 2017/04/23 | [
"https://Stackoverflow.com/questions/43576608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7910608/"
] | You can do something like this:
```
import random
capitals = {'Alabama':'Montgomery', 'Alaska':'Juneau', 'Arizona':'Phoenix', 'Arkansas':'Little_Rock', 'California':'Sacramento', 'Colorado':'Denver', 'Connecticut':'Hartford', 'Delaware':'Dover', 'Florida':'Tallahassee', 'Georgia':'Atlanta', 'Hawaii':'Honolulu', 'Idaho':'Boise', 'Illinois':'Springfield', 'Indiana':'Indianapolis', 'Iowa':'Des_Moines', 'Kansas':'Topeka', 'Kentucky':'Frankfort', 'Louisiana':'Baton_Rouge', 'Maine':'Augusta', 'Maryland':'Annapolis', 'Massachusetts':'Boston', 'Michigan':'Lansing', 'Minnesota':'Saint_Paul', 'Mississippi':'Jackson', 'Missouri':'Jefferson_City', 'Montana':'Helena', 'Nebraska':'Lincoln', 'Nevada':'Carson_City', 'New Hampshire':'Concord', 'New Jersey':'Trenton', 'New Mexico':'Sante_Fe', 'New York':'Albany', 'North Carolina':'Raleigh', 'North Dakota':'Bismarck', 'Ohio':'Columbus', 'Oklahoma':'Oklahoma_City', 'Oregon':'Salem', 'Pennsylvania':'Harrisburg', 'Rhode Island':'Providence', 'South Carolina':'Columbia', 'South Dakota':'Pierre', 'Tennessee':'Nashville', 'Texas':'Austin', 'Utah':'Salt_Lake_City', 'Vermont':'Montpelier', 'Virginia':'Richmond', 'Washington':'Olympia', 'West Virginia':'Charleston', 'Wisconsin':'Madison', 'Wyoming':'Cheyenne'}
states = list(capitals.keys())
random.shuffle(states)
for state in states:
answer = raw_input("%s" % state)
if answer == capitals[state]:
print 'Correct!'
else:
print 'Wrong!'
``` | ```
#Game Start
import random
states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']
###DICTIONARY: Should be defined before you use it
Dict = {'Alabama':Montgomery, 'Alaska':Juneau, 'Arizona':Phoenix, 'Arkansas':Little_Rock, 'California':Sacramento, 'Colorado':Denver, 'Connecticut':Hartford, 'Delaware':Dover, 'Florida':Tallahassee, 'Georgia':Atlanta, 'Hawaii':Honolulu, 'Idaho':Boise, 'Illinois':Springfield, 'Indiana':Indianapolis, 'Iowa':Des_Moines, 'Kansas':Topeka, 'Kentucky':Frankfort, 'Louisiana':Baton_Rouge, 'Maine':Augusta, 'Maryland':Annapolis, 'Massachusetts':Boston, 'Michigan':Lansing, 'Minnesota':Saint_Paul, 'Mississippi':Jackson, 'Missouri':Jefferson_City, 'Montana':Helena, 'Nebraska':Lincoln, 'Nevada':Carson_City, 'New Hampshire':Concord, 'New Jersey':Trenton, 'New Mexico':Sante_Fe, 'New York':Albany, 'North Carolina':Raleigh, 'North Dakota':Bismarck, 'Ohio':Columbus, 'Oklahoma':Oklahoma_City, 'Oregon':Salem, 'Pennsylvania':Harrisburg, 'Rhode Island':Providence, 'South Carolina':Columbia, 'South Dakota':Pierre, 'Tennessee':Nashville, 'Texas':Austin, 'Utah':Salt_Lake_City, 'Vermont':Montpelier, 'Virginia':Richmond, 'Washington':Olympia, 'West Virginia':Charleston, 'Wisconsin':Madison, 'Wyoming':Cheyenne}
random.shuffle(states)
for state in states:
answer = raw_input ("%s" % state)
if Dict[state] == answer:
pass # Do something in case of right answer
else:
pass # what do you want in case of wrong answer
``` |
43,576,608 | I have 50 states and capitals. The game is where the user is given the 50 states in a random order and must input the correct capital for each state.
I want to create a dictionary with all the states and capitals, but I don't know how to make the program check if the user put in the correct capital.
```
# Game Start
import random
states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']
random.shuffle(states)
for state in states:
answer = raw_input ("%s" % state)
# DICTIONARY
Dict = {'Alabama':Montgomery, 'Alaska':Juneau, 'Arizona':Phoenix, 'Arkansas':Little_Rock, 'California':Sacramento, 'Colorado':Denver, 'Connecticut':Hartford, 'Delaware':Dover, 'Florida':Tallahassee, 'Georgia':Atlanta, 'Hawaii':Honolulu, 'Idaho':Boise, 'Illinois':Springfield, 'Indiana':Indianapolis, 'Iowa':Des_Moines, 'Kansas':Topeka, 'Kentucky':Frankfort, 'Louisiana':Baton_Rouge, 'Maine':Augusta, 'Maryland':Annapolis, 'Massachusetts':Boston, 'Michigan':Lansing, 'Minnesota':Saint_Paul, 'Mississippi':Jackson, 'Missouri':Jefferson_City, 'Montana':Helena, 'Nebraska':Lincoln, 'Nevada':Carson_City, 'New Hampshire':Concord, 'New Jersey':Trenton, 'New Mexico':Sante_Fe, 'New York':Albany, 'North Carolina':Raleigh, 'North Dakota':Bismarck, 'Ohio':Columbus, 'Oklahoma':Oklahoma_City, 'Oregon':Salem, 'Pennsylvania':Harrisburg, 'Rhode Island':Providence, 'South Carolina':Columbia, 'South Dakota':Pierre, 'Tennessee':Nashville, 'Texas':Austin, 'Utah':Salt_Lake_City, 'Vermont':Montpelier, 'Virginia':Richmond, 'Washington':Olympia, 'West Virginia':Charleston, 'Wisconsin':Madison, 'Wyoming':Cheyenne}
```
How do I check if the answer is in the dictionary? Also, python tells me that name 'Dict" is not defined | 2017/04/23 | [
"https://Stackoverflow.com/questions/43576608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7910608/"
] | You can do something like this:
```
import random
capitals = {'Alabama':'Montgomery', 'Alaska':'Juneau', 'Arizona':'Phoenix', 'Arkansas':'Little_Rock', 'California':'Sacramento', 'Colorado':'Denver', 'Connecticut':'Hartford', 'Delaware':'Dover', 'Florida':'Tallahassee', 'Georgia':'Atlanta', 'Hawaii':'Honolulu', 'Idaho':'Boise', 'Illinois':'Springfield', 'Indiana':'Indianapolis', 'Iowa':'Des_Moines', 'Kansas':'Topeka', 'Kentucky':'Frankfort', 'Louisiana':'Baton_Rouge', 'Maine':'Augusta', 'Maryland':'Annapolis', 'Massachusetts':'Boston', 'Michigan':'Lansing', 'Minnesota':'Saint_Paul', 'Mississippi':'Jackson', 'Missouri':'Jefferson_City', 'Montana':'Helena', 'Nebraska':'Lincoln', 'Nevada':'Carson_City', 'New Hampshire':'Concord', 'New Jersey':'Trenton', 'New Mexico':'Sante_Fe', 'New York':'Albany', 'North Carolina':'Raleigh', 'North Dakota':'Bismarck', 'Ohio':'Columbus', 'Oklahoma':'Oklahoma_City', 'Oregon':'Salem', 'Pennsylvania':'Harrisburg', 'Rhode Island':'Providence', 'South Carolina':'Columbia', 'South Dakota':'Pierre', 'Tennessee':'Nashville', 'Texas':'Austin', 'Utah':'Salt_Lake_City', 'Vermont':'Montpelier', 'Virginia':'Richmond', 'Washington':'Olympia', 'West Virginia':'Charleston', 'Wisconsin':'Madison', 'Wyoming':'Cheyenne'}
states = list(capitals.keys())
random.shuffle(states)
for state in states:
answer = raw_input("%s" % state)
if answer == capitals[state]:
print 'Correct!'
else:
print 'Wrong!'
``` | I've had this one tested and it works just fine. But it's in Python 3, so you'll need to do some minor adjustments.
```
import random
states =['Alabama', 'Alaska', 'Arizona']
random.shuffle(states)
# dictionary need to be stated beforehand to check the input
# use '' for the state capital
state_dict = {'Alabama':'Montgomery', 'Alaska':'Juneau', 'Arizona':'Phoenix'}
for state in states:
answer = input("%s " %state)
if answer==(state_dict[state]):
print ("Correct")
else :
print ("False")
``` |
43,576,608 | I have 50 states and capitals. The game is where the user is given the 50 states in a random order and must input the correct capital for each state.
I want to create a dictionary with all the states and capitals, but I don't know how to make the program check if the user put in the correct capital.
```
# Game Start
import random
states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']
random.shuffle(states)
for state in states:
answer = raw_input ("%s" % state)
# DICTIONARY
Dict = {'Alabama':Montgomery, 'Alaska':Juneau, 'Arizona':Phoenix, 'Arkansas':Little_Rock, 'California':Sacramento, 'Colorado':Denver, 'Connecticut':Hartford, 'Delaware':Dover, 'Florida':Tallahassee, 'Georgia':Atlanta, 'Hawaii':Honolulu, 'Idaho':Boise, 'Illinois':Springfield, 'Indiana':Indianapolis, 'Iowa':Des_Moines, 'Kansas':Topeka, 'Kentucky':Frankfort, 'Louisiana':Baton_Rouge, 'Maine':Augusta, 'Maryland':Annapolis, 'Massachusetts':Boston, 'Michigan':Lansing, 'Minnesota':Saint_Paul, 'Mississippi':Jackson, 'Missouri':Jefferson_City, 'Montana':Helena, 'Nebraska':Lincoln, 'Nevada':Carson_City, 'New Hampshire':Concord, 'New Jersey':Trenton, 'New Mexico':Sante_Fe, 'New York':Albany, 'North Carolina':Raleigh, 'North Dakota':Bismarck, 'Ohio':Columbus, 'Oklahoma':Oklahoma_City, 'Oregon':Salem, 'Pennsylvania':Harrisburg, 'Rhode Island':Providence, 'South Carolina':Columbia, 'South Dakota':Pierre, 'Tennessee':Nashville, 'Texas':Austin, 'Utah':Salt_Lake_City, 'Vermont':Montpelier, 'Virginia':Richmond, 'Washington':Olympia, 'West Virginia':Charleston, 'Wisconsin':Madison, 'Wyoming':Cheyenne}
```
How do I check if the answer is in the dictionary? Also, python tells me that name 'Dict" is not defined | 2017/04/23 | [
"https://Stackoverflow.com/questions/43576608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7910608/"
] | You can do something like this:
```
import random
capitals = {'Alabama':'Montgomery', 'Alaska':'Juneau', 'Arizona':'Phoenix', 'Arkansas':'Little_Rock', 'California':'Sacramento', 'Colorado':'Denver', 'Connecticut':'Hartford', 'Delaware':'Dover', 'Florida':'Tallahassee', 'Georgia':'Atlanta', 'Hawaii':'Honolulu', 'Idaho':'Boise', 'Illinois':'Springfield', 'Indiana':'Indianapolis', 'Iowa':'Des_Moines', 'Kansas':'Topeka', 'Kentucky':'Frankfort', 'Louisiana':'Baton_Rouge', 'Maine':'Augusta', 'Maryland':'Annapolis', 'Massachusetts':'Boston', 'Michigan':'Lansing', 'Minnesota':'Saint_Paul', 'Mississippi':'Jackson', 'Missouri':'Jefferson_City', 'Montana':'Helena', 'Nebraska':'Lincoln', 'Nevada':'Carson_City', 'New Hampshire':'Concord', 'New Jersey':'Trenton', 'New Mexico':'Sante_Fe', 'New York':'Albany', 'North Carolina':'Raleigh', 'North Dakota':'Bismarck', 'Ohio':'Columbus', 'Oklahoma':'Oklahoma_City', 'Oregon':'Salem', 'Pennsylvania':'Harrisburg', 'Rhode Island':'Providence', 'South Carolina':'Columbia', 'South Dakota':'Pierre', 'Tennessee':'Nashville', 'Texas':'Austin', 'Utah':'Salt_Lake_City', 'Vermont':'Montpelier', 'Virginia':'Richmond', 'Washington':'Olympia', 'West Virginia':'Charleston', 'Wisconsin':'Madison', 'Wyoming':'Cheyenne'}
states = list(capitals.keys())
random.shuffle(states)
for state in states:
answer = raw_input("%s" % state)
if answer == capitals[state]:
print 'Correct!'
else:
print 'Wrong!'
``` | To avoid double book keeping, you can use `random.sample` on the dictionary items.
It's also a lot more pythonic, because you do loop directly over key and value and are not doing a loop over a key and then a lookup:
```
import random
state_capitols = {
'Alabama': 'Montgomery',
'Alaska': 'Juneau',
'Arizona': 'Phoenix',
}
for state, capitol in random.sample(state_capitols.items(), len(state_capitols)):
answer = input('What is the capitol of {}? '.format(state))
if answer == capitol:
print('Correct!')
else:
print('Wrong!')
``` |
49,740,758 | Is there a more efficient way to use Template Matching with images of different sizes?
Here is my current Script:
```
import cv2
import numpy as np
img_bgr = cv2.imread('./full.jpg')
img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
template = cv2.imread('./template.jpg', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray, template,
cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_bgr, pt, (pt[0]+w, pt[1]+h), (0,255,255), 2)
cv2.imshow('detected', img_bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
This is my Template:
[Template](https://imgur.com/urQdXOo)
And I have these images, the first one works and the second one does not because of the size:
[Works!](https://imgur.com/aHKbkiO)
[Fails](https://imgur.com/VXGpF3P)
At first thought, I'm thinking it's failing because of the size of the template vs image
So I tried using this tutorial: [Multi Scale Matching](https://www.pyimagesearch.com/2015/01/26/multi-scale-template-matching-using-python-opencv/)
But this seems really slow and bulky especially since I intend to use this in videos when I get it working. Is there a better way to handle this
Also, eventually I would also only like to check the top right of the image, I know that's a completely different question, but if you have any ideas since we're talking about scaling :) | 2018/04/09 | [
"https://Stackoverflow.com/questions/49740758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8180125/"
] | The easiest way is to use feature matching instead of template matching. Feature matching is exactly meant for this kind of applications. It can also detect if the image is rotated .. etc
Have a lock at this
<https://docs.opencv.org/master/dc/dc3/tutorial_py_matcher.html> | For different size use multi-scale template matching |
49,740,758 | Is there a more efficient way to use Template Matching with images of different sizes?
Here is my current Script:
```
import cv2
import numpy as np
img_bgr = cv2.imread('./full.jpg')
img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
template = cv2.imread('./template.jpg', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray, template,
cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_bgr, pt, (pt[0]+w, pt[1]+h), (0,255,255), 2)
cv2.imshow('detected', img_bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
This is my Template:
[Template](https://imgur.com/urQdXOo)
And I have these images, the first one works and the second one does not because of the size:
[Works!](https://imgur.com/aHKbkiO)
[Fails](https://imgur.com/VXGpF3P)
At first thought, I'm thinking it's failing because of the size of the template vs image
So I tried using this tutorial: [Multi Scale Matching](https://www.pyimagesearch.com/2015/01/26/multi-scale-template-matching-using-python-opencv/)
But this seems really slow and bulky especially since I intend to use this in videos when I get it working. Is there a better way to handle this
Also, eventually I would also only like to check the top right of the image, I know that's a completely different question, but if you have any ideas since we're talking about scaling :) | 2018/04/09 | [
"https://Stackoverflow.com/questions/49740758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8180125/"
] | For different size use multi-scale template matching | How about using AI based algorithms instead of OpenCV?
Mask R-CNN, YOLO, TensorFlow Object Detection API etc.
The above algorithms may already be old enough... |
49,740,758 | Is there a more efficient way to use Template Matching with images of different sizes?
Here is my current Script:
```
import cv2
import numpy as np
img_bgr = cv2.imread('./full.jpg')
img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
template = cv2.imread('./template.jpg', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray, template,
cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_bgr, pt, (pt[0]+w, pt[1]+h), (0,255,255), 2)
cv2.imshow('detected', img_bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
This is my Template:
[Template](https://imgur.com/urQdXOo)
And I have these images, the first one works and the second one does not because of the size:
[Works!](https://imgur.com/aHKbkiO)
[Fails](https://imgur.com/VXGpF3P)
At first thought, I'm thinking it's failing because of the size of the template vs image
So I tried using this tutorial: [Multi Scale Matching](https://www.pyimagesearch.com/2015/01/26/multi-scale-template-matching-using-python-opencv/)
But this seems really slow and bulky especially since I intend to use this in videos when I get it working. Is there a better way to handle this
Also, eventually I would also only like to check the top right of the image, I know that's a completely different question, but if you have any ideas since we're talking about scaling :) | 2018/04/09 | [
"https://Stackoverflow.com/questions/49740758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8180125/"
] | The easiest way is to use feature matching instead of template matching. Feature matching is exactly meant for this kind of applications. It can also detect if the image is rotated .. etc
Have a lock at this
<https://docs.opencv.org/master/dc/dc3/tutorial_py_matcher.html> | What you are looking for isn't that simple. The need is for `multi-scale template matching`, but as you mentioned, it will be slow, especially when the image resolution is pretty high.
The best and easiest solution for such cases is to train a convolutional neural network, a small one. Make use of transfer learning and train an `SSD mobilenet` on your data and you'll have a network that can do this detection pretty well for you and trust me it will be really fast. Object detection would give you the fastest, better, and more accurate solutions here.
Here's a [link](https://heartbeat.fritz.ai/real-time-object-detection-using-ssd-mobilenet-v2-on-video-streams-3bfc1577399c) for an article explaining how to train for object detection in videos. |
49,740,758 | Is there a more efficient way to use Template Matching with images of different sizes?
Here is my current Script:
```
import cv2
import numpy as np
img_bgr = cv2.imread('./full.jpg')
img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
template = cv2.imread('./template.jpg', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray, template,
cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_bgr, pt, (pt[0]+w, pt[1]+h), (0,255,255), 2)
cv2.imshow('detected', img_bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
This is my Template:
[Template](https://imgur.com/urQdXOo)
And I have these images, the first one works and the second one does not because of the size:
[Works!](https://imgur.com/aHKbkiO)
[Fails](https://imgur.com/VXGpF3P)
At first thought, I'm thinking it's failing because of the size of the template vs image
So I tried using this tutorial: [Multi Scale Matching](https://www.pyimagesearch.com/2015/01/26/multi-scale-template-matching-using-python-opencv/)
But this seems really slow and bulky especially since I intend to use this in videos when I get it working. Is there a better way to handle this
Also, eventually I would also only like to check the top right of the image, I know that's a completely different question, but if you have any ideas since we're talking about scaling :) | 2018/04/09 | [
"https://Stackoverflow.com/questions/49740758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8180125/"
] | The easiest way is to use feature matching instead of template matching. Feature matching is exactly meant for this kind of applications. It can also detect if the image is rotated .. etc
Have a lock at this
<https://docs.opencv.org/master/dc/dc3/tutorial_py_matcher.html> | How about using AI based algorithms instead of OpenCV?
Mask R-CNN, YOLO, TensorFlow Object Detection API etc.
The above algorithms may already be old enough... |
49,740,758 | Is there a more efficient way to use Template Matching with images of different sizes?
Here is my current Script:
```
import cv2
import numpy as np
img_bgr = cv2.imread('./full.jpg')
img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
template = cv2.imread('./template.jpg', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray, template,
cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_bgr, pt, (pt[0]+w, pt[1]+h), (0,255,255), 2)
cv2.imshow('detected', img_bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
This is my Template:
[Template](https://imgur.com/urQdXOo)
And I have these images, the first one works and the second one does not because of the size:
[Works!](https://imgur.com/aHKbkiO)
[Fails](https://imgur.com/VXGpF3P)
At first thought, I'm thinking it's failing because of the size of the template vs image
So I tried using this tutorial: [Multi Scale Matching](https://www.pyimagesearch.com/2015/01/26/multi-scale-template-matching-using-python-opencv/)
But this seems really slow and bulky especially since I intend to use this in videos when I get it working. Is there a better way to handle this
Also, eventually I would also only like to check the top right of the image, I know that's a completely different question, but if you have any ideas since we're talking about scaling :) | 2018/04/09 | [
"https://Stackoverflow.com/questions/49740758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8180125/"
] | What you are looking for isn't that simple. The need is for `multi-scale template matching`, but as you mentioned, it will be slow, especially when the image resolution is pretty high.
The best and easiest solution for such cases is to train a convolutional neural network, a small one. Make use of transfer learning and train an `SSD mobilenet` on your data and you'll have a network that can do this detection pretty well for you and trust me it will be really fast. Object detection would give you the fastest, better, and more accurate solutions here.
Here's a [link](https://heartbeat.fritz.ai/real-time-object-detection-using-ssd-mobilenet-v2-on-video-streams-3bfc1577399c) for an article explaining how to train for object detection in videos. | How about using AI based algorithms instead of OpenCV?
Mask R-CNN, YOLO, TensorFlow Object Detection API etc.
The above algorithms may already be old enough... |
9,371,542 | I am using emacs 23 -nw and xterm installed on Debian Squeeze. I need highlighting with python but I don't have it. How can I enable it?
Edit:
Thanks for all answers, the problem is that
* I have googled a lot, really.
* I have the code on a file with extension .py
* The script starts with #!/usr/bin/python, as one of the the answers points I have changed to !#/usr/bin/env python
* I used M-x and tried to find something related to python, well there many options which do not solve my problem.
Sorry my question was not very precise and I even accept -10 but I don't have highlight which would give me red highlight for lines starting # etc. To be more precise I have a very a dull highlight; lines with # are white, lines between """ """ are green, **some** of the variable names are yellow but don't know why not all. [import, as, from] are light blue, [open, max, and other function names] are dark blue etc. And besides my 200 lines of code is working. | 2012/02/21 | [
"https://Stackoverflow.com/questions/9371542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/503473/"
] | I'm not sure if this is right, but try the following.
1) M-x
2) type in "python-mode". Tab completion works here so type in "pyth" and hit tab and you can see what your options are.
mj | Emacs 23 should know about Python out of the box. Does the name of your Python file end with `.py`, or does the file have `#!/usr/bin/env python` as the first line? If you're creating a new file, make sure the filename ends with `.py`. You can also use `M-x python-mode` as mentioned in another answer. If none of that works, check that your terminal actually supports color. |
9,371,542 | I am using emacs 23 -nw and xterm installed on Debian Squeeze. I need highlighting with python but I don't have it. How can I enable it?
Edit:
Thanks for all answers, the problem is that
* I have googled a lot, really.
* I have the code on a file with extension .py
* The script starts with #!/usr/bin/python, as one of the the answers points I have changed to !#/usr/bin/env python
* I used M-x and tried to find something related to python, well there many options which do not solve my problem.
Sorry my question was not very precise and I even accept -10 but I don't have highlight which would give me red highlight for lines starting # etc. To be more precise I have a very a dull highlight; lines with # are white, lines between """ """ are green, **some** of the variable names are yellow but don't know why not all. [import, as, from] are light blue, [open, max, and other function names] are dark blue etc. And besides my 200 lines of code is working. | 2012/02/21 | [
"https://Stackoverflow.com/questions/9371542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/503473/"
] | If you run Emacs from `xterm` with `emacs -nw`, you'll have a different color layout than if you run the same color mode in an X window. Differences include big changes in the highlighting of comments, different colors assigned to various keywords and (rarely in my experience, though Python comments seem to fall into this category) failure to highlight some elements.
I'm not really sure why this happens, but it doesn't seem to be a problem on your end since it's consistent on every machine I've worked on. If it really bugs you, and you really, really want to keep running from `xterm`, take a look at the [color-theme](http://www.nongnu.org/color-theme/) module, it may help. | Emacs 23 should know about Python out of the box. Does the name of your Python file end with `.py`, or does the file have `#!/usr/bin/env python` as the first line? If you're creating a new file, make sure the filename ends with `.py`. You can also use `M-x python-mode` as mentioned in another answer. If none of that works, check that your terminal actually supports color. |
15,479,928 | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
What am I missing? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15479928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> **Note:** This answer was written before the implementation of the `dict` type changed, in Python 3.6. Most of the implementation details in this answer still apply, but the listing order of keys in *dictionaries* is no longer determined by hash values. The set implementation remains unchanged.
>
>
>
The order is not arbitrary, but depends on the insertion and deletion history of the dictionary or set, as well as on the specific Python implementation. For the remainder of this answer, for 'dictionary', you can also read 'set'; sets are implemented as dictionaries with just keys and no values.
Keys are hashed, and hash values are assigned to slots in a dynamic table (it can grow or shrink based on needs). And that mapping process can lead to collisions, meaning that a key will have to be slotted in a *next* slot based on what is already there.
Listing the contents loops over the slots, and so keys are listed in the order they *currently* reside in the table.
Take the keys `'foo'` and `'bar'`, for example, and lets assume the table size is 8 slots. In Python 2.7, `hash('foo')` is `-4177197833195190597`, `hash('bar')` is `327024216814240868`. Modulo 8, that means these two keys are slotted in slots 3 and 4 then:
```
>>> hash('foo')
-4177197833195190597
>>> hash('foo') % 8
3
>>> hash('bar')
327024216814240868
>>> hash('bar') % 8
4
```
This informs their listing order:
```
>>> {'bar': None, 'foo': None}
{'foo': None, 'bar': None}
```
All slots except 3 and 4 are empty, looping over the table first lists slot 3, then slot 4, so `'foo'` is listed before `'bar'`.
`bar` and `baz`, however, have hash values that are exactly 8 apart and thus map to the exact same slot, `4`:
```
>>> hash('bar')
327024216814240868
>>> hash('baz')
327024216814240876
>>> hash('bar') % 8
4
>>> hash('baz') % 8
4
```
Their order now depends on which key was slotted first; the second key will have to be moved to a next slot:
```
>>> {'baz': None, 'bar': None}
{'bar': None, 'baz': None}
>>> {'bar': None, 'baz': None}
{'baz': None, 'bar': None}
```
The table order differs here, because one or the other key was slotted first.
The technical name for the underlying structure used by CPython (the most commonly used Python implemenation) is a [hash table](http://en.wikipedia.org/wiki/hash_table), one that uses open addressing. If you are curious, and understand C well enough, take a look at the [C implementation](http://hg.python.org/cpython/file/tip/Objects/dictobject.c) for all the (well documented) details. You could also watch this [Pycon 2010 presentation by Brandon Rhodes](http://pyvideo.org/video/276/the-mighty-dictionary-55) about how CPython `dict` works, or pick up a copy of [Beautiful Code](http://shop.oreilly.com/product/9780596510046.do), which includes a chapter on the implementation written by Andrew Kuchling.
Note that as of Python 3.3, a random hash seed is used as well, making hash collisions unpredictable to prevent certain types of denial of service (where an attacker renders a Python server unresponsive by causing mass hash collisions). This means that the order of a given dictionary or set is then *also* dependent on the random hash seed for the current Python invocation.
Other implementations are free to use a different structure for dictionaries, as long as they satisfy the documented Python interface for them, but I believe that all implementations so far use a variation of the hash table.
CPython 3.6 introduces a *new* `dict` implementation that maintains insertion order, and is faster and more memory efficient to boot. Rather than keep a large sparse table where each row references the stored hash value, and the key and value objects, the new implementation adds a smaller hash *array* that only references indices in a separate 'dense' table (one that only contains as many rows as there are actual key-value pairs), and it is the dense table that happens to list the contained items in order. See the [proposal to Python-Dev for more details](https://mail.python.org/pipermail/python-dev/2012-December/123028.html). Note that in Python 3.6 this is considered an *implementation detail*, Python-the-language does not specify that other implementations have to retain order. This changed in Python 3.7, where this detail was [elevated to be a *language specification*](https://mail.python.org/pipermail/python-dev/2017-December/151283.html); for any implementation to be properly compatible with Python 3.7 or newer it **must** copy this order-preserving behaviour. And to be explicit: this change doesn't apply to sets, as sets already have a 'small' hash structure.
Python 2.7 and newer also provides an [`OrderedDict` class](https://docs.python.org/2/library/collections.html#collections.OrderedDict), a subclass of `dict` that adds an additional data structure to record key order. At the price of some speed and extra memory, this class remembers in what order you inserted keys; listing keys, values or items will then do so in that order. It uses a doubly-linked list stored in an additional dictionary to keep the order up-to-date efficiently. See the [post by Raymond Hettinger outlining the idea](https://mail.python.org/pipermail/python-dev/2012-December/123028.html). `OrderedDict` objects have other advantages, such as being *re-orderable*.
If you wanted an ordered set, you can install the [`oset` package](https://pypi.python.org/pypi/oset); it works on Python 2.5 and up. | "Arbitrary" isn't the same thing as "non-determined".
What they're saying is that there are no useful properties of dictionary iteration order that are "in the public interface". There almost certainly are many properties of the iteration order that are fully determined by the code that currently implements dictionary iteration, but the authors aren't promising them to you as something you can use. This gives them more freedom to change these properties between Python versions (or even just in different operating conditions, or completely at random at runtime) without worrying that your program will break.
Thus if you write a program that depends on *any property at all* of dictionary order, then you are "breaking the contract" of using the dictionary type, and the Python developers are not promising that this will always work, even if it appears to work for now when you test it. It's basically the equivalent of relying on "undefined behaviour" in C. |
15,479,928 | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
What am I missing? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15479928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> **Note:** This answer was written before the implementation of the `dict` type changed, in Python 3.6. Most of the implementation details in this answer still apply, but the listing order of keys in *dictionaries* is no longer determined by hash values. The set implementation remains unchanged.
>
>
>
The order is not arbitrary, but depends on the insertion and deletion history of the dictionary or set, as well as on the specific Python implementation. For the remainder of this answer, for 'dictionary', you can also read 'set'; sets are implemented as dictionaries with just keys and no values.
Keys are hashed, and hash values are assigned to slots in a dynamic table (it can grow or shrink based on needs). And that mapping process can lead to collisions, meaning that a key will have to be slotted in a *next* slot based on what is already there.
Listing the contents loops over the slots, and so keys are listed in the order they *currently* reside in the table.
Take the keys `'foo'` and `'bar'`, for example, and lets assume the table size is 8 slots. In Python 2.7, `hash('foo')` is `-4177197833195190597`, `hash('bar')` is `327024216814240868`. Modulo 8, that means these two keys are slotted in slots 3 and 4 then:
```
>>> hash('foo')
-4177197833195190597
>>> hash('foo') % 8
3
>>> hash('bar')
327024216814240868
>>> hash('bar') % 8
4
```
This informs their listing order:
```
>>> {'bar': None, 'foo': None}
{'foo': None, 'bar': None}
```
All slots except 3 and 4 are empty, looping over the table first lists slot 3, then slot 4, so `'foo'` is listed before `'bar'`.
`bar` and `baz`, however, have hash values that are exactly 8 apart and thus map to the exact same slot, `4`:
```
>>> hash('bar')
327024216814240868
>>> hash('baz')
327024216814240876
>>> hash('bar') % 8
4
>>> hash('baz') % 8
4
```
Their order now depends on which key was slotted first; the second key will have to be moved to a next slot:
```
>>> {'baz': None, 'bar': None}
{'bar': None, 'baz': None}
>>> {'bar': None, 'baz': None}
{'baz': None, 'bar': None}
```
The table order differs here, because one or the other key was slotted first.
The technical name for the underlying structure used by CPython (the most commonly used Python implemenation) is a [hash table](http://en.wikipedia.org/wiki/hash_table), one that uses open addressing. If you are curious, and understand C well enough, take a look at the [C implementation](http://hg.python.org/cpython/file/tip/Objects/dictobject.c) for all the (well documented) details. You could also watch this [Pycon 2010 presentation by Brandon Rhodes](http://pyvideo.org/video/276/the-mighty-dictionary-55) about how CPython `dict` works, or pick up a copy of [Beautiful Code](http://shop.oreilly.com/product/9780596510046.do), which includes a chapter on the implementation written by Andrew Kuchling.
Note that as of Python 3.3, a random hash seed is used as well, making hash collisions unpredictable to prevent certain types of denial of service (where an attacker renders a Python server unresponsive by causing mass hash collisions). This means that the order of a given dictionary or set is then *also* dependent on the random hash seed for the current Python invocation.
Other implementations are free to use a different structure for dictionaries, as long as they satisfy the documented Python interface for them, but I believe that all implementations so far use a variation of the hash table.
CPython 3.6 introduces a *new* `dict` implementation that maintains insertion order, and is faster and more memory efficient to boot. Rather than keep a large sparse table where each row references the stored hash value, and the key and value objects, the new implementation adds a smaller hash *array* that only references indices in a separate 'dense' table (one that only contains as many rows as there are actual key-value pairs), and it is the dense table that happens to list the contained items in order. See the [proposal to Python-Dev for more details](https://mail.python.org/pipermail/python-dev/2012-December/123028.html). Note that in Python 3.6 this is considered an *implementation detail*, Python-the-language does not specify that other implementations have to retain order. This changed in Python 3.7, where this detail was [elevated to be a *language specification*](https://mail.python.org/pipermail/python-dev/2017-December/151283.html); for any implementation to be properly compatible with Python 3.7 or newer it **must** copy this order-preserving behaviour. And to be explicit: this change doesn't apply to sets, as sets already have a 'small' hash structure.
Python 2.7 and newer also provides an [`OrderedDict` class](https://docs.python.org/2/library/collections.html#collections.OrderedDict), a subclass of `dict` that adds an additional data structure to record key order. At the price of some speed and extra memory, this class remembers in what order you inserted keys; listing keys, values or items will then do so in that order. It uses a doubly-linked list stored in an additional dictionary to keep the order up-to-date efficiently. See the [post by Raymond Hettinger outlining the idea](https://mail.python.org/pipermail/python-dev/2012-December/123028.html). `OrderedDict` objects have other advantages, such as being *re-orderable*.
If you wanted an ordered set, you can install the [`oset` package](https://pypi.python.org/pypi/oset); it works on Python 2.5 and up. | This is more a response to [Python 3.41 A set](https://stackoverflow.com/questions/26098775/python-3-41-a-set) before it was closed as a duplicate.
---
The others are right: don't rely on the order. Don't even pretend there is one.
That said, there is *one* thing you can rely on:
```py
list(myset) == list(myset)
```
That is, the order is *stable*.
---
Understanding why there is a *perceived* order requires understanding a few things:
* That Python uses *hash sets*,
* How CPython's hash set is stored in memory and
* How numbers get hashed
From the top:
A *hash set* is a method of storing random data with really fast lookup times.
It has a backing array:
```none
# A C array; items may be NULL,
# a pointer to an object, or a
# special dummy object
_ _ 4 _ _ 2 _ _ 6
```
We shall ignore the special dummy object, which exists only to make removes easier to deal with, because we won't be removing from these sets.
In order to have really fast lookup, you do some magic to calculate a hash from an object. The only rule is that two objects which are equal have the same hash. (But if two objects have the same hash they can be unequal.)
You then make in index by taking the modulus by the array length:
```py
hash(4) % len(storage) = index 2
```
This makes it really fast to access elements.
Hashes are only most of the story, as `hash(n) % len(storage)` and `hash(m) % len(storage)` can result in the same number. In that case, several different strategies can try and resolve the conflict. [CPython uses "linear probing" 9 times](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L49) before doing pseudorandom probing, so it will look *to the right of the slot* for up to 9 places before looking elsewhere.
CPython's hash sets are stored like this:
* A hash set can be **no more than [60% full](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L175)** (*note:* this load factor was [previously 66%](https://github.com/python/cpython/commit/5cd87a8d61246b0a6233bfb8503d4718b693cef0) it was reduced in Python 3.7). If there are 20 elements and the backing array is 30 elements long, the backing store will resize to be larger. This is because you get collisions more often with small backing stores, and collisions slow everything down.
* When the backing store becomes too full, it will be automatically resized to increase the ratio of unused space (a higher ratio of unused space means it's faster to find a slot when handling a hash collision). For small sets, storage will be quadrupled in size, and for large sets (>50,000) it will be doubled in size [(source)](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L177).
So when you create an array the backing store is length 8. Once it is 4 full and you add an element, it will contain 5 elements. `5 > ³⁄₅·8` so this triggers a resize, and the backing store quadruples to size 32.
```py
>>> import sys
>>> s = set()
>>> for i in range(10):
... print(len(s), sys.getsizeof(s))
... s.add(i)
...
0 216
1 216
2 216
3 216
4 216
5 728
6 728
7 728
8 728
9 728
```
Finally, `hash(n)` just returns `n` for integers (except for `hash(-1)` which returns `-2` because the value [`-1` is reserved for another usage](https://github.com/python/cpython/blob/v3.11.0/Objects/object.c#L762-L768)).
---
So, let's look at the first one:
```py
v_set = {88,11,1,33,21,3,7,55,37,8}
```
`len(v_set)` is 10, so the backing store is at least 15(+1) **after all items have been added**. The relevant power of 2 is 32. So the backing store is:
```none
__ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
```
We have
```py
hash(88) % 32 = 24
hash(11) % 32 = 11
hash(1) % 32 = 1
hash(33) % 32 = 1
hash(21) % 32 = 21
hash(3) % 32 = 3
hash(7) % 32 = 7
hash(55) % 32 = 23
hash(37) % 32 = 5
hash(8) % 32 = 8
```
so these insert as:
```none
__ 1 __ 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
33 ← Can't also be where 1 is;
either 1 or 33 has to move
```
So we would expect an order like
```py
{[1 or 33], 3, 37, 7, 8, 11, 21, 55, 88}
```
with the 1 or 33 that isn't at the start somewhere else. This will use linear probing, so we will either have:
```none
↓
__ 1 33 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
```
or
```none
↓
__ 33 1 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
```
You might expect the 33 to be the one that's displaced because the 1 was already there, but due to the resizing that happens as the set is being built, this isn't actually the case. Every time the set gets rebuilt, the items already added are effectively reordered.
Now you can see why
```py
{7,5,11,1,4,13,55,12,2,3,6,20,9,10}
```
might be in order. There are 14 elements, so the backing store is at least 21+1, which means 32:
```none
__ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
```
1 to 13 hash in the first 13 slots. 20 goes in slot 20.
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ __ __ 20 __ __ __ __ __ __ __ __ __ __ __
```
55 goes in slot `hash(55) % 32` which is 23:
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ __ __ 20 __ __ 55 __ __ __ __ __ __ __ __
```
If we chose 50 instead, we'd expect
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ 50 __ 20 __ __ __ __ __ __ __ __ __ __ __
```
And lo and behold:
```py
>>> {1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 20, 50}
{1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 50, 20}
```
---
`pop` is [implemented](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L629-L652) quite simply by the looks of things: it traverses the underlying array and pops the first element, skipping over unused slots and "dummy" entries (tombstone markers from removed elements).
---
### This is all implementation detail. |
15,479,928 | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
What am I missing? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15479928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> **Note:** This answer was written before the implementation of the `dict` type changed, in Python 3.6. Most of the implementation details in this answer still apply, but the listing order of keys in *dictionaries* is no longer determined by hash values. The set implementation remains unchanged.
>
>
>
The order is not arbitrary, but depends on the insertion and deletion history of the dictionary or set, as well as on the specific Python implementation. For the remainder of this answer, for 'dictionary', you can also read 'set'; sets are implemented as dictionaries with just keys and no values.
Keys are hashed, and hash values are assigned to slots in a dynamic table (it can grow or shrink based on needs). And that mapping process can lead to collisions, meaning that a key will have to be slotted in a *next* slot based on what is already there.
Listing the contents loops over the slots, and so keys are listed in the order they *currently* reside in the table.
Take the keys `'foo'` and `'bar'`, for example, and lets assume the table size is 8 slots. In Python 2.7, `hash('foo')` is `-4177197833195190597`, `hash('bar')` is `327024216814240868`. Modulo 8, that means these two keys are slotted in slots 3 and 4 then:
```
>>> hash('foo')
-4177197833195190597
>>> hash('foo') % 8
3
>>> hash('bar')
327024216814240868
>>> hash('bar') % 8
4
```
This informs their listing order:
```
>>> {'bar': None, 'foo': None}
{'foo': None, 'bar': None}
```
All slots except 3 and 4 are empty, looping over the table first lists slot 3, then slot 4, so `'foo'` is listed before `'bar'`.
`bar` and `baz`, however, have hash values that are exactly 8 apart and thus map to the exact same slot, `4`:
```
>>> hash('bar')
327024216814240868
>>> hash('baz')
327024216814240876
>>> hash('bar') % 8
4
>>> hash('baz') % 8
4
```
Their order now depends on which key was slotted first; the second key will have to be moved to a next slot:
```
>>> {'baz': None, 'bar': None}
{'bar': None, 'baz': None}
>>> {'bar': None, 'baz': None}
{'baz': None, 'bar': None}
```
The table order differs here, because one or the other key was slotted first.
The technical name for the underlying structure used by CPython (the most commonly used Python implemenation) is a [hash table](http://en.wikipedia.org/wiki/hash_table), one that uses open addressing. If you are curious, and understand C well enough, take a look at the [C implementation](http://hg.python.org/cpython/file/tip/Objects/dictobject.c) for all the (well documented) details. You could also watch this [Pycon 2010 presentation by Brandon Rhodes](http://pyvideo.org/video/276/the-mighty-dictionary-55) about how CPython `dict` works, or pick up a copy of [Beautiful Code](http://shop.oreilly.com/product/9780596510046.do), which includes a chapter on the implementation written by Andrew Kuchling.
Note that as of Python 3.3, a random hash seed is used as well, making hash collisions unpredictable to prevent certain types of denial of service (where an attacker renders a Python server unresponsive by causing mass hash collisions). This means that the order of a given dictionary or set is then *also* dependent on the random hash seed for the current Python invocation.
Other implementations are free to use a different structure for dictionaries, as long as they satisfy the documented Python interface for them, but I believe that all implementations so far use a variation of the hash table.
CPython 3.6 introduces a *new* `dict` implementation that maintains insertion order, and is faster and more memory efficient to boot. Rather than keep a large sparse table where each row references the stored hash value, and the key and value objects, the new implementation adds a smaller hash *array* that only references indices in a separate 'dense' table (one that only contains as many rows as there are actual key-value pairs), and it is the dense table that happens to list the contained items in order. See the [proposal to Python-Dev for more details](https://mail.python.org/pipermail/python-dev/2012-December/123028.html). Note that in Python 3.6 this is considered an *implementation detail*, Python-the-language does not specify that other implementations have to retain order. This changed in Python 3.7, where this detail was [elevated to be a *language specification*](https://mail.python.org/pipermail/python-dev/2017-December/151283.html); for any implementation to be properly compatible with Python 3.7 or newer it **must** copy this order-preserving behaviour. And to be explicit: this change doesn't apply to sets, as sets already have a 'small' hash structure.
Python 2.7 and newer also provides an [`OrderedDict` class](https://docs.python.org/2/library/collections.html#collections.OrderedDict), a subclass of `dict` that adds an additional data structure to record key order. At the price of some speed and extra memory, this class remembers in what order you inserted keys; listing keys, values or items will then do so in that order. It uses a doubly-linked list stored in an additional dictionary to keep the order up-to-date efficiently. See the [post by Raymond Hettinger outlining the idea](https://mail.python.org/pipermail/python-dev/2012-December/123028.html). `OrderedDict` objects have other advantages, such as being *re-orderable*.
If you wanted an ordered set, you can install the [`oset` package](https://pypi.python.org/pypi/oset); it works on Python 2.5 and up. | The other answers to this question are excellent and well written. The OP asks "how" which I interpret as "how do they get away with" or "why".
The Python documentation says [dictionaries](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) are not ordered because the Python dictionary implements the [abstract data type](http://en.wikipedia.org/wiki/Abstract_data_type) [associative array](http://en.wikipedia.org/wiki/Associative_array). As they say
>
> the order in which the bindings are returned may be arbitrary
>
>
>
In other words, a computer science student cannot assume that an associative array is ordered. The same is true for sets in [math](http://en.wikipedia.org/wiki/Set_(mathematics))
>
> the order in which the elements of a set are listed is irrelevant
>
>
>
and [computer science](http://en.wikipedia.org/wiki/Set_(computer_science))
>
> a set is an abstract data type that can store certain values, without any particular order
>
>
>
Implementing a dictionary using a hash table is an [implementation detail](https://hg.python.org/cpython/file/tip/Objects/dictobject.c) that is interesting in that it has the same properties as associative arrays as far as order is concerned. |
15,479,928 | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
What am I missing? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15479928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> **Note:** This answer was written before the implementation of the `dict` type changed, in Python 3.6. Most of the implementation details in this answer still apply, but the listing order of keys in *dictionaries* is no longer determined by hash values. The set implementation remains unchanged.
>
>
>
The order is not arbitrary, but depends on the insertion and deletion history of the dictionary or set, as well as on the specific Python implementation. For the remainder of this answer, for 'dictionary', you can also read 'set'; sets are implemented as dictionaries with just keys and no values.
Keys are hashed, and hash values are assigned to slots in a dynamic table (it can grow or shrink based on needs). And that mapping process can lead to collisions, meaning that a key will have to be slotted in a *next* slot based on what is already there.
Listing the contents loops over the slots, and so keys are listed in the order they *currently* reside in the table.
Take the keys `'foo'` and `'bar'`, for example, and lets assume the table size is 8 slots. In Python 2.7, `hash('foo')` is `-4177197833195190597`, `hash('bar')` is `327024216814240868`. Modulo 8, that means these two keys are slotted in slots 3 and 4 then:
```
>>> hash('foo')
-4177197833195190597
>>> hash('foo') % 8
3
>>> hash('bar')
327024216814240868
>>> hash('bar') % 8
4
```
This informs their listing order:
```
>>> {'bar': None, 'foo': None}
{'foo': None, 'bar': None}
```
All slots except 3 and 4 are empty, looping over the table first lists slot 3, then slot 4, so `'foo'` is listed before `'bar'`.
`bar` and `baz`, however, have hash values that are exactly 8 apart and thus map to the exact same slot, `4`:
```
>>> hash('bar')
327024216814240868
>>> hash('baz')
327024216814240876
>>> hash('bar') % 8
4
>>> hash('baz') % 8
4
```
Their order now depends on which key was slotted first; the second key will have to be moved to a next slot:
```
>>> {'baz': None, 'bar': None}
{'bar': None, 'baz': None}
>>> {'bar': None, 'baz': None}
{'baz': None, 'bar': None}
```
The table order differs here, because one or the other key was slotted first.
The technical name for the underlying structure used by CPython (the most commonly used Python implemenation) is a [hash table](http://en.wikipedia.org/wiki/hash_table), one that uses open addressing. If you are curious, and understand C well enough, take a look at the [C implementation](http://hg.python.org/cpython/file/tip/Objects/dictobject.c) for all the (well documented) details. You could also watch this [Pycon 2010 presentation by Brandon Rhodes](http://pyvideo.org/video/276/the-mighty-dictionary-55) about how CPython `dict` works, or pick up a copy of [Beautiful Code](http://shop.oreilly.com/product/9780596510046.do), which includes a chapter on the implementation written by Andrew Kuchling.
Note that as of Python 3.3, a random hash seed is used as well, making hash collisions unpredictable to prevent certain types of denial of service (where an attacker renders a Python server unresponsive by causing mass hash collisions). This means that the order of a given dictionary or set is then *also* dependent on the random hash seed for the current Python invocation.
Other implementations are free to use a different structure for dictionaries, as long as they satisfy the documented Python interface for them, but I believe that all implementations so far use a variation of the hash table.
CPython 3.6 introduces a *new* `dict` implementation that maintains insertion order, and is faster and more memory efficient to boot. Rather than keep a large sparse table where each row references the stored hash value, and the key and value objects, the new implementation adds a smaller hash *array* that only references indices in a separate 'dense' table (one that only contains as many rows as there are actual key-value pairs), and it is the dense table that happens to list the contained items in order. See the [proposal to Python-Dev for more details](https://mail.python.org/pipermail/python-dev/2012-December/123028.html). Note that in Python 3.6 this is considered an *implementation detail*, Python-the-language does not specify that other implementations have to retain order. This changed in Python 3.7, where this detail was [elevated to be a *language specification*](https://mail.python.org/pipermail/python-dev/2017-December/151283.html); for any implementation to be properly compatible with Python 3.7 or newer it **must** copy this order-preserving behaviour. And to be explicit: this change doesn't apply to sets, as sets already have a 'small' hash structure.
Python 2.7 and newer also provides an [`OrderedDict` class](https://docs.python.org/2/library/collections.html#collections.OrderedDict), a subclass of `dict` that adds an additional data structure to record key order. At the price of some speed and extra memory, this class remembers in what order you inserted keys; listing keys, values or items will then do so in that order. It uses a doubly-linked list stored in an additional dictionary to keep the order up-to-date efficiently. See the [post by Raymond Hettinger outlining the idea](https://mail.python.org/pipermail/python-dev/2012-December/123028.html). `OrderedDict` objects have other advantages, such as being *re-orderable*.
If you wanted an ordered set, you can install the [`oset` package](https://pypi.python.org/pypi/oset); it works on Python 2.5 and up. | Python use [**hash table**](http://en.wikipedia.org/wiki/Hash_table) for storing the dictionaries, so there is no order in dictionaries or other iterable objects that use hash table.
But regarding the indices of items in a hash object, python calculate the indices based on following code [within `hashtable.c`](https://hg.python.org/cpython/file/661cdbd617b8/Modules/hashtable.c#l317):
```
key_hash = ht->hash_func(key);
index = key_hash & (ht->num_buckets - 1);
```
Therefor, as the hash value of integers is the integer itself\* the index is based on the number (`ht->num_buckets - 1` is a constant) so the index calculated by *Bitwise-and* between `(ht->num_buckets - 1)` and the number itself\* (expect for -1 which it's hash is -2) , and for other objects with their hash value.
consider the following example with `set` that use hash-table :
```
>>> set([0,1919,2000,3,45,33,333,5])
set([0, 33, 3, 5, 45, 333, 2000, 1919])
```
For number `33` we have :
```
33 & (ht->num_buckets - 1) = 1
```
That actually it's :
```
'0b100001' & '0b111'= '0b1' # 1 the index of 33
```
*Note* in this case `(ht->num_buckets - 1)` is `8-1=7` or `0b111`.
And for `1919` :
```
'0b11101111111' & '0b111' = '0b111' # 7 the index of 1919
```
And for `333` :
```
'0b101001101' & '0b111' = '0b101' # 5 the index of 333
```
For more details about python hash function its good to read the following quotes from [python source code](https://hg.python.org/cpython/file/661cdbd617b8/Objects/dictobject.c#l106) :
>
> Major subtleties ahead: Most hash schemes depend on having a "good" hash
> function, in the sense of simulating randomness. Python doesn't: its most
> important hash functions (for strings and ints) are very regular in common
> cases:
>
>
>
> ```
> >>> map(hash, (0, 1, 2, 3))
> [0, 1, 2, 3]
> >>> map(hash, ("namea", "nameb", "namec", "named"))
> [-1658398457, -1658398460, -1658398459, -1658398462]
>
> ```
>
> This isn't necessarily bad! To the contrary, in a table of size 2\*\*i, taking
> the low-order i bits as the initial table index is extremely fast, and there
> are no collisions at all for dicts indexed by a contiguous range of ints.
> The same is approximately true when keys are "consecutive" strings. So this
> gives better-than-random behavior in common cases, and that's very desirable.
>
>
> OTOH, when collisions occur, the tendency to fill contiguous slices of the
> hash table makes a good collision resolution strategy crucial. Taking only
> the last i bits of the hash code is also vulnerable: for example, consider
> the list `[i << 16 for i in range(20000)]` as a set of keys. **Since ints are their own hash codes, and this fits in a dict of size 2\*\*15, the last 15 bits of every hash code are all 0: they *all* map to the same table index.**
>
>
> But catering to unusual cases should not slow the usual ones, so we just take
> the last i bits anyway. It's up to collision resolution to do the rest. If
> we *usually* find the key we're looking for on the first try (and, it turns
> out, we usually do -- the table load factor is kept under 2/3, so the odds
> are solidly in our favor), then it makes best sense to keep the initial index
> computation dirt cheap.
>
>
>
---
\* The hash function for class `int` :
```
class int:
def __hash__(self):
value = self
if value == -1:
value = -2
return value
``` |
15,479,928 | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
What am I missing? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15479928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This is more a response to [Python 3.41 A set](https://stackoverflow.com/questions/26098775/python-3-41-a-set) before it was closed as a duplicate.
---
The others are right: don't rely on the order. Don't even pretend there is one.
That said, there is *one* thing you can rely on:
```py
list(myset) == list(myset)
```
That is, the order is *stable*.
---
Understanding why there is a *perceived* order requires understanding a few things:
* That Python uses *hash sets*,
* How CPython's hash set is stored in memory and
* How numbers get hashed
From the top:
A *hash set* is a method of storing random data with really fast lookup times.
It has a backing array:
```none
# A C array; items may be NULL,
# a pointer to an object, or a
# special dummy object
_ _ 4 _ _ 2 _ _ 6
```
We shall ignore the special dummy object, which exists only to make removes easier to deal with, because we won't be removing from these sets.
In order to have really fast lookup, you do some magic to calculate a hash from an object. The only rule is that two objects which are equal have the same hash. (But if two objects have the same hash they can be unequal.)
You then make in index by taking the modulus by the array length:
```py
hash(4) % len(storage) = index 2
```
This makes it really fast to access elements.
Hashes are only most of the story, as `hash(n) % len(storage)` and `hash(m) % len(storage)` can result in the same number. In that case, several different strategies can try and resolve the conflict. [CPython uses "linear probing" 9 times](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L49) before doing pseudorandom probing, so it will look *to the right of the slot* for up to 9 places before looking elsewhere.
CPython's hash sets are stored like this:
* A hash set can be **no more than [60% full](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L175)** (*note:* this load factor was [previously 66%](https://github.com/python/cpython/commit/5cd87a8d61246b0a6233bfb8503d4718b693cef0) it was reduced in Python 3.7). If there are 20 elements and the backing array is 30 elements long, the backing store will resize to be larger. This is because you get collisions more often with small backing stores, and collisions slow everything down.
* When the backing store becomes too full, it will be automatically resized to increase the ratio of unused space (a higher ratio of unused space means it's faster to find a slot when handling a hash collision). For small sets, storage will be quadrupled in size, and for large sets (>50,000) it will be doubled in size [(source)](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L177).
So when you create an array the backing store is length 8. Once it is 4 full and you add an element, it will contain 5 elements. `5 > ³⁄₅·8` so this triggers a resize, and the backing store quadruples to size 32.
```py
>>> import sys
>>> s = set()
>>> for i in range(10):
... print(len(s), sys.getsizeof(s))
... s.add(i)
...
0 216
1 216
2 216
3 216
4 216
5 728
6 728
7 728
8 728
9 728
```
Finally, `hash(n)` just returns `n` for integers (except for `hash(-1)` which returns `-2` because the value [`-1` is reserved for another usage](https://github.com/python/cpython/blob/v3.11.0/Objects/object.c#L762-L768)).
---
So, let's look at the first one:
```py
v_set = {88,11,1,33,21,3,7,55,37,8}
```
`len(v_set)` is 10, so the backing store is at least 15(+1) **after all items have been added**. The relevant power of 2 is 32. So the backing store is:
```none
__ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
```
We have
```py
hash(88) % 32 = 24
hash(11) % 32 = 11
hash(1) % 32 = 1
hash(33) % 32 = 1
hash(21) % 32 = 21
hash(3) % 32 = 3
hash(7) % 32 = 7
hash(55) % 32 = 23
hash(37) % 32 = 5
hash(8) % 32 = 8
```
so these insert as:
```none
__ 1 __ 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
33 ← Can't also be where 1 is;
either 1 or 33 has to move
```
So we would expect an order like
```py
{[1 or 33], 3, 37, 7, 8, 11, 21, 55, 88}
```
with the 1 or 33 that isn't at the start somewhere else. This will use linear probing, so we will either have:
```none
↓
__ 1 33 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
```
or
```none
↓
__ 33 1 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
```
You might expect the 33 to be the one that's displaced because the 1 was already there, but due to the resizing that happens as the set is being built, this isn't actually the case. Every time the set gets rebuilt, the items already added are effectively reordered.
Now you can see why
```py
{7,5,11,1,4,13,55,12,2,3,6,20,9,10}
```
might be in order. There are 14 elements, so the backing store is at least 21+1, which means 32:
```none
__ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
```
1 to 13 hash in the first 13 slots. 20 goes in slot 20.
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ __ __ 20 __ __ __ __ __ __ __ __ __ __ __
```
55 goes in slot `hash(55) % 32` which is 23:
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ __ __ 20 __ __ 55 __ __ __ __ __ __ __ __
```
If we chose 50 instead, we'd expect
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ 50 __ 20 __ __ __ __ __ __ __ __ __ __ __
```
And lo and behold:
```py
>>> {1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 20, 50}
{1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 50, 20}
```
---
`pop` is [implemented](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L629-L652) quite simply by the looks of things: it traverses the underlying array and pops the first element, skipping over unused slots and "dummy" entries (tombstone markers from removed elements).
---
### This is all implementation detail. | "Arbitrary" isn't the same thing as "non-determined".
What they're saying is that there are no useful properties of dictionary iteration order that are "in the public interface". There almost certainly are many properties of the iteration order that are fully determined by the code that currently implements dictionary iteration, but the authors aren't promising them to you as something you can use. This gives them more freedom to change these properties between Python versions (or even just in different operating conditions, or completely at random at runtime) without worrying that your program will break.
Thus if you write a program that depends on *any property at all* of dictionary order, then you are "breaking the contract" of using the dictionary type, and the Python developers are not promising that this will always work, even if it appears to work for now when you test it. It's basically the equivalent of relying on "undefined behaviour" in C. |
15,479,928 | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
What am I missing? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15479928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | "Arbitrary" isn't the same thing as "non-determined".
What they're saying is that there are no useful properties of dictionary iteration order that are "in the public interface". There almost certainly are many properties of the iteration order that are fully determined by the code that currently implements dictionary iteration, but the authors aren't promising them to you as something you can use. This gives them more freedom to change these properties between Python versions (or even just in different operating conditions, or completely at random at runtime) without worrying that your program will break.
Thus if you write a program that depends on *any property at all* of dictionary order, then you are "breaking the contract" of using the dictionary type, and the Python developers are not promising that this will always work, even if it appears to work for now when you test it. It's basically the equivalent of relying on "undefined behaviour" in C. | The other answers to this question are excellent and well written. The OP asks "how" which I interpret as "how do they get away with" or "why".
The Python documentation says [dictionaries](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) are not ordered because the Python dictionary implements the [abstract data type](http://en.wikipedia.org/wiki/Abstract_data_type) [associative array](http://en.wikipedia.org/wiki/Associative_array). As they say
>
> the order in which the bindings are returned may be arbitrary
>
>
>
In other words, a computer science student cannot assume that an associative array is ordered. The same is true for sets in [math](http://en.wikipedia.org/wiki/Set_(mathematics))
>
> the order in which the elements of a set are listed is irrelevant
>
>
>
and [computer science](http://en.wikipedia.org/wiki/Set_(computer_science))
>
> a set is an abstract data type that can store certain values, without any particular order
>
>
>
Implementing a dictionary using a hash table is an [implementation detail](https://hg.python.org/cpython/file/tip/Objects/dictobject.c) that is interesting in that it has the same properties as associative arrays as far as order is concerned. |
15,479,928 | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
What am I missing? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15479928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | "Arbitrary" isn't the same thing as "non-determined".
What they're saying is that there are no useful properties of dictionary iteration order that are "in the public interface". There almost certainly are many properties of the iteration order that are fully determined by the code that currently implements dictionary iteration, but the authors aren't promising them to you as something you can use. This gives them more freedom to change these properties between Python versions (or even just in different operating conditions, or completely at random at runtime) without worrying that your program will break.
Thus if you write a program that depends on *any property at all* of dictionary order, then you are "breaking the contract" of using the dictionary type, and the Python developers are not promising that this will always work, even if it appears to work for now when you test it. It's basically the equivalent of relying on "undefined behaviour" in C. | Python use [**hash table**](http://en.wikipedia.org/wiki/Hash_table) for storing the dictionaries, so there is no order in dictionaries or other iterable objects that use hash table.
But regarding the indices of items in a hash object, python calculate the indices based on following code [within `hashtable.c`](https://hg.python.org/cpython/file/661cdbd617b8/Modules/hashtable.c#l317):
```
key_hash = ht->hash_func(key);
index = key_hash & (ht->num_buckets - 1);
```
Therefor, as the hash value of integers is the integer itself\* the index is based on the number (`ht->num_buckets - 1` is a constant) so the index calculated by *Bitwise-and* between `(ht->num_buckets - 1)` and the number itself\* (expect for -1 which it's hash is -2) , and for other objects with their hash value.
consider the following example with `set` that use hash-table :
```
>>> set([0,1919,2000,3,45,33,333,5])
set([0, 33, 3, 5, 45, 333, 2000, 1919])
```
For number `33` we have :
```
33 & (ht->num_buckets - 1) = 1
```
That actually it's :
```
'0b100001' & '0b111'= '0b1' # 1 the index of 33
```
*Note* in this case `(ht->num_buckets - 1)` is `8-1=7` or `0b111`.
And for `1919` :
```
'0b11101111111' & '0b111' = '0b111' # 7 the index of 1919
```
And for `333` :
```
'0b101001101' & '0b111' = '0b101' # 5 the index of 333
```
For more details about python hash function its good to read the following quotes from [python source code](https://hg.python.org/cpython/file/661cdbd617b8/Objects/dictobject.c#l106) :
>
> Major subtleties ahead: Most hash schemes depend on having a "good" hash
> function, in the sense of simulating randomness. Python doesn't: its most
> important hash functions (for strings and ints) are very regular in common
> cases:
>
>
>
> ```
> >>> map(hash, (0, 1, 2, 3))
> [0, 1, 2, 3]
> >>> map(hash, ("namea", "nameb", "namec", "named"))
> [-1658398457, -1658398460, -1658398459, -1658398462]
>
> ```
>
> This isn't necessarily bad! To the contrary, in a table of size 2\*\*i, taking
> the low-order i bits as the initial table index is extremely fast, and there
> are no collisions at all for dicts indexed by a contiguous range of ints.
> The same is approximately true when keys are "consecutive" strings. So this
> gives better-than-random behavior in common cases, and that's very desirable.
>
>
> OTOH, when collisions occur, the tendency to fill contiguous slices of the
> hash table makes a good collision resolution strategy crucial. Taking only
> the last i bits of the hash code is also vulnerable: for example, consider
> the list `[i << 16 for i in range(20000)]` as a set of keys. **Since ints are their own hash codes, and this fits in a dict of size 2\*\*15, the last 15 bits of every hash code are all 0: they *all* map to the same table index.**
>
>
> But catering to unusual cases should not slow the usual ones, so we just take
> the last i bits anyway. It's up to collision resolution to do the rest. If
> we *usually* find the key we're looking for on the first try (and, it turns
> out, we usually do -- the table load factor is kept under 2/3, so the odds
> are solidly in our favor), then it makes best sense to keep the initial index
> computation dirt cheap.
>
>
>
---
\* The hash function for class `int` :
```
class int:
def __hash__(self):
value = self
if value == -1:
value = -2
return value
``` |
15,479,928 | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
What am I missing? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15479928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This is more a response to [Python 3.41 A set](https://stackoverflow.com/questions/26098775/python-3-41-a-set) before it was closed as a duplicate.
---
The others are right: don't rely on the order. Don't even pretend there is one.
That said, there is *one* thing you can rely on:
```py
list(myset) == list(myset)
```
That is, the order is *stable*.
---
Understanding why there is a *perceived* order requires understanding a few things:
* That Python uses *hash sets*,
* How CPython's hash set is stored in memory and
* How numbers get hashed
From the top:
A *hash set* is a method of storing random data with really fast lookup times.
It has a backing array:
```none
# A C array; items may be NULL,
# a pointer to an object, or a
# special dummy object
_ _ 4 _ _ 2 _ _ 6
```
We shall ignore the special dummy object, which exists only to make removes easier to deal with, because we won't be removing from these sets.
In order to have really fast lookup, you do some magic to calculate a hash from an object. The only rule is that two objects which are equal have the same hash. (But if two objects have the same hash they can be unequal.)
You then make in index by taking the modulus by the array length:
```py
hash(4) % len(storage) = index 2
```
This makes it really fast to access elements.
Hashes are only most of the story, as `hash(n) % len(storage)` and `hash(m) % len(storage)` can result in the same number. In that case, several different strategies can try and resolve the conflict. [CPython uses "linear probing" 9 times](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L49) before doing pseudorandom probing, so it will look *to the right of the slot* for up to 9 places before looking elsewhere.
CPython's hash sets are stored like this:
* A hash set can be **no more than [60% full](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L175)** (*note:* this load factor was [previously 66%](https://github.com/python/cpython/commit/5cd87a8d61246b0a6233bfb8503d4718b693cef0) it was reduced in Python 3.7). If there are 20 elements and the backing array is 30 elements long, the backing store will resize to be larger. This is because you get collisions more often with small backing stores, and collisions slow everything down.
* When the backing store becomes too full, it will be automatically resized to increase the ratio of unused space (a higher ratio of unused space means it's faster to find a slot when handling a hash collision). For small sets, storage will be quadrupled in size, and for large sets (>50,000) it will be doubled in size [(source)](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L177).
So when you create an array the backing store is length 8. Once it is 4 full and you add an element, it will contain 5 elements. `5 > ³⁄₅·8` so this triggers a resize, and the backing store quadruples to size 32.
```py
>>> import sys
>>> s = set()
>>> for i in range(10):
... print(len(s), sys.getsizeof(s))
... s.add(i)
...
0 216
1 216
2 216
3 216
4 216
5 728
6 728
7 728
8 728
9 728
```
Finally, `hash(n)` just returns `n` for integers (except for `hash(-1)` which returns `-2` because the value [`-1` is reserved for another usage](https://github.com/python/cpython/blob/v3.11.0/Objects/object.c#L762-L768)).
---
So, let's look at the first one:
```py
v_set = {88,11,1,33,21,3,7,55,37,8}
```
`len(v_set)` is 10, so the backing store is at least 15(+1) **after all items have been added**. The relevant power of 2 is 32. So the backing store is:
```none
__ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
```
We have
```py
hash(88) % 32 = 24
hash(11) % 32 = 11
hash(1) % 32 = 1
hash(33) % 32 = 1
hash(21) % 32 = 21
hash(3) % 32 = 3
hash(7) % 32 = 7
hash(55) % 32 = 23
hash(37) % 32 = 5
hash(8) % 32 = 8
```
so these insert as:
```none
__ 1 __ 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
33 ← Can't also be where 1 is;
either 1 or 33 has to move
```
So we would expect an order like
```py
{[1 or 33], 3, 37, 7, 8, 11, 21, 55, 88}
```
with the 1 or 33 that isn't at the start somewhere else. This will use linear probing, so we will either have:
```none
↓
__ 1 33 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
```
or
```none
↓
__ 33 1 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
```
You might expect the 33 to be the one that's displaced because the 1 was already there, but due to the resizing that happens as the set is being built, this isn't actually the case. Every time the set gets rebuilt, the items already added are effectively reordered.
Now you can see why
```py
{7,5,11,1,4,13,55,12,2,3,6,20,9,10}
```
might be in order. There are 14 elements, so the backing store is at least 21+1, which means 32:
```none
__ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
```
1 to 13 hash in the first 13 slots. 20 goes in slot 20.
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ __ __ 20 __ __ __ __ __ __ __ __ __ __ __
```
55 goes in slot `hash(55) % 32` which is 23:
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ __ __ 20 __ __ 55 __ __ __ __ __ __ __ __
```
If we chose 50 instead, we'd expect
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ 50 __ 20 __ __ __ __ __ __ __ __ __ __ __
```
And lo and behold:
```py
>>> {1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 20, 50}
{1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 50, 20}
```
---
`pop` is [implemented](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L629-L652) quite simply by the looks of things: it traverses the underlying array and pops the first element, skipping over unused slots and "dummy" entries (tombstone markers from removed elements).
---
### This is all implementation detail. | The other answers to this question are excellent and well written. The OP asks "how" which I interpret as "how do they get away with" or "why".
The Python documentation says [dictionaries](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) are not ordered because the Python dictionary implements the [abstract data type](http://en.wikipedia.org/wiki/Abstract_data_type) [associative array](http://en.wikipedia.org/wiki/Associative_array). As they say
>
> the order in which the bindings are returned may be arbitrary
>
>
>
In other words, a computer science student cannot assume that an associative array is ordered. The same is true for sets in [math](http://en.wikipedia.org/wiki/Set_(mathematics))
>
> the order in which the elements of a set are listed is irrelevant
>
>
>
and [computer science](http://en.wikipedia.org/wiki/Set_(computer_science))
>
> a set is an abstract data type that can store certain values, without any particular order
>
>
>
Implementing a dictionary using a hash table is an [implementation detail](https://hg.python.org/cpython/file/tip/Objects/dictobject.c) that is interesting in that it has the same properties as associative arrays as far as order is concerned. |
15,479,928 | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
What am I missing? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15479928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This is more a response to [Python 3.41 A set](https://stackoverflow.com/questions/26098775/python-3-41-a-set) before it was closed as a duplicate.
---
The others are right: don't rely on the order. Don't even pretend there is one.
That said, there is *one* thing you can rely on:
```py
list(myset) == list(myset)
```
That is, the order is *stable*.
---
Understanding why there is a *perceived* order requires understanding a few things:
* That Python uses *hash sets*,
* How CPython's hash set is stored in memory and
* How numbers get hashed
From the top:
A *hash set* is a method of storing random data with really fast lookup times.
It has a backing array:
```none
# A C array; items may be NULL,
# a pointer to an object, or a
# special dummy object
_ _ 4 _ _ 2 _ _ 6
```
We shall ignore the special dummy object, which exists only to make removes easier to deal with, because we won't be removing from these sets.
In order to have really fast lookup, you do some magic to calculate a hash from an object. The only rule is that two objects which are equal have the same hash. (But if two objects have the same hash they can be unequal.)
You then make in index by taking the modulus by the array length:
```py
hash(4) % len(storage) = index 2
```
This makes it really fast to access elements.
Hashes are only most of the story, as `hash(n) % len(storage)` and `hash(m) % len(storage)` can result in the same number. In that case, several different strategies can try and resolve the conflict. [CPython uses "linear probing" 9 times](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L49) before doing pseudorandom probing, so it will look *to the right of the slot* for up to 9 places before looking elsewhere.
CPython's hash sets are stored like this:
* A hash set can be **no more than [60% full](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L175)** (*note:* this load factor was [previously 66%](https://github.com/python/cpython/commit/5cd87a8d61246b0a6233bfb8503d4718b693cef0) it was reduced in Python 3.7). If there are 20 elements and the backing array is 30 elements long, the backing store will resize to be larger. This is because you get collisions more often with small backing stores, and collisions slow everything down.
* When the backing store becomes too full, it will be automatically resized to increase the ratio of unused space (a higher ratio of unused space means it's faster to find a slot when handling a hash collision). For small sets, storage will be quadrupled in size, and for large sets (>50,000) it will be doubled in size [(source)](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L177).
So when you create an array the backing store is length 8. Once it is 4 full and you add an element, it will contain 5 elements. `5 > ³⁄₅·8` so this triggers a resize, and the backing store quadruples to size 32.
```py
>>> import sys
>>> s = set()
>>> for i in range(10):
... print(len(s), sys.getsizeof(s))
... s.add(i)
...
0 216
1 216
2 216
3 216
4 216
5 728
6 728
7 728
8 728
9 728
```
Finally, `hash(n)` just returns `n` for integers (except for `hash(-1)` which returns `-2` because the value [`-1` is reserved for another usage](https://github.com/python/cpython/blob/v3.11.0/Objects/object.c#L762-L768)).
---
So, let's look at the first one:
```py
v_set = {88,11,1,33,21,3,7,55,37,8}
```
`len(v_set)` is 10, so the backing store is at least 15(+1) **after all items have been added**. The relevant power of 2 is 32. So the backing store is:
```none
__ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
```
We have
```py
hash(88) % 32 = 24
hash(11) % 32 = 11
hash(1) % 32 = 1
hash(33) % 32 = 1
hash(21) % 32 = 21
hash(3) % 32 = 3
hash(7) % 32 = 7
hash(55) % 32 = 23
hash(37) % 32 = 5
hash(8) % 32 = 8
```
so these insert as:
```none
__ 1 __ 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
33 ← Can't also be where 1 is;
either 1 or 33 has to move
```
So we would expect an order like
```py
{[1 or 33], 3, 37, 7, 8, 11, 21, 55, 88}
```
with the 1 or 33 that isn't at the start somewhere else. This will use linear probing, so we will either have:
```none
↓
__ 1 33 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
```
or
```none
↓
__ 33 1 3 __ 37 __ 7 8 __ __ 11 __ __ __ __ __ __ __ __ __ 21 __ 55 88 __ __ __ __ __ __ __
```
You might expect the 33 to be the one that's displaced because the 1 was already there, but due to the resizing that happens as the set is being built, this isn't actually the case. Every time the set gets rebuilt, the items already added are effectively reordered.
Now you can see why
```py
{7,5,11,1,4,13,55,12,2,3,6,20,9,10}
```
might be in order. There are 14 elements, so the backing store is at least 21+1, which means 32:
```none
__ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
```
1 to 13 hash in the first 13 slots. 20 goes in slot 20.
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ __ __ 20 __ __ __ __ __ __ __ __ __ __ __
```
55 goes in slot `hash(55) % 32` which is 23:
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ __ __ 20 __ __ 55 __ __ __ __ __ __ __ __
```
If we chose 50 instead, we'd expect
```none
__ 1 2 3 4 5 6 7 8 9 10 11 12 13 __ __ __ __ 50 __ 20 __ __ __ __ __ __ __ __ __ __ __
```
And lo and behold:
```py
>>> {1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 20, 50}
{1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 50, 20}
```
---
`pop` is [implemented](https://github.com/python/cpython/blob/v3.11.0/Objects/setobject.c#L629-L652) quite simply by the looks of things: it traverses the underlying array and pops the first element, skipping over unused slots and "dummy" entries (tombstone markers from removed elements).
---
### This is all implementation detail. | Python use [**hash table**](http://en.wikipedia.org/wiki/Hash_table) for storing the dictionaries, so there is no order in dictionaries or other iterable objects that use hash table.
But regarding the indices of items in a hash object, python calculate the indices based on following code [within `hashtable.c`](https://hg.python.org/cpython/file/661cdbd617b8/Modules/hashtable.c#l317):
```
key_hash = ht->hash_func(key);
index = key_hash & (ht->num_buckets - 1);
```
Therefor, as the hash value of integers is the integer itself\* the index is based on the number (`ht->num_buckets - 1` is a constant) so the index calculated by *Bitwise-and* between `(ht->num_buckets - 1)` and the number itself\* (expect for -1 which it's hash is -2) , and for other objects with their hash value.
consider the following example with `set` that use hash-table :
```
>>> set([0,1919,2000,3,45,33,333,5])
set([0, 33, 3, 5, 45, 333, 2000, 1919])
```
For number `33` we have :
```
33 & (ht->num_buckets - 1) = 1
```
That actually it's :
```
'0b100001' & '0b111'= '0b1' # 1 the index of 33
```
*Note* in this case `(ht->num_buckets - 1)` is `8-1=7` or `0b111`.
And for `1919` :
```
'0b11101111111' & '0b111' = '0b111' # 7 the index of 1919
```
And for `333` :
```
'0b101001101' & '0b111' = '0b101' # 5 the index of 333
```
For more details about python hash function its good to read the following quotes from [python source code](https://hg.python.org/cpython/file/661cdbd617b8/Objects/dictobject.c#l106) :
>
> Major subtleties ahead: Most hash schemes depend on having a "good" hash
> function, in the sense of simulating randomness. Python doesn't: its most
> important hash functions (for strings and ints) are very regular in common
> cases:
>
>
>
> ```
> >>> map(hash, (0, 1, 2, 3))
> [0, 1, 2, 3]
> >>> map(hash, ("namea", "nameb", "namec", "named"))
> [-1658398457, -1658398460, -1658398459, -1658398462]
>
> ```
>
> This isn't necessarily bad! To the contrary, in a table of size 2\*\*i, taking
> the low-order i bits as the initial table index is extremely fast, and there
> are no collisions at all for dicts indexed by a contiguous range of ints.
> The same is approximately true when keys are "consecutive" strings. So this
> gives better-than-random behavior in common cases, and that's very desirable.
>
>
> OTOH, when collisions occur, the tendency to fill contiguous slices of the
> hash table makes a good collision resolution strategy crucial. Taking only
> the last i bits of the hash code is also vulnerable: for example, consider
> the list `[i << 16 for i in range(20000)]` as a set of keys. **Since ints are their own hash codes, and this fits in a dict of size 2\*\*15, the last 15 bits of every hash code are all 0: they *all* map to the same table index.**
>
>
> But catering to unusual cases should not slow the usual ones, so we just take
> the last i bits anyway. It's up to collision resolution to do the rest. If
> we *usually* find the key we're looking for on the first try (and, it turns
> out, we usually do -- the table load factor is kept under 2/3, so the odds
> are solidly in our favor), then it makes best sense to keep the initial index
> computation dirt cheap.
>
>
>
---
\* The hash function for class `int` :
```
class int:
def __hash__(self):
value = self
if value == -1:
value = -2
return value
``` |
44,285,118 | Here is my code:
```
for x in stem:
stem[stem.index(x+1)] = "Four"
print(x)
```
The problem begins when i design an algorithm (on paper) based on special (and strongly wrong) assumption and when i start coding in python, problem appears
Consider that `x` contains `["One" , "Two", "Three"]` at start moment (get from `stem`).
I want to impress `x` on for next iteration after first iteration. i want below result:
```
One
Four
Four
```
not this result which happens:
```
One
Two
Three
``` | 2017/05/31 | [
"https://Stackoverflow.com/questions/44285118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5738909/"
] | Frédéric, your best option would be to install using yum by running the following:
>
> yum install -y MarkLogic-9.0-1.1.x86\_64.rpm
>
>
>
This will automatically go through the dependencies and install those as well for you. | Both the 64 bit and 32 bit versions of glibc need to be installed. I think this may also be the case for some of the 8.0-5.x & 8.0-6.x versions (or at least that's the other times I have seen this behavior).
This related question should point you in the right direction for installing the libraries.
[Install 32 bit glibc on 64 bit CentOS 6](https://stackoverflow.com/questions/38217355/install-32-bit-glibc-on-64-bit-centos-6) |
44,285,118 | Here is my code:
```
for x in stem:
stem[stem.index(x+1)] = "Four"
print(x)
```
The problem begins when i design an algorithm (on paper) based on special (and strongly wrong) assumption and when i start coding in python, problem appears
Consider that `x` contains `["One" , "Two", "Three"]` at start moment (get from `stem`).
I want to impress `x` on for next iteration after first iteration. i want below result:
```
One
Four
Four
```
not this result which happens:
```
One
Two
Three
``` | 2017/05/31 | [
"https://Stackoverflow.com/questions/44285118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5738909/"
] | Frédéric, your best option would be to install using yum by running the following:
>
> yum install -y MarkLogic-9.0-1.1.x86\_64.rpm
>
>
>
This will automatically go through the dependencies and install those as well for you. | The [install guide mentions a number of libraries](http://docs.marklogic.com/guide/installation/intro#id_63469) that need to be installed upfront (pay attention to the footnotes). glibc is one of them. As mentioned in this [SO answer](https://stackoverflow.com/a/28703744/918496) you can install those dependencies using yum. That answer talks about RedHat/CentOS 6, but it works for 7 too:
```
yum -y install glibc.i686 gdb.x86_64 redhat-lsb.x86_64 cyrus-sasl cyrus-sasl-lib cyrus-sasl-md5
```
See also: <https://github.com/grtjn/mlvagrant/blob/master/opt/vagrant/install-ml-centos.sh#L17>
HTH! |
44,285,118 | Here is my code:
```
for x in stem:
stem[stem.index(x+1)] = "Four"
print(x)
```
The problem begins when i design an algorithm (on paper) based on special (and strongly wrong) assumption and when i start coding in python, problem appears
Consider that `x` contains `["One" , "Two", "Three"]` at start moment (get from `stem`).
I want to impress `x` on for next iteration after first iteration. i want below result:
```
One
Four
Four
```
not this result which happens:
```
One
Two
Three
``` | 2017/05/31 | [
"https://Stackoverflow.com/questions/44285118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5738909/"
] | The [install guide mentions a number of libraries](http://docs.marklogic.com/guide/installation/intro#id_63469) that need to be installed upfront (pay attention to the footnotes). glibc is one of them. As mentioned in this [SO answer](https://stackoverflow.com/a/28703744/918496) you can install those dependencies using yum. That answer talks about RedHat/CentOS 6, but it works for 7 too:
```
yum -y install glibc.i686 gdb.x86_64 redhat-lsb.x86_64 cyrus-sasl cyrus-sasl-lib cyrus-sasl-md5
```
See also: <https://github.com/grtjn/mlvagrant/blob/master/opt/vagrant/install-ml-centos.sh#L17>
HTH! | Both the 64 bit and 32 bit versions of glibc need to be installed. I think this may also be the case for some of the 8.0-5.x & 8.0-6.x versions (or at least that's the other times I have seen this behavior).
This related question should point you in the right direction for installing the libraries.
[Install 32 bit glibc on 64 bit CentOS 6](https://stackoverflow.com/questions/38217355/install-32-bit-glibc-on-64-bit-centos-6) |
59,647,987 | i have Dictionary like this:
```
d={(('4', '2'), ('2', '0')): [3], (('4', '2'), ('2', '1')): [3], (('4', '2'), ('2', '3')): [1], (('4', '2'), ('2', '4')): [71]}
```
my target is to get the probability of some special key, for example, I need the probability of `('4', '2'), ('2', '1')`, which is 3/(3+3+1+71)=3/78, but how can I write this method in python?
i have some idea like this:
```
p={}
for i,j in d.keys():
p[i,j]=d[i,j][0]/sum(d[i][0])
```
but it didn't work, because d[I] is not right.
update:
the question has been well solved with some nice answers. Now I want to ask about how to do calculations along a path in a tree that shown in the picture[the picture describes the transitions between states](https://i.stack.imgur.com/zVHus.png), and I want to find the time needed from every state to the red states.
every path in this tree has two values, for example [6,109.0], 109.0 is the time from ('4','1') to ('1','0'), and on this path, from ('4')->('4','1')->('1','0') is 10.0+109.0=119.0, so the question is how to get the time from current state to the red state?
the transitions between them could be written like this:
states\_agg={((), ('2',)): [1, 0.0], (('0', '1'), ('1', '4')): [1, 10.0], (('0', '2'), ('2', '0')): [2, 10.0], (('0', '2'), ('2', '4')): [1, 159.0], (('0', '4'), ('4', '0')): [26, 13.26923076923077],
(('0', '4'), ('4', '2')): [2, 10.5],(('1', '2'), ('2', '4')): [4, 71.5], (('1', '4'), ('4', '1')): [3, 10.333333333333334], (('2',), ('2', '0')): [1, 10.0], (('2', '0'), ('0', '2')): [1, 42.0],
(('2', '0'), ('0', '4')): [6, 109.0], (('2', '1'), ('1', '2')): [3, 43.0], (('2', '3'), ('3', '2')): [1, 860.0],(('2', '4'), ('4', '2')): [76, -223.8815789473684],(('3', '2'), ('2', '0')): [1, 11.0],
(('4', '0'), ('0', '1')): [1, 507.0], (('4', '0'), ('0', '2')): [2, 69.5],(('4', '0'), ('0', '4')): [23, 200.17391304347825],(('4', '1'), ('1', '2')): [1, 95.0],(('4', '1'), ('1', '4')): [2, 1447.0],
(('4', '2'), ('2', '0')): [3, 28.666666666666668] (('4', '2'), ('2', '1'))[3,132.66666666666666], (('4', '2'), ('2', '3')): [1, 64.0],(('4', '2'), ('2', '4')): [71,79.09859154929578]}
for example from ('4', '2') to ('2', '4') the transition time is 79.09859154929578 | 2020/01/08 | [
"https://Stackoverflow.com/questions/59647987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12675949/"
] | Do you want something like the following?
```
d={(('4', '2'), ('2', '0')): [3],
(('4', '2'), ('2', '1')): [3],
(('4', '2'), ('2', '3')): [1],
(('4', '2'), ('2', '4')): [71]}
s = sum(v[0] for v in d.values())
p = {k: v[0]/s for k, v in d.items()}
```
This gives us:
```
>>> p
{(('4', '2'), ('2', '0')): 0.038461538461538464,
(('4', '2'), ('2', '1')): 0.038461538461538464,
(('4', '2'), ('2', '3')): 0.01282051282051282,
(('4', '2'), ('2', '4')): 0.9102564102564102}
```
Answering question from comments - how can I get the probability of keys begin with ('4', '1') with `d` as below:
```
d={(('4', '2'), ('2', '0')): [3], (('4', '2'), ('2', '1')): [3], (('4', '2'), ('2', '3')): [1], (('4', '2'), ('2', '4')): [71], (('4', '1'), ('1', '2')): [1], (('4', '1'), ('1', '4')): [2],}
```
Then we can just use a list comprehension on `p`:
```
>>> [v for k, v in p.items() if k[0] == ('4', '1')]
[0.012345679012345678, 0.024691358024691357]
```
And if we want the total probability of those keys:
```
>>> sum(v for k, v in p.items() if k[0] == ('4', '1'))
0.037037037037037035
``` | The [answer](https://stackoverflow.com/a/59648064/6529697) by CDJB may be what you are after.
However if your dictionary ever has keys in it for which you don't wish to use in calculating the probability (which your `d[i]` seems to imply) you will need to make some tweaks:
```
def get_prob_from_key(mykey, dikt):
numer = dikt.get(mykey)
if numer is None:
print(f"Key {mykey} not found! Can't calculate probability")
return None
denom = sum(v[0] for k, v in d.items() if mykey[0] == k[0])
return numer[0]/denom
d={(('4', '2'), ('2', '0')): [3], (('4', '2'), ('2', '1')): [3], (('4', '2'), ('2', '3')): [1], (('4', '2'), ('2', '4')): [71], (('4', '1'), ('1', '2')): [1], (('4', '1'), ('1', '4')): [2],}
k1 = (('4', '2'), ('2', '1'))
k2 = (('4', '2'), ('2', '4'))
k3 = (('5', '2'), ('2', '1'))
k4 = (('4', '1'), ('1', '2'))
get_prob_from_key(k1, d)
> 0.038461538461538464
get_prob_from_key(k2, d)
> 0.9102564102564102
get_prob_from_key(k3, d)
> Key (('5', '2'), ('2', '1')) not found! Can't calculate probability
get_prob_from_key(k4, d)
> 0.3333333333333333
```
A caveat:
This assumes that, like your current dictionary input, all values are lists of length 1. If that's not always the case then a change will need to be made. |
57,798,033 | ```
ValueError Traceback (most recent call last)
<ipython-input-30-33821ccddf5f> in <module>
23 output = model(data)
24 # calculate the batch loss
---> 25 loss = criterion(output, target)
26 # backward pass: compute gradient of the loss with respect to model parameters
27 loss.backward()
C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
487 result = self._slow_forward(*input, **kwargs)
488 else:
--> 489 result = self.forward(*input, **kwargs)
490 for hook in self._forward_hooks.values():
491 hook_result = hook(self, input, result)
C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target)
593 self.weight,
594 pos_weight=self.pos_weight,
--> 595 reduction=self.reduction)
596
597
C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight)
2073
2074 if not (target.size() == input.size()):
-> 2075 raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size()))
2076
2077 return torch.binary_cross_entropy_with_logits(input, target, weight, pos_weight, reduction_enum)
ValueError: Target size (torch.Size([16])) must be the same as input size (torch.Size([16, 1]))
```
I am training a CNN. Working on the Horses vs humans dataset. [This is my code](https://github.com/mnauf/horses_humans/blob/master/Untitled.ipynb). I am using `criterion = nn.BCEWithLogitsLoss()` and `optimizer = optim.RMSprop(model.parameters(), lr=0.01`). My final layer is `self.fc2 = nn.Linear(512, 1)`. Out last neuron, will output 1 for horse and 0 for human, right? or should I choose 2 neurons for output?
`16` is the batch size. Since the error says `ValueError: Target size (torch.Size([16])) must be the same as input size (torch.Size([16, 1]))`. I don't understand, where do I need to make change, to rectify the error. | 2019/09/05 | [
"https://Stackoverflow.com/questions/57798033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10240085/"
] | `target = target.unsqueeze(1)`, before passing target to criterion, changed the target tensor size from `[16]` to `[16,1]`. Doing it solved the issue. Furthermore, I also needed to do `target = target.float()` before passing it to criterion, because our outputs are in float. Besides, there was another error in the code. I was using sigmoid activation function in the last layer, but I shouldn’t because the criterion I am using already comes with sigmoid builtin. | You can also try `_, pred = torch.max(output, 1)` and then pass the `pred` variable into Loss function. |
2,076,606 | I'm trying to get some python code I've written earlier on Windows to work on my DS. I'm using ([DSPython](https://www.develer.com/trac/dspython/)), and when I tried to import math, it failed with "ImportError: No module named math". I've gotten most all other modules I need that don't rely on math working. But math is normally a builtin module, so I can't just find math.py on my PC and copy it over. Any suggestions on where I can find an alternative to the builtin math module that can still perform the same functions? | 2010/01/16 | [
"https://Stackoverflow.com/questions/2076606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216292/"
] | Last month [dspython](https://www.develer.com/trac/dspython/) has been given an overall project cleanup, and several issues, including the one you mention, were addressed in the process.
If you're still interested in running that Python code in your DS, this is a good time to try again. A contributor has also written some small example programs, that are good starting points for you to use - they also can give you an idea of what's implemented so far. | Your best bet would be to wrap the NDS c library with pyrex, and create your own math module. The rest of dspython is. |
41,561,388 | I want to have few global variables in my python code.
Then set their values with set function and want to get their values through get function.
For example:
```
a = None #global variable1
b= None #global variable2
def set(var, value):
var = value
def get(var):
return var
set(a, '1')
get(b, '2')
```
I want to have a generic get and set function which will do this for any global variable. How can I do this in python ? The code written here gives error. | 2017/01/10 | [
"https://Stackoverflow.com/questions/41561388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7349246/"
] | ```
for($i = 0; $i < count($users_array); $i++){
for($j = 0; $j < count($users_array[$i]; $j++)) {
$xyz[] = $users_array[$i][$j]["user_id"];
}
}
$users = implode(',',$xyz);
``` | ```
$user_ids = array();
foreach($users_array as $val){
foreach($val as $v)){
array_push($user_ids,$v['user_id']);
}
}
$users = implode(',',$user_ids);
```
This code is very easy and also use for as per your requirement. |
41,561,388 | I want to have few global variables in my python code.
Then set their values with set function and want to get their values through get function.
For example:
```
a = None #global variable1
b= None #global variable2
def set(var, value):
var = value
def get(var):
return var
set(a, '1')
get(b, '2')
```
I want to have a generic get and set function which will do this for any global variable. How can I do this in python ? The code written here gives error. | 2017/01/10 | [
"https://Stackoverflow.com/questions/41561388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7349246/"
] | ```
for($i = 0; $i < count($users_array); $i++){
for($j = 0; $j < count($users_array[$i]; $j++)) {
$xyz[] = $users_array[$i][$j]["user_id"];
}
}
$users = implode(',',$xyz);
``` | >
> hey @rjcode in php if you want to convert an array to comma separated
> string so use function implode(separation letter, $array) and for vice
> versa means string to an array so use function explode(separation
> letter, string)
>
>
>
for your case use use implode() so for your code try below one
```
<?php
for($i = 0; $i < count($users_array); $i++){
for($j = 0; $j < count($users_array[$i]; $j++)) {
$xyz[] = $users_array[$i][$j]["user_id"];
}
}
$users = implode(',',$xyz);
?>
``` |
22,408,951 | Often, T form a dictionary in python whose keys are inserted dynamically and the values are some sort of lists:
```
dc = {'foo': [1,2,3], 'bar': [2,3,4]}
```
However, the generation of such a dictionary is problematic to me. For example, say I am going through this list:
```
l = [('foo', 1),('foo', 2),('foo', 3), ('bar', 2), ('bar', 3), ('bar', 4)]
```
And I want my program to generate the `dc` dictionary from above. For now, the only code I have is this:
```
dc = {}
for key, value in l:
if dc.has_key(key):
dc[key].append(value)
else:
dc[key] = value
```
Is there a more pythonesque way of doing this? There is a lot of code here that could really be squished to make one simple line, while not being cumbersome and/or slow...
**Edit** The list `l` above is there for illustration. In fact, I often go through a large file and find a key-value pair in each line of the file, so calling `dict(l)` is not an option. | 2014/03/14 | [
"https://Stackoverflow.com/questions/22408951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2381279/"
] | ```
from collections import defaultdict
dc = defaultdict(list)
for key, value in l:
dc[key].append(value)
print dc
# defaultdict(<type 'list'>, {'foo': [1, 2, 3], 'bar': [2, 3, 4]})
```
You can use it just like using normal dictionary. But if you want to convert that to a dictionary, then you just do this
```
print dict(dc)
# {'foo': [1, 2, 3], 'bar': [2, 3, 4]}
``` | You can use [`setdefault`](http://docs.python.org/2.7/library/stdtypes.html?highlight=dict.setdefault#dict.setdefault) function as well.
```
>>>dc = {}
>>>for key, value in l:
>>> dc.setdefault(key,[]).append(value)
>>>dc
{'bar': [2, 3, 4], 'foo': [1, 2, 3]}
``` |
38,681,412 | I have get a virtual env on '/home/name/pyenv' for python2.7.9;
Now I want to install 'matplotlib' for it;
then I activate this virtual env and install 'matplotlib' as below:
* by command "sudo apt-get install python-matplotlib";
(if delete "sudo", permission denied), it runs well and I find "matplotlib" is exactly installed, but it is for default python and not for virtual env(pyenv) ;
* by command "pip install matplotlib"
I get error as below:
=====================
```
* The following required packages can not be built:
* freetype
```
---
Cleaning up...
Command python setup.py egg\_info failed with error code 1 in /tmp/pip-build-tYCFkL/matplotlib
Exception information:
Traceback (most recent call last):
File "/home/caofa/odoo-9.0/local/lib/python2.7/site-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/home/caofa/odoo-9.0/local/lib/python2.7/site-packages/pip/commands/install.py", line 290, in run
requirement\_set.prepare\_files(finder, force\_root\_egg\_info=self.bundle, bundle=self.bundle)
File "/home/caofa/odoo-9.0/local/lib/python2.7/site-packages/pip/req.py", line 1230, in prepare\_files
req\_to\_install.run\_egg\_info()
File "/home/caofa/odoo-9.0/local/lib/python2.7/site-packages/pip/req.py", line 326, in run\_egg\_info
command\_desc='python setup.py egg\_info')
File "/home/caofa/odoo-9.0/local/lib/python2.7/site-packages/pip/util.py", line 716, in call\_subprocess
% (command\_desc, proc.returncode, cwd))
InstallationError: Command python setup.py egg\_info failed with error code 1 in /tmp/pip-build-tYCFkL/matplotlib
I want to install it by method 1, but i don;t know how to install it for virtual env. | 2016/07/31 | [
"https://Stackoverflow.com/questions/38681412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6336288/"
] | when working in venv then try to used pip for installation for python packages ,sudo apt-get install normally using for root user of Linux. for your case you could try
pip install matplotlib==2.2.5 | One possibility is to install matplotlib globally then create your virtualenv **with** the site packages, see [here](https://stackoverflow.com/questions/12079607/make-virtualenv-inherit-specific-packages-from-your-global-site-packages) for someone with exactly the same problem, by using `virtualenv --system-site-packages` you can then activate your virtualenv and add additional packages, or update them, within your virtualenv only.
I am reasonably sure that you can even uninstall globally installed packages within your virtualenv without impacting your global installation but suggest you pick a small package that you can easily reinstall to test this on early on. |
67,903,509 | I'm currently trying to write a python script that notifies me through mail when a site updates it's selection of apartments. However, when I use Beautiful Soup, the site doesn't return a list of items, but rather a script that selects all relevant houses instead of the results of said script. Is there any way for me to retrieve the html of text of a site that I would see normally as a user? This is the rather simple code I've written in case that helps.
```
html = #somesite
response = requests.get(html)
text = BeautifulSoup(response.text)
text.find_all("script")
``` | 2021/06/09 | [
"https://Stackoverflow.com/questions/67903509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16175233/"
] | You may use `!` [non-null assertion operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator).
```ts
if (infinoteToken === null && !infinoteUrl!.toString().includes("localhost")) {
``` | Use [`@ts-ignore`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html#suppress-errors-in-ts-files-using--ts-ignore-comments)
```
// @ts-ignore TS2531: Object is possibly 'null'
if (infinoteToken === null && !infinoteUrl.toString().includes("localhost"))
```
This will ignore **all** errors on the line below the comment (so using optional chaining even though the value is never `null` will be safer) |
67,903,509 | I'm currently trying to write a python script that notifies me through mail when a site updates it's selection of apartments. However, when I use Beautiful Soup, the site doesn't return a list of items, but rather a script that selects all relevant houses instead of the results of said script. Is there any way for me to retrieve the html of text of a site that I would see normally as a user? This is the rather simple code I've written in case that helps.
```
html = #somesite
response = requests.get(html)
text = BeautifulSoup(response.text)
text.find_all("script")
``` | 2021/06/09 | [
"https://Stackoverflow.com/questions/67903509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16175233/"
] | You are assuming that `infinoteUrl` cannot be null, because you assume that `$q.localStorage.getItem("infinote-dev-api")` will return twice the same value. But there's no syntactical guarantee for that. Therefore TypeScript is warning you. You can use `!.` as suggested, but in my eyes, that defeats the point of using a strict type system in the first place. Try to leverage the features typescript has. You can rewrite it to
```
const maybeInfinoteUrl = $q.localStorage.getItem("infinote-dev-api");
const infinoteUrl =
maybeInfinoteUrl === null
? `${window.location.protocol}//${window.location.host}`
: maybeInfinoteUrl
console.log(`infinote URL: ${infinoteUrl}`)
```
or a much simpler form (which basically compiles to something similar) would be
```
const infinoteUrl =
$q.localStorage.getItem("infinote-dev-api")
?? `${window.location.protocol}//${window.location.host}`
console.log(`infinote URL: ${infinoteUrl}`)
```
here you have a TypeScript Plaground example: <https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAcwKZQGoEMA2JUAUAlAFyJgg46IA+iAzlAE4xjKIDeAUIr4k+hBMkAciz0AJsBEBuLgF8uXCAkaIAHogC8KdNjyEi2rTopVEAfkQiAjgHdUTEYjJpMufMTkqwagJ7auu4GxJZWtg5OcsqqcDioAHQ4cMgE6glQcAAycJEAwuKGRN6x8UkpBH4Z2bmOBfRFMkA> | Use [`@ts-ignore`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html#suppress-errors-in-ts-files-using--ts-ignore-comments)
```
// @ts-ignore TS2531: Object is possibly 'null'
if (infinoteToken === null && !infinoteUrl.toString().includes("localhost"))
```
This will ignore **all** errors on the line below the comment (so using optional chaining even though the value is never `null` will be safer) |
67,903,509 | I'm currently trying to write a python script that notifies me through mail when a site updates it's selection of apartments. However, when I use Beautiful Soup, the site doesn't return a list of items, but rather a script that selects all relevant houses instead of the results of said script. Is there any way for me to retrieve the html of text of a site that I would see normally as a user? This is the rather simple code I've written in case that helps.
```
html = #somesite
response = requests.get(html)
text = BeautifulSoup(response.text)
text.find_all("script")
``` | 2021/06/09 | [
"https://Stackoverflow.com/questions/67903509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16175233/"
] | You may use `!` [non-null assertion operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator).
```ts
if (infinoteToken === null && !infinoteUrl!.toString().includes("localhost")) {
``` | You are assuming that `infinoteUrl` cannot be null, because you assume that `$q.localStorage.getItem("infinote-dev-api")` will return twice the same value. But there's no syntactical guarantee for that. Therefore TypeScript is warning you. You can use `!.` as suggested, but in my eyes, that defeats the point of using a strict type system in the first place. Try to leverage the features typescript has. You can rewrite it to
```
const maybeInfinoteUrl = $q.localStorage.getItem("infinote-dev-api");
const infinoteUrl =
maybeInfinoteUrl === null
? `${window.location.protocol}//${window.location.host}`
: maybeInfinoteUrl
console.log(`infinote URL: ${infinoteUrl}`)
```
or a much simpler form (which basically compiles to something similar) would be
```
const infinoteUrl =
$q.localStorage.getItem("infinote-dev-api")
?? `${window.location.protocol}//${window.location.host}`
console.log(`infinote URL: ${infinoteUrl}`)
```
here you have a TypeScript Plaground example: <https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAcwKZQGoEMA2JUAUAlAFyJgg46IA+iAzlAE4xjKIDeAUIr4k+hBMkAciz0AJsBEBuLgF8uXCAkaIAHogC8KdNjyEi2rTopVEAfkQiAjgHdUTEYjJpMufMTkqwagJ7auu4GxJZWtg5OcsqqcDioAHQ4cMgE6glQcAAycJEAwuKGRN6x8UkpBH4Z2bmOBfRFMkA> |
58,191,895 | I need a python function evaluates a polynomial at a set of input points.The function takes as input a vector of polynomial weights, and a vector of input points where `x`: a vector of input values, and `w`: a vector of polynomial weights (ordered so the jth element is the linear coefficient for the `j`th-order monomial, i.e.,`x(j)`). The function outputs the predictions of the polynomial at each input point.
Is there a python built in function for this? | 2019/10/01 | [
"https://Stackoverflow.com/questions/58191895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11301963/"
] | See [numpy.poly1d](https://docs.scipy.org/doc/numpy/reference/generated/numpy.poly1d.html)
>
> Construct the polynomial x^2 + 2x + 3:
>
>
>
```
p = np.poly1d([1, 2, 3])
p(1) # prints 6
``` | It seems you are describing [`numpy.polyval()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyval.html):
```
import numpy as np
# 1 * x**2 + 2 * x**1 + 3 * x**0
# computed at points: [0, 1, 2]
y = np.polyval([1, 2, 3], [0, 1, 2])
print(y)
# [ 3 6 11]
```
Note that the same could be achieved with [`np.poly1d()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.poly1d.html), which should be more efficient if you are computing values from the same polynomial multiple times:
```
import numpy as np
# 1 * x**2 + 2 * x**1 + 3 * x**0
my_poly_func = np.poly1d([1, 2, 3])
# computed at points: [0, 1, 2]
y = my_poly_func([0, 1, 2])
print(y)
# [ 3 6 11]
```
---
If you want to use only Python built-ins, you could easily define a `polyval()` version yourself, e.g.:
```
def polyval(p, x):
return [sum(p_i * x_i ** i for i, p_i in enumerate(p[::-1])) for x_i in x]
y = polyval([1, 2, 3], [0, 1, 2])
print(y)
# [3, 6, 11]
```
or, more efficiently:
```
def polyval_horner(p, x):
y = []
for x_i in x:
y_i = 0
for p_i in p:
y_i = x_i * y_i + p_i
y.append(y_i)
return y
y = polyval_horner([1, 2, 3], [0, 1, 2])
print(y)
# [3, 6, 11]
```
but I would recommend using NumPy unless you have a good reason not to (for example, if your result would overflow with NumPy but not with pure Python). |
58,191,895 | I need a python function evaluates a polynomial at a set of input points.The function takes as input a vector of polynomial weights, and a vector of input points where `x`: a vector of input values, and `w`: a vector of polynomial weights (ordered so the jth element is the linear coefficient for the `j`th-order monomial, i.e.,`x(j)`). The function outputs the predictions of the polynomial at each input point.
Is there a python built in function for this? | 2019/10/01 | [
"https://Stackoverflow.com/questions/58191895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11301963/"
] | See [numpy.poly1d](https://docs.scipy.org/doc/numpy/reference/generated/numpy.poly1d.html)
>
> Construct the polynomial x^2 + 2x + 3:
>
>
>
```
p = np.poly1d([1, 2, 3])
p(1) # prints 6
``` | For fun you could try implementing the basic algorithms, iter being the worst, horner being better (I believe Karatsuba is the best). Here are the first two:
```
def iterative(coefficients, x): #very inefficient
i = len(coefficients)
result = coefficients[i - 1]
for z in range(i - 1, 0, -1):
temp = x
for y in range(z - 1):
temp = temp * x
result += temp * coefficients[i - z - 1]
return (x, result)
def horner(coefficients, x):
result = 0
for c in coefficients:
result = x * result + c
return (x, result)
```
I think numpy is faster in all cases as it goes into the C-level code. |
36,304,982 | I install some packages with pip command and when use `pip freeze` command shows some packages that is install
```
pip freeze
antlr4-python3-runtime==4.5.2.1
django==1.9.4
django-realtime==1.1
pymssql==2.1.2
```
I want to know where is location of this modules in **Windows** ?
I installed them with: `python setup.py install`
I search in python`s installation directory but not found anything | 2016/03/30 | [
"https://Stackoverflow.com/questions/36304982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3166171/"
] | From [this](https://docs.python.org/3/using/windows.html#finding-modules) in python documentation:
>
> Python usually stores its library (and thereby your site-packages folder) in the installation directory. So, if you had installed Python to C:\Python\, the default library would reside in C:\Python\Lib\ and third-party modules should be stored in C:\Python\Lib\site-packages.
>
>
>
If you want to install your packages in a different directory, use:
```
pip install --install-option="--prefix=$PREFIX_PATH" package_name
```
Use can use also `--ignore-installed` to force all dependencies to be reinstalled.
see other [options](https://pip.pypa.io/en/stable/reference/pip_install/?highlight=install-option#options) | Having installed modules using pip on windows, they should be in the installation directory, in `"Lib/site-packages"` directory.
So suppose you have installed Python at
>
> C://python27\_x64
>
>
>
then those modules should be at
>
> C://python27\_x64/Lib/site-packages/
>
>
> |
43,255,153 | For an automation project, I have to persist user id/password to allow my scripts to connect to a remote service.
My idea is to use the [keyring](https://pypi.python.org/pypi/keyring) module to achieve some better level of security; but as not all platforms support keyring; I am looking into storing credentials into a flat file, too. I created a "Credentials" class; and figured that using `pickle` I could just dump/load objects of that class, like:
```
def _store_to_file(credentials):
from pickle import dump
pkl = open('whatever.dat', 'wb')
dump(credentials, pkl)
pkl.close()
```
Unfortunately, this file gives away the password in plain text:
```
S'_password'
p6
S'bla'
```
I understand that file, stored by a local script isn't offering real security. But I was hoping to at least get to a point where one would need more than a simple "less whatever.dat" to acquire that password text.
I had hoped that pickle has some kind of "scramble" mode; but couldn't find anything. Am I overlooking something?
Alternatively: is there another way to persist my objects that easily, but not that "easy human readable"? | 2017/04/06 | [
"https://Stackoverflow.com/questions/43255153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1531124/"
] | A simple solution; based on the comment by Keef Baker --- using AES encryption to scramble on password/username; like this:
```
class Credentials(object):
def __init__(self, user, password):
self._user = aes.encrypt(user)
self._password = aes.encrypt(password)
@property
def user(self):
return aes.decrypt(self._user)
@property
def password(self):
return aes.decrypt(self._password)
from Crypto.Cipher import AES
aes = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
``` | You should not.
The problem in applications that try to keep a safely encrypted copy of a key is just that they need another key to decrypt it. It could be encrypted too by would need still another key. It could... (sorry joking :-) ). It only makes sense when you have to store multiple secrets, because you unlock the secure vault with one single password - what keyring and password managers do...
For one single password, the correct and portable way is to rely on the OS to provide a secure folder. Both Linux (and Unix-like) and provide either access control rules (only accessible to user), or encrypted folders if you need better security. Just document it and respect the [single responsibility principle](https://en.wikipedia.org/wiki/Single_responsibility_principle). |
70,781,970 | That's what happened when I tried to use facial recognition on my raspberry PI
The following code:
```
#coding=utf-8
import cv2
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
faces = face_cascade.detectMultiScale(frame, 1.3, 5)
img = frame
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
face_area = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(face_area)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(face_area,(ex,ey),(ex+ew,ey+eh),(0,255,0),1)
cv2.imshow('frame2',img)
if cv2.waitKey(5) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
Error message:
```
Traceback (most recent call last):
File "face_recognition1.py", line 4, in <module>
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_frontalface_default.xml')
AttributeError: 'module' object has no attribute 'data'
```
python version:3.7.5
opencv version:3.4.3 | 2022/01/20 | [
"https://Stackoverflow.com/questions/70781970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17652592/"
] | You can use:
```
df.index[n]
```
Example for the fifth (n=4) row:
```
(81, 37, 25)
``` | @MatthewHooper, for getting the value of nth index in pandas use the **index method** for getting the values of nth columns use **iloc method** For example
```py
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100,5)), columns=list('ABCDF'))
# Set index using column
df = df.set_index(['A','B','C'])
```
### Print the 5 first values
```py
print(df.head(5))
```
**Output**
```sh
D F
A B C
19 32 44 43 94
32 1 76 79 4
2 96 76 80 77
68 67 42 87 50
20 68 14 4 9
```
### Find the 5th row index
```py
print(df.index[4])
```
**Output**
```sh
(20, 68, 14)
```
### Find the 5th columns values
```py
print(tuple(df.iloc[4]))
```
**Output**
```sh
(4, 9)
``` |
38,720,688 | Here is my script:
```
import random
import os
i = 0
file = os.open("numbers.txt", "w")
while i < 5000:
ranNumb = str(random.randint(1,500))
file.write(ranNumb,",")
```
The end goal is simply a text file with 5000 randomly generated numbers in it that I would like to use in subsequent projects. When I run this little script I get the following error :
```
Traceback (most recent call last):
File "C:/Users/LewTo002/Desktop/New folder (2)/numGen.py", line 5, in <module>
file = os.open("numbers.txt", "w")
TypeError: an integer is required (got type str)
```
I've reviewed the following sites to solve the problem myself :
<http://learnpythonthehardway.org/book/ex16.html>
<https://docs.python.org/3/library/os.html>
<https://docs.python.org/3/tutorial/inputoutput.html>
And according to those, I am doing the correctly. The error is thrown specifically due to the "w" in "file = os.open('numbers.txt', 'w')" according to my IDE ( using JetBrain's PyCharm ). I feel like I am overlooking something trivial especially with how simple this script is... Any assistance would be thoroughly appreciated! :) | 2016/08/02 | [
"https://Stackoverflow.com/questions/38720688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6435999/"
] | If you want to use [os.open](https://docs.python.org/2/library/os.html#os.open) you have to use [os flags](https://docs.python.org/2/library/os.html#open-constants) to identify mode in which you are going to open file:
```
file = os.open("numbers.txt", os.O_WRONLY)
```
The way you are trying to open file is correct for [built in open method](https://docs.python.org/2/library/functions.html#open)
**Good Luck !** | From the [documentation](https://docs.python.org/3/library/os.html) you linked:
>
> If you just want to read or write a file see [open()](https://docs.python.org/3/library/functions.html#open).
>
>
>
As I said in the comment, change this:
```
os.open(...)
```
To this:
```
open(...)
``` |
38,720,688 | Here is my script:
```
import random
import os
i = 0
file = os.open("numbers.txt", "w")
while i < 5000:
ranNumb = str(random.randint(1,500))
file.write(ranNumb,",")
```
The end goal is simply a text file with 5000 randomly generated numbers in it that I would like to use in subsequent projects. When I run this little script I get the following error :
```
Traceback (most recent call last):
File "C:/Users/LewTo002/Desktop/New folder (2)/numGen.py", line 5, in <module>
file = os.open("numbers.txt", "w")
TypeError: an integer is required (got type str)
```
I've reviewed the following sites to solve the problem myself :
<http://learnpythonthehardway.org/book/ex16.html>
<https://docs.python.org/3/library/os.html>
<https://docs.python.org/3/tutorial/inputoutput.html>
And according to those, I am doing the correctly. The error is thrown specifically due to the "w" in "file = os.open('numbers.txt', 'w')" according to my IDE ( using JetBrain's PyCharm ). I feel like I am overlooking something trivial especially with how simple this script is... Any assistance would be thoroughly appreciated! :) | 2016/08/02 | [
"https://Stackoverflow.com/questions/38720688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6435999/"
] | If you want to use [os.open](https://docs.python.org/2/library/os.html#os.open) you have to use [os flags](https://docs.python.org/2/library/os.html#open-constants) to identify mode in which you are going to open file:
```
file = os.open("numbers.txt", os.O_WRONLY)
```
The way you are trying to open file is correct for [built in open method](https://docs.python.org/2/library/functions.html#open)
**Good Luck !** | Citing after Python docs available [here](https://docs.python.org/2/library/os.html#os.open)
>
> This function is intended for low-level I/O. For normal usage, use the built-in function open(), which returns a “file object” with read() and write() methods (and many more). To wrap a file descriptor in a “file object”, use fdopen().
>
>
>
You should use the built-in `open` function as others has said already. |
58,387,072 | Is there a single root type that all other types inherit from in python? From doing basic trial-and-error, it seems this may be the type called `type`:
```
>>> None.__class__
<class 'NoneType'>
>>> None.__class__.__class__
<class 'type'>
>>> None.__class__.__class__.__class__
<class 'type'>
```
And also it seems like that is the only type for which the class of it equals itself.
Are there any other types that are more basic than the `type` type? If not, why is `type` the most basic type in python? | 2019/10/15 | [
"https://Stackoverflow.com/questions/58387072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4673887/"
] | ```
import React, { Component } from 'react';
import './index.css';
import Game from './Game.js'
import Homescreen from './Homescreen.js'
import PlayerScreen from './Playerscreen.js'
class App extends Component {
constructor(props) {
super(props);
this.state = {
Homescreen: true,
PlayerScreen: false,
Game: false,
players: [{
users: '',
points: 0,
}]
}
}
render() {
return (
<div>
{
(this.state.Homescreen) ?
<div id="wrapper">
<Homescreen newScreen={() => this.setState({ Homescreen: false, PlayerScreen: true })} />
</div> :
(this.state.PlayerScreen) ?
<div id="wrapper">
<PlayerScreen players={this.state.players} start={(players) => this.setState({ PlayerScreen: false, Game: true, players: players })} />
</div> :
<div id="wrapper">
<Game players={this.state.players} />
</div>
}
</div>
);
}
}
export default App
```
replace this code with yours and check | the message is expecting a semi colon there because you haven't closed your constructor method ;)
Take a break, walk around your apt/house/office give your eyes a second to catch these little things |
58,387,072 | Is there a single root type that all other types inherit from in python? From doing basic trial-and-error, it seems this may be the type called `type`:
```
>>> None.__class__
<class 'NoneType'>
>>> None.__class__.__class__
<class 'type'>
>>> None.__class__.__class__.__class__
<class 'type'>
```
And also it seems like that is the only type for which the class of it equals itself.
Are there any other types that are more basic than the `type` type? If not, why is `type` the most basic type in python? | 2019/10/15 | [
"https://Stackoverflow.com/questions/58387072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4673887/"
] | You are missing a curly brackets in your state declaration.
```
constructor(props){
super(props);
this.state = {
Homescreen: true,
PlayerScreen: false,
Game: false,
players: [{
users: '',
points: 0,
}]
} // this is missing
}
``` | the message is expecting a semi colon there because you haven't closed your constructor method ;)
Take a break, walk around your apt/house/office give your eyes a second to catch these little things |
58,387,072 | Is there a single root type that all other types inherit from in python? From doing basic trial-and-error, it seems this may be the type called `type`:
```
>>> None.__class__
<class 'NoneType'>
>>> None.__class__.__class__
<class 'type'>
>>> None.__class__.__class__.__class__
<class 'type'>
```
And also it seems like that is the only type for which the class of it equals itself.
Are there any other types that are more basic than the `type` type? If not, why is `type` the most basic type in python? | 2019/10/15 | [
"https://Stackoverflow.com/questions/58387072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4673887/"
] | ```
import React, { Component } from 'react';
import './index.css';
import Game from './Game.js'
import Homescreen from './Homescreen.js'
import PlayerScreen from './Playerscreen.js'
class App extends Component {
constructor(props) {
super(props);
this.state = {
Homescreen: true,
PlayerScreen: false,
Game: false,
players: [{
users: '',
points: 0,
}]
}
}
render() {
return (
<div>
{
(this.state.Homescreen) ?
<div id="wrapper">
<Homescreen newScreen={() => this.setState({ Homescreen: false, PlayerScreen: true })} />
</div> :
(this.state.PlayerScreen) ?
<div id="wrapper">
<PlayerScreen players={this.state.players} start={(players) => this.setState({ PlayerScreen: false, Game: true, players: players })} />
</div> :
<div id="wrapper">
<Game players={this.state.players} />
</div>
}
</div>
);
}
}
export default App
```
replace this code with yours and check | Make these changes to your main file.
```
showComponent = (component) => {
this.setState({currentComponent: component})
}
let checkCurrentScreen = this.state.currentScreen;
{checkCurrentScreen === "homeScreen" ? (
<Homescreen showComponent={this.state.showComponent} />
) : checkCurrentScreen ? (
<PlayerScreen showComponent={this.state.showComponent} />
) : <DefaultScreen />
}
```
Pass in your component with button click
```
const handleComponentChange = (e, component) => {
e.preventDefault();
props.showComponent(component)
}
```
I apologize for my type o, I have corrected above. The last method is what I use in a separate component, I like this approach be cause it allows t his method to be used almost anywhere. Here is an example to the button used.
```
<button
onClick={e => handleComponentChange(e, "author")}
className="comment-submit-button">Cancel
</button>
```
This button will pass "e" and the name of the component to the method above the return. This allows for this method to be portable, here is the full method, perhaps this will help.
```
const handleComponentChange = (e, component) => { // passed in e
e.preventDefault(); // for this
props.showComponent(component); // called method from index.js
}
```
With my handleComponentChange I can pass in any props/state to use as I wish to use, plus the name of my component I want to render. I was able to easily add e for prevent default, plus the name.
ShowComponent sits in my index file, where I have my components that will be conditionally rendered. |
58,387,072 | Is there a single root type that all other types inherit from in python? From doing basic trial-and-error, it seems this may be the type called `type`:
```
>>> None.__class__
<class 'NoneType'>
>>> None.__class__.__class__
<class 'type'>
>>> None.__class__.__class__.__class__
<class 'type'>
```
And also it seems like that is the only type for which the class of it equals itself.
Are there any other types that are more basic than the `type` type? If not, why is `type` the most basic type in python? | 2019/10/15 | [
"https://Stackoverflow.com/questions/58387072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4673887/"
] | You are missing a curly brackets in your state declaration.
```
constructor(props){
super(props);
this.state = {
Homescreen: true,
PlayerScreen: false,
Game: false,
players: [{
users: '',
points: 0,
}]
} // this is missing
}
``` | Make these changes to your main file.
```
showComponent = (component) => {
this.setState({currentComponent: component})
}
let checkCurrentScreen = this.state.currentScreen;
{checkCurrentScreen === "homeScreen" ? (
<Homescreen showComponent={this.state.showComponent} />
) : checkCurrentScreen ? (
<PlayerScreen showComponent={this.state.showComponent} />
) : <DefaultScreen />
}
```
Pass in your component with button click
```
const handleComponentChange = (e, component) => {
e.preventDefault();
props.showComponent(component)
}
```
I apologize for my type o, I have corrected above. The last method is what I use in a separate component, I like this approach be cause it allows t his method to be used almost anywhere. Here is an example to the button used.
```
<button
onClick={e => handleComponentChange(e, "author")}
className="comment-submit-button">Cancel
</button>
```
This button will pass "e" and the name of the component to the method above the return. This allows for this method to be portable, here is the full method, perhaps this will help.
```
const handleComponentChange = (e, component) => { // passed in e
e.preventDefault(); // for this
props.showComponent(component); // called method from index.js
}
```
With my handleComponentChange I can pass in any props/state to use as I wish to use, plus the name of my component I want to render. I was able to easily add e for prevent default, plus the name.
ShowComponent sits in my index file, where I have my components that will be conditionally rendered. |
36,641,229 | I often write short programs when collect statistics when they run and report at the end. I normally gather these stats in a dictionary to display at the end.
I end up writing these like the simple example below, but I expect there is a cleaner more pythonic way to do this. This way can grow quite large (or nested) when there are several metrics.
```
stats = {}
def add_result_to_stats(result,func_name):
if not func_name in stats.keys():
stats[func_name] = {}
if not result in stats[func_name].keys():
stats[func_name][result] = 1
else:
stats[func_name][result] += 1
``` | 2016/04/15 | [
"https://Stackoverflow.com/questions/36641229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1697349/"
] | You could combine [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) with [`Counter`](https://docs.python.org/2/library/collections.html#collections.Counter) which would reduce `add_result_to_stats` to one line:
```
from collections import defaultdict, Counter
stats = defaultdict(Counter)
def add_result_to_stats(result, func_name):
stats[func_name][result] += 1
add_result_to_stats('foo', 'bar')
print stats # defaultdict(<class 'collections.Counter'>, {'bar': Counter({'foo': 1})})
``` | If you just have to count `func_names` and `results` go with a [Counter](https://docs.python.org/2/library/collections.html#collections.Counter)
```
import collections
stats = collections.Counter()
def add_result_to_stats(result,func_name):
stats.update({(func_name, result):1})
``` |
56,628,716 | I have been trying to merge several csv files into one but its showing me some error. I am new to python, your help will be highly appreciated.
Following is my code:
```
import pandas as pd
import numpy as np
import glob
all_data_csv = pd.read_csv("C:/Users/Am/Documents/A.csv", encoding='utf-8')
for f in glob.glob('*.csv'):
df = pd.read_csv(f, encoding='utf-8')
all_data_csv= pd.merge(all_data_csv,df ,how= 'outer')
print(all_data_csv)
```
and the error shown:
```
Traceback (most recent call last):
File "pandas\_libs\parsers.pyx", line 1169, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1299, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1315, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1553, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 1: invalid start byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:/internship/j.py", line 8, in <module>
df = pd.read_csv(f, encoding='utf-8')
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 702, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 435, in _read
data = parser.read(nrows)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 1139, in read
ret = self._engine.read(nrows)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 1995, in read
data = self._reader.read(nrows)
File "pandas\_libs\parsers.pyx", line 899, in pandas._libs.parsers.TextReader.read
File "pandas\_libs\parsers.pyx", line 914, in pandas._libs.parsers.TextReader._read_low_memory
File "pandas\_libs\parsers.pyx", line 991, in pandas._libs.parsers.TextReader._read_rows
File "pandas\_libs\parsers.pyx", line 1123, in pandas._libs.parsers.TextReader._convert_column_data
File "pandas\_libs\parsers.pyx", line 1176, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1299, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1315, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1553, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 1: invalid start byte
``` | 2019/06/17 | [
"https://Stackoverflow.com/questions/56628716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11629551/"
] | You can combine`filter`, `for` and `for...in` to do that:
```js
var myObject= [
{
"Product-name": "Shirt",
"product-price": "500",
"attributevalue": [
{ "color": "red" },
{"fabric": "cottton"}
]
},
{
"Product-name": "Samsung mobile",
"product-price": "15000",
"attributevalue":[
{"Ram": "4 GB"},
{"Network": "4G"},
{"Primary Camera": "8 MP"},
{"Internal Memory": "8 GB"}
]
}
]
const search = (arr, search) => {
return arr.filter(item => {
for (var i = 0; i < item.attributevalue.length; i++) {
for (var key in item.attributevalue[i]) {
if (item.attributevalue[i][key].toLowerCase() === search.toLowerCase()) {
return item;
}
}
}
})
}
console.log(search(myObject, 'red'))
``` | Try doing this:
```
const filterBy = (obj, attr, query) =>
obj.filter((prod) => prod.attributevalue && prod.attributevalue[attr] === query);
``` |
56,628,716 | I have been trying to merge several csv files into one but its showing me some error. I am new to python, your help will be highly appreciated.
Following is my code:
```
import pandas as pd
import numpy as np
import glob
all_data_csv = pd.read_csv("C:/Users/Am/Documents/A.csv", encoding='utf-8')
for f in glob.glob('*.csv'):
df = pd.read_csv(f, encoding='utf-8')
all_data_csv= pd.merge(all_data_csv,df ,how= 'outer')
print(all_data_csv)
```
and the error shown:
```
Traceback (most recent call last):
File "pandas\_libs\parsers.pyx", line 1169, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1299, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1315, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1553, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 1: invalid start byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:/internship/j.py", line 8, in <module>
df = pd.read_csv(f, encoding='utf-8')
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 702, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 435, in _read
data = parser.read(nrows)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 1139, in read
ret = self._engine.read(nrows)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 1995, in read
data = self._reader.read(nrows)
File "pandas\_libs\parsers.pyx", line 899, in pandas._libs.parsers.TextReader.read
File "pandas\_libs\parsers.pyx", line 914, in pandas._libs.parsers.TextReader._read_low_memory
File "pandas\_libs\parsers.pyx", line 991, in pandas._libs.parsers.TextReader._read_rows
File "pandas\_libs\parsers.pyx", line 1123, in pandas._libs.parsers.TextReader._convert_column_data
File "pandas\_libs\parsers.pyx", line 1176, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1299, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1315, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1553, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 1: invalid start byte
``` | 2019/06/17 | [
"https://Stackoverflow.com/questions/56628716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11629551/"
] | Just the `filter` method of Array will do the trick.
```js
var myObject = [{
"Product-name": "Shirt",
"product-price": "500",
"attributevalue": [{
"color": "red"
}, {
"fabric": "cottton"
}]
}, {
"Product-name": "Samsung mobile",
"product-price": "15000",
"attributevalue": [{
"Ram": "4 GB"
}, {
"Network": "4G"
}, {
"Primary Camera": "8 MP"
}, {
"Internal Memory": "8 GB"
}]
}]
function findProduct(property, searchField) {
return myObject.filter((x) => {
const result = x.attributevalue.filter((y) => y[property] === searchField);
if (result.length) {
return x;
}
})
}
console.log(findProduct('Network', '4G'))
``` | Try doing this:
```
const filterBy = (obj, attr, query) =>
obj.filter((prod) => prod.attributevalue && prod.attributevalue[attr] === query);
``` |
56,628,716 | I have been trying to merge several csv files into one but its showing me some error. I am new to python, your help will be highly appreciated.
Following is my code:
```
import pandas as pd
import numpy as np
import glob
all_data_csv = pd.read_csv("C:/Users/Am/Documents/A.csv", encoding='utf-8')
for f in glob.glob('*.csv'):
df = pd.read_csv(f, encoding='utf-8')
all_data_csv= pd.merge(all_data_csv,df ,how= 'outer')
print(all_data_csv)
```
and the error shown:
```
Traceback (most recent call last):
File "pandas\_libs\parsers.pyx", line 1169, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1299, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1315, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1553, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 1: invalid start byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:/internship/j.py", line 8, in <module>
df = pd.read_csv(f, encoding='utf-8')
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 702, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 435, in _read
data = parser.read(nrows)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 1139, in read
ret = self._engine.read(nrows)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 1995, in read
data = self._reader.read(nrows)
File "pandas\_libs\parsers.pyx", line 899, in pandas._libs.parsers.TextReader.read
File "pandas\_libs\parsers.pyx", line 914, in pandas._libs.parsers.TextReader._read_low_memory
File "pandas\_libs\parsers.pyx", line 991, in pandas._libs.parsers.TextReader._read_rows
File "pandas\_libs\parsers.pyx", line 1123, in pandas._libs.parsers.TextReader._convert_column_data
File "pandas\_libs\parsers.pyx", line 1176, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1299, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1315, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1553, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 1: invalid start byte
``` | 2019/06/17 | [
"https://Stackoverflow.com/questions/56628716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11629551/"
] | You can combine`filter`, `for` and `for...in` to do that:
```js
var myObject= [
{
"Product-name": "Shirt",
"product-price": "500",
"attributevalue": [
{ "color": "red" },
{"fabric": "cottton"}
]
},
{
"Product-name": "Samsung mobile",
"product-price": "15000",
"attributevalue":[
{"Ram": "4 GB"},
{"Network": "4G"},
{"Primary Camera": "8 MP"},
{"Internal Memory": "8 GB"}
]
}
]
const search = (arr, search) => {
return arr.filter(item => {
for (var i = 0; i < item.attributevalue.length; i++) {
for (var key in item.attributevalue[i]) {
if (item.attributevalue[i][key].toLowerCase() === search.toLowerCase()) {
return item;
}
}
}
})
}
console.log(search(myObject, 'red'))
``` | Here is an approach supporting multiple filtering (multiple keys and values) and multiple support for the key-value check.
The routine is:
* applying filter over the desired object.
* mapping the array of attribute value to a single object holding the key (string) and the value.
* evaluating the searchBy parameter, which holds an object containing the key, which is the searched key and the value that can either be a primitive, an object or a function. If that's a function, it will be evaluated through the argument passed, which is the currently looped value to search on.
* return whether any of the searched criteria match.
```js
var myObject = [
{
"Product-name": "Shirt",
"product-price": "500",
"attributevalue": [
{ "color": "red" },
{"fabric": "cottton"}
]
},
{
"Product-name": "Samsung mobile",
"product-price": "15000",
"attributevalue":[
{"Ram": "4 GB"},
{"Network": "4G"},
{"Primary Camera": "8 MP"},
{"Internal Memory": "8 GB"}
]
}
];
function filterBy(obj, searchBy) {
return obj.filter(item => {
const _assigned = Object.assign({}, ...item.attributevalue);
return Object.entries(searchBy).some(([k,v]) => {
return _assigned[k] && (typeof(v) === 'function' ? v.call(null, _assigned[k]) : _assigned[k] === v);
});
});
}
// Sample to filter by color and fabric.
console.log(filterBy(myObject, {
color: 'red',
fabric: (needle) => needle === 'cottton'
}));
// sample of callback filter that checks whether the "RAM" value exists and is, when lowercase, '4 gb'
console.log(
filterBy(myObject, {
Ram: (ram) => {
return ram && ram.toLowerCase() === '4 gb'
}
})
);
``` |
56,628,716 | I have been trying to merge several csv files into one but its showing me some error. I am new to python, your help will be highly appreciated.
Following is my code:
```
import pandas as pd
import numpy as np
import glob
all_data_csv = pd.read_csv("C:/Users/Am/Documents/A.csv", encoding='utf-8')
for f in glob.glob('*.csv'):
df = pd.read_csv(f, encoding='utf-8')
all_data_csv= pd.merge(all_data_csv,df ,how= 'outer')
print(all_data_csv)
```
and the error shown:
```
Traceback (most recent call last):
File "pandas\_libs\parsers.pyx", line 1169, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1299, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1315, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1553, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 1: invalid start byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:/internship/j.py", line 8, in <module>
df = pd.read_csv(f, encoding='utf-8')
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 702, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 435, in _read
data = parser.read(nrows)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 1139, in read
ret = self._engine.read(nrows)
File "C:\Users\Amreeta Koner\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py", line 1995, in read
data = self._reader.read(nrows)
File "pandas\_libs\parsers.pyx", line 899, in pandas._libs.parsers.TextReader.read
File "pandas\_libs\parsers.pyx", line 914, in pandas._libs.parsers.TextReader._read_low_memory
File "pandas\_libs\parsers.pyx", line 991, in pandas._libs.parsers.TextReader._read_rows
File "pandas\_libs\parsers.pyx", line 1123, in pandas._libs.parsers.TextReader._convert_column_data
File "pandas\_libs\parsers.pyx", line 1176, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1299, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1315, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1553, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 1: invalid start byte
``` | 2019/06/17 | [
"https://Stackoverflow.com/questions/56628716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11629551/"
] | Just the `filter` method of Array will do the trick.
```js
var myObject = [{
"Product-name": "Shirt",
"product-price": "500",
"attributevalue": [{
"color": "red"
}, {
"fabric": "cottton"
}]
}, {
"Product-name": "Samsung mobile",
"product-price": "15000",
"attributevalue": [{
"Ram": "4 GB"
}, {
"Network": "4G"
}, {
"Primary Camera": "8 MP"
}, {
"Internal Memory": "8 GB"
}]
}]
function findProduct(property, searchField) {
return myObject.filter((x) => {
const result = x.attributevalue.filter((y) => y[property] === searchField);
if (result.length) {
return x;
}
})
}
console.log(findProduct('Network', '4G'))
``` | Here is an approach supporting multiple filtering (multiple keys and values) and multiple support for the key-value check.
The routine is:
* applying filter over the desired object.
* mapping the array of attribute value to a single object holding the key (string) and the value.
* evaluating the searchBy parameter, which holds an object containing the key, which is the searched key and the value that can either be a primitive, an object or a function. If that's a function, it will be evaluated through the argument passed, which is the currently looped value to search on.
* return whether any of the searched criteria match.
```js
var myObject = [
{
"Product-name": "Shirt",
"product-price": "500",
"attributevalue": [
{ "color": "red" },
{"fabric": "cottton"}
]
},
{
"Product-name": "Samsung mobile",
"product-price": "15000",
"attributevalue":[
{"Ram": "4 GB"},
{"Network": "4G"},
{"Primary Camera": "8 MP"},
{"Internal Memory": "8 GB"}
]
}
];
function filterBy(obj, searchBy) {
return obj.filter(item => {
const _assigned = Object.assign({}, ...item.attributevalue);
return Object.entries(searchBy).some(([k,v]) => {
return _assigned[k] && (typeof(v) === 'function' ? v.call(null, _assigned[k]) : _assigned[k] === v);
});
});
}
// Sample to filter by color and fabric.
console.log(filterBy(myObject, {
color: 'red',
fabric: (needle) => needle === 'cottton'
}));
// sample of callback filter that checks whether the "RAM" value exists and is, when lowercase, '4 gb'
console.log(
filterBy(myObject, {
Ram: (ram) => {
return ram && ram.toLowerCase() === '4 gb'
}
})
);
``` |
8,060,397 | What is the specific method to iterate a stack in python. is the best practice to use a for loop just like to iterate a list? | 2011/11/09 | [
"https://Stackoverflow.com/questions/8060397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004875/"
] | If your stack can potentially grow to large proportions, you should absolutely not be using a `List` or a custom stack class. Raymond Hettinger has already done the work for you and written the wonderful `collections.deque`. The `deque` is a list like data structure that supports constant time appends and pops from both ends.
```
>>> from collections import deque
>>>
>>> stack = deque()
>>> stack.append(1)
>>> stack.append(2)
>>> stack.append(3)
>>> print stack
deque([1,2,3])
```
By then appropriately using `deque.pop()` and `deque.popleft()` you can acheive both FILO and FIFO respectively. You can also iterate over it with `for item in stack` if you want FIFO or `for item in reversed(stack)` for FILO, which will generate a memory efficient reverse iterator. | In Python, unlike other prog. languages like C++ (STL), we do not have predefined data structure `Stack`, we just have a regular `List`.
So, if you want to iterate your "Stack" as a regular List, you can just simply have to make something like:
```
for item in reversed(my_list): # to preserve LIFO
# do something with item
# ...
```
Now, if you want your List to behave as a Stack (LIFO: Last In First Out), you could use the predefined list functions `append` and `pop`:
```
>>> stack = [1, 2]
>>> stack.append(3)
>>> stack.append(4)
>>> stack
[1, 2, 3, 4]
>>> stack.pop()
4
>>> stack
[1, 2, 3]
```
More about this in <http://docs.python.org/tutorial/datastructures.html#using-lists-as-stacks> |
8,060,397 | What is the specific method to iterate a stack in python. is the best practice to use a for loop just like to iterate a list? | 2011/11/09 | [
"https://Stackoverflow.com/questions/8060397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004875/"
] | If your stack can potentially grow to large proportions, you should absolutely not be using a `List` or a custom stack class. Raymond Hettinger has already done the work for you and written the wonderful `collections.deque`. The `deque` is a list like data structure that supports constant time appends and pops from both ends.
```
>>> from collections import deque
>>>
>>> stack = deque()
>>> stack.append(1)
>>> stack.append(2)
>>> stack.append(3)
>>> print stack
deque([1,2,3])
```
By then appropriately using `deque.pop()` and `deque.popleft()` you can acheive both FILO and FIFO respectively. You can also iterate over it with `for item in stack` if you want FIFO or `for item in reversed(stack)` for FILO, which will generate a memory efficient reverse iterator. | As the others have said, python doesn't really have a built-in stack datatype, per se-- but you can use a list to emulate one.
When using a list as a stack, you can model the first-in-last-out behavior with append() as push and pop() as pop, as julio.alegria describes.
If you want to use that list in a for-loop, but still have it behave in the FILO fashion you can reverse the order of the elements with this slice syntax: `[::-1]`.
Example:
```
for element in stack[::-1]:
print element
```
If you're using a custom class that implements a stack, just as long as it has `__iter__()` and `next()` methods defined you can use it in list comprehensions, for loops, or whatever.
That way you can implement a custom iterator that removes items as it iterates over it, just as it should with a proper stack.
Example:
```
class Stack:
def __init__(self):
self.data = []
def push(self,n):
self.data.append(n)
def pop(self):
return self.data.pop()
def __iter__(self):
return self
def next(self):
if len(self.data)>0:
return self.pop()
else:
raise StopIteration
filo = Stack()
filo.push(1)
filo.push(2)
filo.push(3)
for i in filo:
print i
``` |
40,583,272 | I am using python 3.5 and below code is mostly from the google api page...
<https://developers.google.com/gmail/api/guides/sending>
slightly revised for python 3.x
i could successfully send out the email with the content text and an attachment pdf but the pdf attached is completely blank..
please help and thanks in advance
```
def create_message_with_attachment(bcc, subject, message_text, file,sender='me' ):
message = MIMEMultipart()
message['bcc'] = bcc
message['from'] = sender
message['subject'] = subject
msg = MIMEText(message_text)
message.attach(msg)
content_type, encoding = mimetypes.guess_type(file)
main_type, sub_type = content_type.split('/', 1)
fp = open(file, 'rb')
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
fp.close()
filename = os.path.basename(file)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(msg)
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
return {'raw':raw}
``` | 2016/11/14 | [
"https://Stackoverflow.com/questions/40583272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7155406/"
] | you just forgot to encode the attachment. Replace two lines of your code with those:
```
import email.encoders
...
msg.add_header('Content-Disposition', 'attachment',filename=filename)
email.encoders.encode_base64(msg)
message.attach(msg)
...
``` | Less line of code, Seem to work well, but very slow :
```
def SendPDF(to, file, Server):
msg = EmailMessage()
msg['From'] = ME
msg['To'] = to
msg['Subject'] = 'Send a pdf File'
with open(file, 'rb') as PDFFile:
PdfContent = PDFFile.read()
msg.add_attachment(PdfContent, maintype='', subtype='pdf',
filename="The Pdf File Bro.pdf")
Server.send_message(msg)
```
But I don't know what append with maintype, this argument is needed, and you can write whatever you want it will works, I didn't find actually any documentation on it.Don't manage SMTP enough to know it otherwise. If anyone know... |
66,196,554 | [Select a Data and Time Need Python and selenium logic](https://i.stack.imgur.com/WcW5m.png)
Good Evening!
I have attached one picture what I require from all of you is need logic for the added picture. I am learning python(pycharam) with selenium automation. I have come cross one scenario where in I have to schedule an appointment by selecting the 'month' and date as '16' and time as '1:30pm'
If I get the logic for month, I will try for weekly.
I would appreciate it, if someone answering if they can share step by steps what needs to be done. I would appreciate it.
Regards,
Shiva | 2021/02/14 | [
"https://Stackoverflow.com/questions/66196554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15067112/"
] | ```
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
driver.get('url')
elem = Select(driver.find_element_by_id('id_of_the_drop_down_list'))
# select by visible text
elem.select_by_visible_text('text_that_you_want_to_choose')
/
# select by index
elem_select_by_index(0)
/
# select by value
elem.select_by_value('1')
``` | ```
elem = Select(driver.find_element_by_id('tt_form_ChoiceSelect_0'))
elem.select_by_visible_text('15 Available')
elem.select_by_value('2021-02-16T19:30:00.000Z').click()
driver.find_element_by_xpath("//*[@id='nextBtn']").click()
```
Worked above logic. Its working .Thanks |
73,897,570 | Ik have created a python test file in VSC. When I run this file it works fine and I see my output in the browser (Dash/Flask). However when I try to debug the file in VSC it gives me an error "No module named test.py" For sure I select the Python debug option.
My file structure is:
```
-root
-chapter
-test.py
```
What is the difference in debug and not debug? | 2022/09/29 | [
"https://Stackoverflow.com/questions/73897570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8771201/"
] | You should only use `%` symbol at the end of your `where` clause value (eg: `admin_side_barmenu%`) so that the `DB` knows you only want the rows starting with `admin_side_barmenu` and can have 0 or more characters from the right.
UPDATE
------
After checking the package, it seems `getAllPermissions` return a collection and doesn't make a *direct* DB call, So we need to filter the return collection from that method.
```php
use Illuminate\Support\Str;
auth()->user()
->getAllPermissions()
->filter(fn($p) => Str::startsWith($p, 'admin_side_barmenu')) // only return permissions starting with "admin_side_barmenu"
->toArray();
```
Based on the data sample found in your question, the above query should return **all the rows** from the table because they **all start with** `admin_side_barmenu` substring.
>
> Learn more about [`Pattern Matching`](https://dev.mysql.com/doc/refman/8.0/en/pattern-matching.html) on `MySQL` docs.
>
>
> | [**@ths**](https://stackoverflow.com/users/6388552/ths)
Thank you so much for your time.
I have made some changes in your answer. and its working for me. Thanks for the help
```
auth()->user()
->getAllPermissions()
->filter(fn($p) => Str::startsWith($p->name, 'admin_side_barmenu',))
->toArray());
``` |
45,026,920 | Scenario-
I am running B\* instances on App Engine. I've a background ETL related task(**written in python**) scheduled as a cron job on App Engine.
When time arrives, cron initiates a http request to start the task and runs without returning a response till the task gets completed.
When task was executing, it was typically consuming "X" MB of RAM. After the task got finished and returned 200 OK, App Engine Instance monitoring is still showing "X" MB of RAM in use.
Please help me understand the following -
1. If an instance is running only one task and after completing it, when will memory get freed that was consumed by this task?
2. Do I need to run `gc.collect()` to call the garbage collector explicitly to free up RAM ?
3. The only way to free up RAM is to restart the instance ?
**PS: This is not at all related to NDB, my task is taking input from Bigquery, performing some ETL operation and then streaming it to Bigquery.** | 2017/07/11 | [
"https://Stackoverflow.com/questions/45026920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4503532/"
] | From my observations with an app using lots of memory for `StringIO` operations:
* explicitly calling `gc.collect()` didn't noticeably help (I even suspected for a while that I actually have memory leaks, but it wasn't the case)
* the memory is not freed after each and every request, but, if the instance remains alive long enough without running out of memory it does eventual
appears to be freed now and then. Easy to test - just increase the time between requests to reduce the free memory draining rate. But I couldn't figure out a usable pattern. Note that I observed this only after upgrading to `B2` instances, my `B1` instances were running out of memory too fast, I never noticed a freeing event with them.
* using an [instance class](https://cloud.google.com/appengine/docs/standard/#instance_classes) with more memory (which I tried as a workaround for my instances eventually running out of memory) helped - the memory appeared to be freed more often. It *might* be because these instances also have a faster CPU (but that's just guesswork). | There are a few questions on StackOverflow describing similar memory issues for tasks when using ndb on app engine. Here is one [example](https://stackoverflow.com/questions/12095259/ndb-not-clearing-memory-during-a-long-request).
The issue is that app engine doesn't clear the ndb context cache upon the conclusion of a task so context cache continues to hog your memory long after the task completes.
The solution is to not use or clear the context cache during your tasks. Here are a few ways:
* Bypass caching with `key.get(use_cache=False)`
* Call `ndb.get_context().clear_cache()` at appropriate times.
* Disable caching for all entities of a kind by adding `_use_cache = False` to your model definition. |
9,696,495 | My code :
```
locs = [ [1], [2] ]
for loc in locs:
loc = []
print locs
# prints => [ [1], [2] ]
```
Why is `loc` not reference of elements of `locs` ?
Python : Everything is passed as reference unless explicitly copied [ Is this not True ? ]
Please explain.. how does python decides **referencing and copying** ?
**Update :**
How to do ?
```
def compute(ob):
if isinstance(ob,list): return process_list(ob)
if isinstance(ob,dict): return process_dict(ob)
for loc in locs:
loc = compute(loc) # What to change here to make loc a reference of actual locs iteration ?
```
* locs must contain the final processed response !
* I don't want to use `enumerate`, is it possible without it ? | 2012/03/14 | [
"https://Stackoverflow.com/questions/9696495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731963/"
] | It doesn't help in Python to think in terms of references or values. Neither is correct.
In Python, variables are just names. In your for loop, `loc` is just a name that points to the current element in the list. Doing `loc = []` simply *rebinds* the name `loc` to a different list, leaving the original version alone.
But since in your example, each element is a list, you could actually *mutate* that element, and that would be reflected in the original list:
```
for loc in locs:
loc[0] = loc[0] * 2
``` | >
> Why is loc not reference of elements of locs ?
>
>
>
**It is**. Or at least, it is in the same sense that every other variable in Python is. Python variables are **names, not storage**. `loc` is a name that is used to refer to elements of `[[1,2], [3,4]]`, while `locs` is a name that refers to the entire structure.
```
loc = []
```
This **does not mean** "look at the thing that `loc` names, and cause it to turn into `[]`". It **cannot** mean that, because Python objects are **not capable** of such a thing.
Instead, it means "cause `loc` to stop being a name for the thing that it's currently a name for, and start instead being a name for `[]`". (Of course, it means the specific `[]` that's provided there, since in general there may be several objects in memory that are the same.)
Naturally, the contents of `locs` are unchanged as a result. |
9,696,495 | My code :
```
locs = [ [1], [2] ]
for loc in locs:
loc = []
print locs
# prints => [ [1], [2] ]
```
Why is `loc` not reference of elements of `locs` ?
Python : Everything is passed as reference unless explicitly copied [ Is this not True ? ]
Please explain.. how does python decides **referencing and copying** ?
**Update :**
How to do ?
```
def compute(ob):
if isinstance(ob,list): return process_list(ob)
if isinstance(ob,dict): return process_dict(ob)
for loc in locs:
loc = compute(loc) # What to change here to make loc a reference of actual locs iteration ?
```
* locs must contain the final processed response !
* I don't want to use `enumerate`, is it possible without it ? | 2012/03/14 | [
"https://Stackoverflow.com/questions/9696495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731963/"
] | Effbot (aka Fredrik Lundh) has described Python's variable passing style as call-by-object: <http://effbot.org/zone/call-by-object.htm>
Objects are allocated on the heap and pointers to them can be passed around anywhere.
* When you make an assignment such as `x = 1000`, a dictionary entry is created that maps the string "x" in the current namespace to a pointer to the integer object containing one thousand.
* When you update "x" with `x = 2000`, a new integer object is created and the dictionary is updated to point at the new object. The old one thousand object is unchanged (and may or may not be alive depending on whether anything else refers to the object).
* When you do a new assignment such as `y = x`, a new dictionary entry "y" is created that points to the same object as the entry for "x".
* Objects like strings and integers are *immutable*. This simply means that there are no methods that can change the object after it has been created. For example, once the integer object one-thousand is created, it will never change. Math is done by creating new integer objects.
* Objects like lists are *mutable*. This means that the contents of the object can be changed by anything pointing to the object. For example, `x = []; y = x; x.append(10); print y` will print `[10]`. The empty list was created. Both "x" and "y" point to the same list. The *append* method mutates (updates) the list object (like adding a record to a database) and the result is visible to both "x" and "y" (just as a database update would be visible to every connection to that database).
Hope that clarifies the issue for you. | When you say
```
loc = []
```
you are rebinding the `loc` variable to a newly created empty list
Perhaps you want
```
loc[:] = []
```
Which assigns a slice (which happens to be the whole list) of loc to the empty list |
9,696,495 | My code :
```
locs = [ [1], [2] ]
for loc in locs:
loc = []
print locs
# prints => [ [1], [2] ]
```
Why is `loc` not reference of elements of `locs` ?
Python : Everything is passed as reference unless explicitly copied [ Is this not True ? ]
Please explain.. how does python decides **referencing and copying** ?
**Update :**
How to do ?
```
def compute(ob):
if isinstance(ob,list): return process_list(ob)
if isinstance(ob,dict): return process_dict(ob)
for loc in locs:
loc = compute(loc) # What to change here to make loc a reference of actual locs iteration ?
```
* locs must contain the final processed response !
* I don't want to use `enumerate`, is it possible without it ? | 2012/03/14 | [
"https://Stackoverflow.com/questions/9696495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731963/"
] | It doesn't help in Python to think in terms of references or values. Neither is correct.
In Python, variables are just names. In your for loop, `loc` is just a name that points to the current element in the list. Doing `loc = []` simply *rebinds* the name `loc` to a different list, leaving the original version alone.
But since in your example, each element is a list, you could actually *mutate* that element, and that would be reflected in the original list:
```
for loc in locs:
loc[0] = loc[0] * 2
``` | Everything is passed by object. Rebinding and mutating are different operations.
```
locs = [ [1], [2] ]
for loc in locs:
del loc[:]
print locs
``` |
9,696,495 | My code :
```
locs = [ [1], [2] ]
for loc in locs:
loc = []
print locs
# prints => [ [1], [2] ]
```
Why is `loc` not reference of elements of `locs` ?
Python : Everything is passed as reference unless explicitly copied [ Is this not True ? ]
Please explain.. how does python decides **referencing and copying** ?
**Update :**
How to do ?
```
def compute(ob):
if isinstance(ob,list): return process_list(ob)
if isinstance(ob,dict): return process_dict(ob)
for loc in locs:
loc = compute(loc) # What to change here to make loc a reference of actual locs iteration ?
```
* locs must contain the final processed response !
* I don't want to use `enumerate`, is it possible without it ? | 2012/03/14 | [
"https://Stackoverflow.com/questions/9696495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731963/"
] | When you say
```
loc = []
```
you are rebinding the `loc` variable to a newly created empty list
Perhaps you want
```
loc[:] = []
```
Which assigns a slice (which happens to be the whole list) of loc to the empty list | >
> Why is loc not reference of elements of locs ?
>
>
>
**It is**. Or at least, it is in the same sense that every other variable in Python is. Python variables are **names, not storage**. `loc` is a name that is used to refer to elements of `[[1,2], [3,4]]`, while `locs` is a name that refers to the entire structure.
```
loc = []
```
This **does not mean** "look at the thing that `loc` names, and cause it to turn into `[]`". It **cannot** mean that, because Python objects are **not capable** of such a thing.
Instead, it means "cause `loc` to stop being a name for the thing that it's currently a name for, and start instead being a name for `[]`". (Of course, it means the specific `[]` that's provided there, since in general there may be several objects in memory that are the same.)
Naturally, the contents of `locs` are unchanged as a result. |
9,696,495 | My code :
```
locs = [ [1], [2] ]
for loc in locs:
loc = []
print locs
# prints => [ [1], [2] ]
```
Why is `loc` not reference of elements of `locs` ?
Python : Everything is passed as reference unless explicitly copied [ Is this not True ? ]
Please explain.. how does python decides **referencing and copying** ?
**Update :**
How to do ?
```
def compute(ob):
if isinstance(ob,list): return process_list(ob)
if isinstance(ob,dict): return process_dict(ob)
for loc in locs:
loc = compute(loc) # What to change here to make loc a reference of actual locs iteration ?
```
* locs must contain the final processed response !
* I don't want to use `enumerate`, is it possible without it ? | 2012/03/14 | [
"https://Stackoverflow.com/questions/9696495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731963/"
] | Everything in Python is passed and assigned by value, in the same way that everything is passed and assigned by value in Java. Every value in Python is a reference (pointer) to an object. Objects cannot be values. Assignment always copies the value (which is a pointer); two such pointers can thus point to the same object. Objects are never copied unless you're doing something explicit to copy them.
For your case, every iteration of the loop assigns an element of the list into the variable `loc`. You then assign something else to the variable `loc`. All these values are pointers; you're assigning pointers; but you do not affect any objects in any way. | Everything is passed by object. Rebinding and mutating are different operations.
```
locs = [ [1], [2] ]
for loc in locs:
del loc[:]
print locs
``` |
9,696,495 | My code :
```
locs = [ [1], [2] ]
for loc in locs:
loc = []
print locs
# prints => [ [1], [2] ]
```
Why is `loc` not reference of elements of `locs` ?
Python : Everything is passed as reference unless explicitly copied [ Is this not True ? ]
Please explain.. how does python decides **referencing and copying** ?
**Update :**
How to do ?
```
def compute(ob):
if isinstance(ob,list): return process_list(ob)
if isinstance(ob,dict): return process_dict(ob)
for loc in locs:
loc = compute(loc) # What to change here to make loc a reference of actual locs iteration ?
```
* locs must contain the final processed response !
* I don't want to use `enumerate`, is it possible without it ? | 2012/03/14 | [
"https://Stackoverflow.com/questions/9696495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731963/"
] | Everything in Python is passed and assigned by value, in the same way that everything is passed and assigned by value in Java. Every value in Python is a reference (pointer) to an object. Objects cannot be values. Assignment always copies the value (which is a pointer); two such pointers can thus point to the same object. Objects are never copied unless you're doing something explicit to copy them.
For your case, every iteration of the loop assigns an element of the list into the variable `loc`. You then assign something else to the variable `loc`. All these values are pointers; you're assigning pointers; but you do not affect any objects in any way. | It doesn't help in Python to think in terms of references or values. Neither is correct.
In Python, variables are just names. In your for loop, `loc` is just a name that points to the current element in the list. Doing `loc = []` simply *rebinds* the name `loc` to a different list, leaving the original version alone.
But since in your example, each element is a list, you could actually *mutate* that element, and that would be reflected in the original list:
```
for loc in locs:
loc[0] = loc[0] * 2
``` |
9,696,495 | My code :
```
locs = [ [1], [2] ]
for loc in locs:
loc = []
print locs
# prints => [ [1], [2] ]
```
Why is `loc` not reference of elements of `locs` ?
Python : Everything is passed as reference unless explicitly copied [ Is this not True ? ]
Please explain.. how does python decides **referencing and copying** ?
**Update :**
How to do ?
```
def compute(ob):
if isinstance(ob,list): return process_list(ob)
if isinstance(ob,dict): return process_dict(ob)
for loc in locs:
loc = compute(loc) # What to change here to make loc a reference of actual locs iteration ?
```
* locs must contain the final processed response !
* I don't want to use `enumerate`, is it possible without it ? | 2012/03/14 | [
"https://Stackoverflow.com/questions/9696495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731963/"
] | Effbot (aka Fredrik Lundh) has described Python's variable passing style as call-by-object: <http://effbot.org/zone/call-by-object.htm>
Objects are allocated on the heap and pointers to them can be passed around anywhere.
* When you make an assignment such as `x = 1000`, a dictionary entry is created that maps the string "x" in the current namespace to a pointer to the integer object containing one thousand.
* When you update "x" with `x = 2000`, a new integer object is created and the dictionary is updated to point at the new object. The old one thousand object is unchanged (and may or may not be alive depending on whether anything else refers to the object).
* When you do a new assignment such as `y = x`, a new dictionary entry "y" is created that points to the same object as the entry for "x".
* Objects like strings and integers are *immutable*. This simply means that there are no methods that can change the object after it has been created. For example, once the integer object one-thousand is created, it will never change. Math is done by creating new integer objects.
* Objects like lists are *mutable*. This means that the contents of the object can be changed by anything pointing to the object. For example, `x = []; y = x; x.append(10); print y` will print `[10]`. The empty list was created. Both "x" and "y" point to the same list. The *append* method mutates (updates) the list object (like adding a record to a database) and the result is visible to both "x" and "y" (just as a database update would be visible to every connection to that database).
Hope that clarifies the issue for you. | >
> Why is loc not reference of elements of locs ?
>
>
>
**It is**. Or at least, it is in the same sense that every other variable in Python is. Python variables are **names, not storage**. `loc` is a name that is used to refer to elements of `[[1,2], [3,4]]`, while `locs` is a name that refers to the entire structure.
```
loc = []
```
This **does not mean** "look at the thing that `loc` names, and cause it to turn into `[]`". It **cannot** mean that, because Python objects are **not capable** of such a thing.
Instead, it means "cause `loc` to stop being a name for the thing that it's currently a name for, and start instead being a name for `[]`". (Of course, it means the specific `[]` that's provided there, since in general there may be several objects in memory that are the same.)
Naturally, the contents of `locs` are unchanged as a result. |
9,696,495 | My code :
```
locs = [ [1], [2] ]
for loc in locs:
loc = []
print locs
# prints => [ [1], [2] ]
```
Why is `loc` not reference of elements of `locs` ?
Python : Everything is passed as reference unless explicitly copied [ Is this not True ? ]
Please explain.. how does python decides **referencing and copying** ?
**Update :**
How to do ?
```
def compute(ob):
if isinstance(ob,list): return process_list(ob)
if isinstance(ob,dict): return process_dict(ob)
for loc in locs:
loc = compute(loc) # What to change here to make loc a reference of actual locs iteration ?
```
* locs must contain the final processed response !
* I don't want to use `enumerate`, is it possible without it ? | 2012/03/14 | [
"https://Stackoverflow.com/questions/9696495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731963/"
] | Effbot (aka Fredrik Lundh) has described Python's variable passing style as call-by-object: <http://effbot.org/zone/call-by-object.htm>
Objects are allocated on the heap and pointers to them can be passed around anywhere.
* When you make an assignment such as `x = 1000`, a dictionary entry is created that maps the string "x" in the current namespace to a pointer to the integer object containing one thousand.
* When you update "x" with `x = 2000`, a new integer object is created and the dictionary is updated to point at the new object. The old one thousand object is unchanged (and may or may not be alive depending on whether anything else refers to the object).
* When you do a new assignment such as `y = x`, a new dictionary entry "y" is created that points to the same object as the entry for "x".
* Objects like strings and integers are *immutable*. This simply means that there are no methods that can change the object after it has been created. For example, once the integer object one-thousand is created, it will never change. Math is done by creating new integer objects.
* Objects like lists are *mutable*. This means that the contents of the object can be changed by anything pointing to the object. For example, `x = []; y = x; x.append(10); print y` will print `[10]`. The empty list was created. Both "x" and "y" point to the same list. The *append* method mutates (updates) the list object (like adding a record to a database) and the result is visible to both "x" and "y" (just as a database update would be visible to every connection to that database).
Hope that clarifies the issue for you. | Everything is passed by object. Rebinding and mutating are different operations.
```
locs = [ [1], [2] ]
for loc in locs:
del loc[:]
print locs
``` |