Unnamed: 0
int64 0
1.91M
| id
int64 337
73.8M
| title
stringlengths 10
150
| question
stringlengths 21
64.2k
| answer
stringlengths 19
59.4k
| tags
stringlengths 5
112
| score
int64 -10
17.3k
|
---|---|---|---|---|---|---|
1,906,200 | 69,878,375 |
How to create tree structure from hierarchical data in Python?
|
<p>Hi I am a bit new to Python and am a bit confused how to proceed. I have a large dataset that contains both parent and child information. For example, if we have various items and their components, and their components also have other components or children, how do we create a type of tree structure? Here is an example of the data:
<a href="https://i.stack.imgur.com/FkhAO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FkhAO.png" alt="enter image description here" /></a></p>
<p>I was wondering how I can get it into a tree structure. So the output would be:</p>
<p><a href="https://i.stack.imgur.com/hSzeq.png" rel="nofollow noreferrer">Tree structure for car</a></p>
<p>and it will also return the one for airplane, similar to the one for car.</p>
<p>I know that the common attribute for this would be based upon the parent number/child number. But, I am a bit confused on how to go about this in python.</p>
|
<p>Problems like this always come down to algorithm and data set. The first thing I notice about your data set is that it is ordered such that no child is ever the parent of a previous parent. In other words, the items are listed in a "top-down" fashion. Is this always to be true? If it is, it means the logic of the algorithm becomes much simpler.</p>
<p>Another consideration is data structure. I would use nested dictionaries to hold the main data set here. Each new unique parent will be a "key" of the main dict. And each "value" corresponding to that key will be a dict, and the nesting can continue on and on as needed. In this case, there will only be few levels of nesting.</p>
<p>So, for each line in the data set, you would check if the Parent appears as a key in the top dict or any of the nested dicts. If it does not, you'll create a new entry in the top level dict with Parent as the key, and {Child:{}} as the new entry's value. (This will happen for "car" and "airplane".)</p>
<p>If the current Parent DOES appear as a key in any of the dicts, you need to add the Child value as a new key to the dict that is the value of the dict which has Parent as a key. In that instance, Child is the new key, and the value for that key is the empty dict {}.</p>
<p>The above is the rough logic I would use to write the code. I leave that part to you. There may be third party libraries you can use to make the effort much less, but if you're taking a class and this is an assignment, your teacher may not want you to use such external libraries.</p>
<p>Note that the above logic assumes that the data set is organized as "top-down." If that is not the case, then the logic becomes more complicated, and a key that is currently at a certain level in the hierarchy might be bumped down the hierarchy if a new Parent to that Child is processed in the data set.</p>
|
python
| 0 |
1,906,201 | 69,878,848 |
Python Elasticsearch : Index mapping inconsistencies between ‘es.index’ and ‘es.indices.create’
|
<p>I'm trying to implement a custom index mapping (my_mapping) in Python, BUT, I do not get the expected index mapping after the python file is run!</p>
<pre class="lang-py prettyprint-override"><code>my_mapping = """
{
"settings": {
"number_of_shards": "1",
"number_of_replicas": "1"
},
"mappings": {
"properties": {
"site": {
"type": "completion",
},
"geometry": {
"type": "geo_shape"
}
}
}
}"""
result = es.index(index='my_index', document=my_mapping)
</code></pre>
<p>Expected Output:</p>
<pre><code>{
"mappings": {
"_doc": {
"properties": {
"geometry": {
"type": "geo_shape"
},
"site": {
"type": "completion",
"analyzer": "simple",
"preserve_separators": true,
"preserve_position_increments": true,
"max_input_length": 200
}
}
}
}
}
</code></pre>
<p>Actual output:</p>
<pre><code>{
"mappings": {
"_doc": {
"properties": {
"mappings": {
"properties": {
"properties": {
"properties": {
"geometry": { ...........
</code></pre>
<p>BUT! NOTE that when I instead use the following python to create the index, I DO get the expected outcome.</p>
<pre class="lang-py prettyprint-override"><code>result = es.index(index='my_index', document=my_mapping)
</code></pre>
<p>Can someone please explain to me the inconsistency, and HOW to generate the expected outcome USING es.index</p>
|
<p>Answers from <a href="https://discuss.elastic.co/t/python-elasticsearch-index-mapping-inconsistencies-between-es-index-and-es-indices-create/288584" rel="nofollow noreferrer">https://discuss.elastic.co/t/python-elasticsearch-index-mapping-inconsistencies-between-es-index-and-es-indices-create/288584</a></p>
<p>“The es.index is meant to index documents. Not to call the create index API.”</p>
<p>On the other hand, Es.indices.create Creates an index with optional settings and mappings.</p>
|
python|elasticsearch|kibana|elastic-stack
| 1 |
1,906,202 | 55,736,121 |
TypeError when calling an object's attribute in a little card game
|
<p>I'm writing a card game.</p>
<p>I have made a 'card' class, and a deck class with card objects in it as an attribute. I successfully made up functions to shuffle, to print the deck cards list, to print the remaining card in the deck and to make a functioning "draw" system.
Now I'm trying to give to every Card an attribute ("Briscola" = True/False) based on the card's seed (A first card is drawn by the dealer, its seed is considered then the value of Briscola is changed to True for every card matching that exctracted seed) but i encountered 2 problems.</p>
<p>When I try to run </p>
<pre><code>prova = Mazzo()
prova.inizio()
</code></pre>
<p>the "inizo" method (which should pick a card and do the seed stuff) gives out this TypeError:</p>
<pre><code>in inizio
print('La briscola è', self.semi[brisc.Seme])
TypeError: 'str' object is not callable
</code></pre>
<p>Here is what i wrote:</p>
<pre><code>import random
class Carta:
semi = ['Bastoni', 'Spade', 'Coppe', 'Denari']
numeri = ['1', '2', '3', '4', '5', '6', '7', 'Fante', 'Cavallo', 'Re']
briscola = None
def __init__(self, Seme = 0, Valore = 0, Briscola = False):
self.Seme = Seme
self.Valore = Valore
self.Briscola = Briscola
def __str__(self):
return (self.numeri[self.Valore] + " di " +
self.semi[self.Seme])
class Mazzo:
semi = ['Bastoni', 'Spade', 'Coppe', 'Denari']
numeri = ['1', '2', '3', '4', '5', '6', '7', 'Fante', 'Cavallo', 'Re']
def __init__(self):
self.Carte = []
for seme in range(4):
for valore in range(10):
self.Carte.append(Carta(seme,valore))
def inizio(self):
brisc = random.choice(self.Carte)
print = ('-------------La partita è iniziata!-------------')
print('La carta iniziale è ' , brisc)
print('La briscola è', self.semi[brisc.Seme])
for carta in self.Carte:
if carta.Seme == brisc.Seme:
carta.Briscola = True
self.Carte.remove(brisc)
</code></pre>
<p>I'm sorry but variable names are in my native language. Here is some translation for better understanding:
carta/e = card/s seme/i = seed/s Mazzo = deck numeri = numbers prova = foo</p>
|
<pre><code>print = ('-------------La partita è iniziata!-------------')
</code></pre>
<p>That line reassigns the <code>print()</code> function to be a plain string, and it's not a function anymore.</p>
<p>So the next time you call <code>print('something')</code>, you get an error.</p>
<p>Presumably that's a typo, and you didn't mean to have the <code>=</code> in there.</p>
|
python|string
| 1 |
1,906,203 | 55,813,086 |
How to use a value in a JSON file within an if statement
|
<p>I'm trying to create an if statement based on the value from an API I'm using. This API contains a status code value, <code>"status"</code>. if this is 404 (or others) I want to return an error, else carry on. </p>
<p>An example of the JSON:</p>
<pre><code>{
"data": {
"test_index": {
"test_a": [...], // 429 items
"test_b": [...] // 182 items
}
},
"status": 200
}
</code></pre>
<p>When running the code below:</p>
<pre><code>import json
import urllib.request as ur
API = ur.urlopen('https://example.com')
data = json.loads(API.read())
if data['status'][0] == 404:
print("404")
else:
print("Not 404")
</code></pre>
<p>I get the following error:</p>
<pre><code>TypeError: 'int' object is not subscriptable
</code></pre>
<p>Which is referring to line 7, the if statement.</p>
<p>How do I convert this JSON value to something I can work with?</p>
|
<p><code>data['status']</code> is an integer, and you cannot subscript an integer with an index, like you do for a list, Change your code as follows.</p>
<pre><code>if data['status'] == 404:
print("404")
else:
print("Not 404")
</code></pre>
|
python|json
| 0 |
1,906,204 | 49,852,455 |
How to find the Null Space of a matrix in Python using numpy?
|
<p>As the title says, how can I find the null space of a matrix
i.e. the <em>nontrivial</em> solution to the equation ax=0.</p>
<p>I've tried to use <code>np.linalg.solve(a,b)</code>, which solves the equation ax=b. So setting <code>b</code> equal to an array of zeros with the same dimensions as matrix <code>a</code>, I only get the <em>trivial</em> solution i.e. x=0.</p>
|
<p>From <a href="http://scipy-cookbook.readthedocs.io/items/RankNullspace.html" rel="nofollow noreferrer">SciPy Cookbook</a>:</p>
<pre><code>import numpy as np
from numpy.linalg import svd
def nullspace(A, atol=1e-13, rtol=0):
A = np.atleast_2d(A)
u, s, vh = svd(A)
tol = max(atol, rtol * s[0])
nnz = (s >= tol).sum()
ns = vh[nnz:].conj().T
return ns
</code></pre>
<p>Computes an approximate basis for the nullspace of <code>A</code>.</p>
<p>The algorithm used by this function is based on the singular value decomposition of <code>A</code>.</p>
<p><strong>Parameters</strong>:</p>
<p><code>A</code> : ndarray</p>
<p><code>A</code> should be at most 2-D. A 1-D array with length k will be treated as a 2-D with shape (1, k)</p>
<p><code>atol</code> : float</p>
<p>The absolute tolerance for a zero singular value. Singular values smaller than <code>atol</code> are considered to be zero.</p>
<p><code>rtol</code> : float</p>
<p>The relative tolerance. Singular values less than rtol*smax are considered to be zero, where smax is the largest singular value.</p>
<p>If both <code>atol</code> and <code>rtol</code> are positive, the combined tolerance is the maximum of the two; that is:</p>
<pre><code>tol = max(atol, rtol * smax)
</code></pre>
<p>Singular values smaller than <code>tol</code> are considered to be zero.</p>
<p><strong>Return value</strong>:</p>
<p><code>ns</code> : ndarray</p>
<p>If <code>A</code> is an array with shape (m, k), then <code>ns</code> will be an array with shape (k, n), where n is the estimated dimension of the nullspace of <code>A</code>. The columns of <code>ns</code> are a basis for the nullspace; each element in numpy.dot(A, ns) will be approximately zero.</p>
|
python|numpy
| 3 |
1,906,205 | 49,930,710 |
python unicode to list, reciving double double quotes
|
<p>I'm doing some fetching via tornado websocket and recive json data like this:</p>
<pre><code>msg = [157,"tu","27213579-SD",229156181,1524173145,8265,0.08]
</code></pre>
<p>type(msg) -> unicode</p>
<p>now I have to convert it into datatype list.
My first intention was the following:</p>
<pre><code>msg = [e.encode('utf-8') for e in msg.strip('[]').split(',')]
</code></pre>
<p>but now there are double quotes</p>
<pre><code>msg =["157",""tu"",""27213579-SD"","229156181","1524173145","8265","0.08"]
</code></pre>
<p>Do you know a smart way to get a clean python list?</p>
|
<p>Use the <code>json</code> module to convert JSON to data:</p>
<pre><code>#!python2
import json
msg = u'[157,"tu","27213579-SD",229156181,1524173145,8265,0.08]'
print type(msg)
data = json.loads(msg)
print type(data)
print data
</code></pre>
<p>Output:</p>
<pre><code><type 'unicode'>
<type 'list'>
[157, u'tu', u'27213579-SD', 229156181, 1524173145, 8265, 0.08]
</code></pre>
|
python|list|unicode
| 0 |
1,906,206 | 66,748,429 |
opencv_annotation error message; 'opencv_annotation' is not recognized as an internal or external command, operable program or batch file
|
<p>I want to use OpenCV's integrated annotation tool as per <a href="https://docs.opencv.org/4.5.1/dc/d88/tutorial_traincascade.html" rel="nofollow noreferrer">https://docs.opencv.org/4.5.1/dc/d88/tutorial_traincascade.html</a>.</p>
<p>The tutorial says this command will open up a window containing the images for you to annotate using your cursor.</p>
<pre><code>opencv_annotation --annotations=/path/to/annotations/file.txt --images=/path/to/image/folder/
</code></pre>
<p>But when I try to use it:</p>
<pre><code># Attempt 1
opencv_annotation --annotations=C:\Users\my_user\po_images\pos_anno.txt --images=C:\Users\my_user\po_images
# Attempt 2
opencv_annotation --annotations=\Users\my_user\po_images\pos_anno.txt --images=\Users\my_user\po_images
# Attempt 3
opencv_annotation --annotations \Users\my_user\po_images\pos_anno.txt --images \Users\my_user\po_images\
</code></pre>
<p>I get an error message:</p>
<pre><code>'opencv_annotation' is not recognized as an internal or external command,
operable program or batch file.
</code></pre>
<p>I've definitely got openCV installed:</p>
<pre><code>C:\Users\my_user>pip show opencv-python
Name: opencv-python
Version: 4.5.1.48
</code></pre>
<p>So where am I going wrong?</p>
<p>I'm on Python 3.9.1, Windows 10.</p>
<p>Thanks!</p>
|
<p>( Please Note That The Following Solution is based on Windows OS , Other Platforms may Not be Compatible with the Following Solution )</p>
<p>I think the <code>opencv_annotation</code> is excluded in opencv 4.5.1 ?</p>
<p>I'm also using opencv 4.5.3 and the <code>opencv_annotation</code> is not a command-line tool ( I think )</p>
<p>Maybe you can follow this youtube video ( <a href="https://www.youtube.com/watch?v=XrCAvs9AePM&t=605s" rel="nofollow noreferrer">Training a Cascade Classifier - OpenCV Object Detection in Games #8</a> ) or the same <a href="https://learncodebygaming.com/blog/training-a-cascade-classifier" rel="nofollow noreferrer">text-based tutorial</a> to create positive and negative samples. I'll also describe how I make these samples below ( the “<em>Handling Positive Samples</em>” section may solve your issue ( maybe ) ) :</p>
<h1>My Dir. Structure</h1>
<pre><code>main.py
img_source
Source1
Positive
img1.png
img2.png
...
Negative
img1.png
img2.png
...
Source2
Positive
img1.png
img2.png
...
Negative
img1.png
img2.png
...
...
</code></pre>
<p>// Please Note that All the Python Code Below is Run Inside the <code>main.py</code></p>
<h1>Collecting Samples</h1>
<p>I just searched online and screenshot it manually by myself. Note that you may don't need to crop it</p>
<p>for negative samples : I just randomly take some unrelated pictures or search online and dump them into the <code>Negative</code> dir.</p>
<p>for positive samples : I just manually take screenshots of it + collect from online</p>
<h1>Handling Negative Samples</h1>
<p>create a file called <code>bg.txt</code> and run the following code to add each image path to the <code>bg.txt</code> in each <code>Negative</code> folder</p>
<pre><code>import os
img_source_dir = os.path.join(os.getcwd(), <image source>)
_ = os.listdir(img_source_dir)
for sources in _:
os.chdir(os.path.join(img_source_dir, sources))
if not os.path.exists(os.path.join(img_source_dir, sources, "Negative")):
os.mkdir("Negative")
os.chdir("./Negative")
f = open("bg.txt", "w")
content = ""
for file in os.listdir("."):
if j != "bg.txt":
content += os.path.join(img_source_dir, sources, "Negative", file) + "\n"
f.write(content)
f.close()
</code></pre>
<h1>Handling Positive Samples ( the major answer for your question )</h1>
<p>Since the <code>opencv_annotation</code> etc. cannot be found , I downloaded the <code>opencv-3.4.11-vc14_vc15.exe</code> from <a href="https://sourceforge.net/projects/opencvlibrary/files/3.4.11/" rel="nofollow noreferrer">SOURCEFORGE</a></p>
<p>Run the downloaded file ( should be .exe )</p>
<p>In the extracted file <code>opencv</code> , go to : <code>./build/x64/vc15/bin/</code>
and you will find <code>opencv_annotation.exe</code> <code>opencv_createsamples.exe</code> <code>opencv_traincascade.exe</code> etc. there</p>
<p>then go to the <code>\Positive</code> dir. and type what you did before</p>
<p>in my case :</p>
<pre><code>C:\Users\PAUL\Downloads\opencv\build\x64\vc15\bin\opencv_annotation.exe --annotations=positive.txt --images=./
</code></pre>
<p>follow the instruction to crop the positive image , remember to press key "c" to accept the selection</p>
<p>when done , it will create a file called <code>positive.txt</code> in the <code>./Positive</code> dir. containing [ img_path number_of_sample_for_each_img coordinates ]</p>
<p>then we will need to create a vector file from these positive annotations , by :</p>
<p>in my case :</p>
<pre><code>C:\Users\PAUL\Downloads\opencv\build\x64\vc15\bin\opencv_createsamples.exe -info positive.txt -w 24 -h 24 -num 1000 -vec positive.vec
</code></pre>
<p>it will create a <code>positive.vec</code> file from the given information in <code>Positive.txt</code> ( in the same dir. ) containing [<= 1000] vectors ( from <code>-num</code> )</p>
<ul>
<li>for lazy guy like me :</li>
</ul>
<p>the following code will create a <code>\Positive</code> dir. inside the <code><image source>\<sources></code> dir. and will annotate + create [<= 1000] vectors for each set of sources ( like what we did above )</p>
<p>in my case :</p>
<pre><code>import os
img_source_dir = os.path.join(os.getcwd(), <image source>)
_ = os.listdir(img_source_dir)
for sources in _:
if not os.path.exists(os.path.join(img_source_dir, sources, "Positive")):
os.mkdir(os.path.join(img_source_dir, sources, "Positive"))
os.chdir(os.path.join(img_source_dir, sources, "Positive"))
# annotate
os.system("C:/Users/PAUL/Downloads/opencv/build/x64/vc15/bin/opencv_annotation.exe --annotations=positive.txt --images=./")
# create samples
os.system("C:/Users/PAUL/Downloads/opencv/build/x64/vc15/bin/opencv_createsamples.exe -info positive.txt -w 24 -h 24 -num 1000 -vec positive.vec")
</code></pre>
<h1>The Updated Dir. Structure</h1>
<p>also create a <code>\cascade</code> folder in each source for our trained cascades</p>
<pre><code>main.py
img_source
Source1
Positive
img1.png
img2.png
...
positive.txt
positive.vec
Negative
img1.png
img2.png
...
bg.txt
cascade
Source2
Positive
img1.png
img2.png
...
positive.txt
positive.vec
Negative
img1.png
img2.png
...
bg.txt
cascade
...
</code></pre>
<ul>
<li>for lazy guy like me :</li>
</ul>
<pre><code># create the cascade folder for each source
import os
img_source_dir = os.path.join(os.getcwd(), <image source>)
_ = os.listdir(img_source_dir)
for sources in _:
os.chdir(os.path.join(img_source_dir, sources))
if not os.path.exists(os.path.join(img_source_dir, sources, "cascade")):
os.mkdir("cascade")
</code></pre>
<h1>Train Cascade Classifier Model</h1>
<p>Go to the <code>Source</code> dir. which contain the <code>Positive</code> <code>Negative</code>
and <code>cascade</code> folder</p>
<p>For each <code>Source</code> dir. :
Use the following command to train the cascade :</p>
<p>in my case :</p>
<pre><code>C:/Users/PAUL/Downloads/opencv/build/x64/vc15/bin/opencv_traincascade.exe -data ./cascade/ -vec ./Positive/positive.vec -bg ./Negative/bg.txt -w 24 -h 24 -numPos 200 -numNeg 100 -numStages 20
</code></pre>
<p>It will create <code>.xml</code> files in the <code>\cascade</code> dir. using the information given e.g. <code>positive.vec</code> in <code>\Positive\</code> folder , <code>bg.txt</code> in <code>\Negative\</code> folder , etc.</p>
<p>If you get errors like</p>
<pre><code>OpenCV: terminate handler is called! The last OpenCV error is:
...
Can not get new positive sample
</code></pre>
<p>You may either lower the <code>-numPos</code> or the <code>-minHitRate</code></p>
<h1>Implementation</h1>
<p>Below we will use <code>opencv</code> and <code>PIL</code> ( Pillow ) to detect obj. in one single image by using the cascade generated above</p>
<pre><code>import cv2
from PIL import ImageGrab, Image # ImageGrab for screenshot ; Image for loading img.
import numpy as np
import os
# screenshot
# _screenshot = ImageGrab.grab()
# _frame = cv2.cvtColor(np.array(_screenshot), cv2.COLOR_BGR2RGB)
# test img.
img = Image.open(os.path.join(<path to where the img locate>))
_frame = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)
# load the trained models
cascade = cv2.CascadeClassifier(<path to where the cascade.xml locate>)
# object detection
rect = cascade.detectMultiScale(_frame)
"""
rectangle(s) detected of structure :
[ [x, y, w, h]
[x, y, w, h]
...]
where x and y is the x- y- coordinate in the img ;
w and h is the width and height relative to the x, y coordinate
"""
for x, y, width, height in rect:
# draw rectangle on the _frame
# color --> (r, g, b)
cv2.rectangle(_frame, pt1 = (x, y), pt2 = (x + height, y + width), color = (255, 0, 0), thickness = 2)
# visualize it
# display the images
cv2.imshow("title", _frame)
cv2.waitKey(0)
</code></pre>
<h1>Reference</h1>
<ul>
<li>OpenCV Doc. : <a href="https://docs.opencv.org/3.4/dc/d88/tutorial_traincascade.html" rel="nofollow noreferrer">Cascade Classifier Training</a></li>
<li>Text-based Tutorial by Ben : <a href="https://learncodebygaming.com/blog/training-a-cascade-classifier" rel="nofollow noreferrer">Training a Cascade Classifier</a></li>
<li>SOURCEFORGE : <a href="https://sourceforge.net/projects/opencvlibrary/files/3.4.11/" rel="nofollow noreferrer">Where I download the <code>opencv-3.4.11-vc14_vc15.exe</code></a></li>
</ul>
<h1>Code Snippet</h1>
<ul>
<li>Get Number of Positive and Negative Samples from Each Source</li>
</ul>
<p>Just in case you need it</p>
<pre><code>import os
img_source_dir = os.path.join(os.getcwd(), <image source>)
_ = os.listdir(img_source_dir)
for sources in _:
print(sources)
# positive
if os.path.exists(os.path.join(img_source_dir, sources, "Positive", "positive.txt")):
f = open(os.path.join(img_source_dir, sources, "Positive", "positive.txt"), "r")
content = f.read()
f.close()
content = content.strip().split("\n")
n = 0
for line in content:
tmp = line.split(" ")
if int(tmp[1]) > 0:
n += int(tmp[1])
print(f"Positive Samples : {n}")
# negative
if os.path.exists(os.path.join(img_source_dir, sources, "Negative", "bg.txt")):
f = open(os.path.join(img_source_dir, sources, "Negative", "bg.txt"), "r")
content = f.readlines()
print(f"Negative Samples : {len(content)}")
f.close()
print()
</code></pre>
<hr />
<p>Please correct it if anything is incorrect</p>
<p>Any suggestions are welcome : )</p>
|
python|opencv
| 0 |
1,906,207 | 64,783,171 |
merge multiple lists into one list in python using for loop
|
<p>I have a code that return the max value of each column in the dataframe until now it returns each value as a seperated list so if i have 3 values it returns 3 list each list contains one item.</p>
<p>What i want is to return one list that contains all the items.</p>
<pre><code>returned list:
[1]
[509]
[92]
[332]
[14]
expected result:
[1,509,92,332,14]
</code></pre>
<h1>code:</h1>
<pre><code>import pandas as pd
df = pd.Dataframe({'event_type': ['watch movie ', 'stay at home', 'swimming','camping','meeting'],
'year_month': ['2020-08', '2020-05', '2020-02','2020-06','2020-01'],
'event_mohafaza':['loc1','loc3','loc2','loc5','loc4'],
' number_person ':[24,39,20,10,33],})
grouped_df=pd.crosstab(df['year_month'], df[event_type])
print(type(grouped_df))
for x in grouped_df.columns:
mx = []
maxvalue =grouped_df[x].max()
mx.append(maxvalue)
print(mx)
</code></pre>
|
<p>You can just define your list before you enter the loop and print it afterwards.</p>
<pre><code>mx = []
for x in grouped_df.columns:
maxvalue = grouped_df[x].max()
mx.append(maxvalue)
print(mx)
</code></pre>
<p>You can also use the builtin <code>max</code> function.</p>
<pre><code>print(grouped_df.max())
</code></pre>
|
python|pandas|list|for-loop
| 2 |
1,906,208 | 65,037,032 |
How to re-reun a specific pytest test, based on output error
|
<p>Say if appium throws webdriver exception error, only then that specific test should re-run in pytest</p>
|
<p>Use <a href="https://github.com/pytest-dev/pytest-rerunfailures" rel="nofollow noreferrer">pytest-rerunfailures</a> library to achieve this. It is a plugin for pytest.</p>
<p>Following are the requirements to use it.</p>
<blockquote>
<p>Python 3.6, up to 3.8, or PyPy3</p>
</blockquote>
<blockquote>
<p>pytest 5.0 or newer</p>
</blockquote>
<p>Once installed you can pass <code>--only-rerun</code> argument with pytest and re-run the specific failed test.</p>
<pre><code>$ pytest --reruns 5 --only-rerun AssertionError
</code></pre>
|
python|appium|pytest|allure|pytest-mock
| 0 |
1,906,209 | 52,912,998 |
Element <option> could not be scrolled into view
|
<p>I'm trying to select a value with Selenium.</p>
<p>This is the target <strong>HTML</strong>:</p>
<pre><code> <div class="main_table">
<div class="fields filter_center clearfix" style="margin: 0 auto;">
<div class="form-group clearfix">
<div class="col-sm-8">
<select class="form-control input-sm js-example-basic-single" name="city">
<option style="padding: 3px;" value="213">New York</option>
<option style="padding: 3px;" value="2">Washington</option>
<option style="padding: 3px;" value="47">Los Angeles</option>
</code></pre>
<p>My first attempt:</p>
<pre><code>from selenium.webdriver.support.wait import WebDriverWait
region_element = Select(drv.find_element_by_tag_name("select"))
region_element.select_by_value("2")
</code></pre>
<p>This raises:</p>
<pre><code>selenium.common.exceptions.ElementNotInteractableException: Message: Element <option> could not be scrolled into view
</code></pre>
<p>My attempt 2:</p>
<pre><code>region_element = WebDriverWait(drv, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='city']")))
region_element = Select(region_element)
region_element.select_by_value("2")
</code></pre>
<p>Again:</p>
<pre><code>selenium.common.exceptions.ElementNotInteractableException: Message: Element <option> could not be scrolled into view
</code></pre>
<p>Attempt 3 (wait for the specific option to be clickable):</p>
<pre><code>region_element = WebDriverWait(drv, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='city']")))
WebDriverWait(drv, 10).until(
EC.element_to_be_clickable((By.XPATH, "//select[@name='city']/option[text()='Washington']")))
region_element = Select(region_element)
region_element.select_by_value("2")
</code></pre>
<p>Again:</p>
<pre><code>selenium.common.exceptions.ElementNotInteractableException: Message: Element <option> could not be scrolled into view
</code></pre>
<p>Could you help me correct the situation?</p>
|
<p>If the option menu its not hidden inside a wrapper, example another dropdown menu or nested page try with actions moving to it.</p>
<pre><code>from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element_by_xpath("//select[@name='city']")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
</code></pre>
<p>or with javascript executor</p>
<pre><code>driver.execute_script("arguments[0].scrollIntoView();", element)
</code></pre>
|
python|selenium|selenium-webdriver
| 1 |
1,906,210 | 53,295,150 |
how to replace item in a list with two indexes
|
<p>I'm a beginner in python and I am trying to make a hangman game but I can't seem to get it to work.
Here's my code:</p>
<pre><code>word = "street"
letters = list(word)
dashes = ["_","_","_","_","_","_"]
guess = input("Guess the letter. ") #assuming that "e" was the input
x = [index for index, value in enumerate(letters) if value == guess]
dashes[x] = guess
</code></pre>
<p>I want to replace in dashes in <code>dashes</code> that have the indexes in <code>x</code>. In the case of <code>"e"</code> being the input that means <code>dashes[3]</code> and <code>dashes[4]</code> become <code>"e"</code>. <code>dashes[x] = guess</code> doesn't seem to work.</p>
|
<p>It's easier to build a new list <code>dashes</code> and reassign the name after each guess than to maintain a list of dashes which you mutate.</p>
<p>Demo:</p>
<pre><code>>>> word = 'street'
>>> dashes = ['_']*len(word)
>>>
>>> guess = 'e'
>>> dashes = [guess if letter == guess else current
...: for letter, current in zip(word, dashes)]
>>> dashes
>>> ['_', '_', '_', 'e', 'e', '_']
>>>
>>> guess = 't'
>>> dashes = [guess if letter == guess else current
...: for letter, current in zip(word, dashes)]
>>> dashes
>>> ['_', 't', '_', 'e', 'e', 't']
</code></pre>
|
python|python-3.x|list
| 1 |
1,906,211 | 53,249,829 |
Python: Keep changes on a variable made within a function
|
<p>I have a question on a fairly simple task in python, however, I didn't manage to find a solution. I would like to assign a new value to an already existing variable in python. However, the changes I am doing to the variable within the function don't stick to the variable.</p>
<p>Here is a simplified example of my problem:</p>
<pre><code>y = 1
x = None
def test(var):
var = y
return var
test(x)
print(x)
</code></pre>
<p>The print simply returns none. So the changes I have done to the variable within the function are non permanent.</p>
<p>How can I make the changes on the input-variable of the function permanent?</p>
<p>Thanks in advance!</p>
|
<p>Variables in Python are just names which <em>refer</em> to objects. In an expression, the name is a stand-in for the actual object. Saying <code>test(x)</code> means "pass the object referred to by <code>x</code> into <code>test</code>". It does not mean "pass the symbol <code>x</code> into <code>test</code>".</p>
<p>In addition, re-assigning a name only changes what object <em>that name</em> refers to. It affects neither the object nor any of its aliases.</p>
<p>In short, the name <code>var</code> you modify inside <code>test</code> has no relation to <code>x</code> at all.</p>
<hr />
<p>The preferred way to have a function change something is by reassigning the result:</p>
<pre><code>x = 2
def change(var):
return var * 2
x = change(x) # x now refers to 4 instead of 2
print(x)
</code></pre>
<hr />
<p>If you want to change a name outside a function, you can use the <a href="https://docs.python.org/3/reference/executionmodel.html#resolution-of-names" rel="noreferrer"><code>nonlocal</code> and <code>global</code> keywords</a>:</p>
<pre><code>x = 2
def change_x():
global x
x = x * 2
change_x() # x now refers to 4 instead of 2
print(x)
</code></pre>
<p>While this can make some trivial problems easy to solve, it is generally a bad idea for larger programs. Using global variables means one can no longer use the function in isolation; results may depend on how often and in what order such a function is called.</p>
<hr />
<p>If you have some self-contained group of values and means to modify them, a class can be used to describe this:</p>
<pre><code>class XY:
def __init__(self, x, y):
self.x, self.y = x, y
def swap(self):
self.x, self.y = self.y, self.x
my_values = XY(None, 1)
print(my_values.x, my_values.y)
my_values.swap()
print(my_values.x, my_values.y)
</code></pre>
<p>In contrast to <code>global</code> variables, you can create as many isolated instances of classes as needed. Each instance can be worked on in isolation, without affecting the others.</p>
<hr />
<p>You can also use mutable values to make changes visible to the outside. Instead of changing the name, you modify the value.</p>
<pre><code>x = [2] # x is a mutable list, containing the value 2 at the moment
def change(var):
var[0] = 4 # change leading element of argument
change(x) # x now contains 4 instead of 2
print(x)
</code></pre>
|
python|function|variables
| 6 |
1,906,212 | 65,164,906 |
Count the values in a list
|
<p>The instruction is this:</p>
<p>Which genre is most likely to contain free apps?</p>
<p>First, filter data where the price is 0.00. Assign the filtered data to a new variable called free_apps. Then count the values in free_apps. Your code should return:</p>
<pre><code>Games 2257
Entertainment 334
Photo & Video 167
Social Networking 143
Education 132
Shopping 121
Utilities 109
Lifestyle 94
Finance 84
Sports 79
Health & Fitness 76
Music 67
Book 66
Productivity 62
News 58
Travel 56
Food & Drink 43
Weather 31
Navigation 20
Reference 20
Business 20
Catalogs 9
Medical 8
Name: prime_genre, dtype: int64
</code></pre>
<p>But trying to apply functions all I get are errors or a count like this:</p>
<pre><code>free_apps = data[data["price"] == 0.00]
free_apps.count_values()
AttributeError: 'DataFrame' object has no attribute 'count_values'
</code></pre>
<p>or</p>
<pre><code>free_apps = data[data["price"] == 0.00]
free_apps = free_apps.count()
free_apps
id 4056
track_name 4056
size_bytes 4056
price 4056
rating_count_tot 4056
rating_count_ver 4056
user_rating 4056
user_rating_ver 4056
prime_genre 4056
dtype: int64
</code></pre>
<p>what I try to do to obtain the count of the values for each of the genres that has a price equal to 0.00, but i don't get it.</p>
|
<p>The function you are looking for is <code>value_counts</code> for <code>pd.Series</code> and <code>count</code> for <code>pd.DataFrame</code>.</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.count.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.count.html</a></p>
|
python|list|dataframe|filter|count
| 2 |
1,906,213 | 68,745,234 |
Python mecab package import error on Windows 'not defined'
|
<p>I am trying to install mecab on English OS Windows 10. I am using the command prompt and simply did;</p>
<pre><code>pip install mecab
</code></pre>
<p>It looked like the package was installed;</p>
<pre><code>Collecting mecab
Using cached mecab-0.996.3-cp39-cp39-win_amd64.whl (500 kB)
Installing collected packages: mecab
Successfully installed mecab-0.996.3
</code></pre>
<p>But then, if I go to python (by typing 'python' in the command line) and do;</p>
<pre><code>import mecab
</code></pre>
<p>I get this error.</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'mecab'
</code></pre>
<p>If I try to import MeCab.py file, I get;</p>
<pre><code>ImportError: DLL load failed while importing _MeCab: The specified module could not be found.
</code></pre>
<p>I set PYTHONPATH in the environmental variables. No luck.</p>
|
<p>The <code>mecab</code> package on pypi <a href="https://pypi.org/project/mecab/" rel="nofollow noreferrer">requires you to install MeCab</a> separately if you are using a platform other than 32bit Python on Windows.</p>
<p>If you use <code>mecab-python3</code> 32bit Python on Windows is not supported, but for other platforms you do not need to install MeCab separately.</p>
<p>It looks like you are using 64bit Python so <code>mecab-python3</code> would fix your issue.</p>
<p>Also rarely sometimes installs on Windows don't get included DLL files. I've never been able to figure out why this happens but it's usually some kind of Python configuration issue, often related to conda. Check if your <code>site-packages</code> directory with the MeCab package has a <code>mecab.dll</code> or similar file.</p>
|
python|import|module|site-packages|mecab
| 3 |
1,906,214 | 10,694,364 |
Inserting Geolocation Coordinates Into Django Meta Form Field
|
<p>I'm wading – carefully – into some basic geolocation using HTML5. I currently have a meta form for my first Django application that has space for lat and long coordinates and have found the proper code to obtain those coordinates using the Google Maps API (pretty simple stuff).</p>
<p>Next step: inserting those coordinates automatically into the meta form when a user access the application. The application would ideally allow users to make posts and store their coordinates for future reference and filtering (that part is the big endeavor; one step at a time).</p>
<p>Using JavaScript (which I know very little) with Django in this manner seems to be the most efficient manner to accomplish this and was looking to see if there's a straightforward method for doing this. I found some ways to accomplish this that may work using jQuery, but with the meta form automatically setting up the form's structure it doesn't seem as if there's a simple way to add an "id" to the form (researched but can't seem to find a means).</p>
<p>Any insight or experience that can shared would be greatly appreciated.</p>
<pre><code>Model:
class Story(models.Model):
objects = StoryManager()
title = models.CharField(max_length=100)
topic = models.CharField(max_length=50)
copy = models.TextField()
author = models.ForeignKey(User, related_name="stories")
zip_code = models.CharField(max_length=10)
latitude = models.FloatField(blank=False, null=False)
longitude = models.FloatField(blank=False, null=False)
date = models.DateTimeField(auto_now=True, auto_now_add=True)
pic = models.ImageField(upload_to='pictures', blank=True)
caption = models.CharField(max_length=100, blank=True)
def __unicode__(self):
return " %s" % (self.title)
Form:
class StoryForm(forms.ModelForm):
class Meta:
model = Story
exclude = ('author',)
</code></pre>
|
<p>Django is usually pointed towards <a href="http://ru.wikipedia.org/wiki/REST" rel="nofollow">RESTful</a> apps so every existing object should have its own URL to edit (even if it's AJAX). So good URL will look something like <code>/obj/123/edit/</code> for editing existing object and <code>/obj/create/</code> for creating a new one. Actually, in perfect REST you can use very few URLS for all CRUD activity, but this is good enough too. So you have object ID in your URL and don't need to duplicate it in your form.</p>
<p>Or you can always display a hidden input in your form with <code>value="{{ form.instance.pk }}"</code> and manually process it in the view.</p>
|
python|django|django-forms
| 1 |
1,906,215 | 10,563,436 |
passing a string with multiple arguments
|
<p>I'm new to python. I'm using python 3.1.2 I've to communicate to the xml-rpc server through my code. From my code, I'm calling the client.py that will in-turn connect to the server to get the lists of comments from the server.</p>
<p>The working code:</p>
<pre class="lang-python prettyprint-override"><code>class xmlrpc:
def connect(self, webaddr):
self.server = ServerProxy(webaddr)
</code></pre>
<p>Listing the method:-</p>
<pre><code>my_list = self.server.tests.getTests()
</code></pre>
<p>the above method is working, but, whereas i've constraint to set the <code>tests.getTests()</code> into a single <code>cmd_str</code> like below </p>
<pre><code>my_list = self.server.cmd_str
</code></pre>
<p>in this case, <code>cmd_str</code> sent to the client.py as a string itself and not like other one. Could anyone pls help me how to acheive this?</p>
|
<p>If I understand you right, you want to call a method of an object, but you don't know the method in advance, you just have it in a string. Is that correct?</p>
<pre><code>class Server(object):
def isRunning(self):
print("you are inside the isRunning")
my_server = Server()
cmd_str = "isRunning"
my_function = my_server.__getattribute__(cmd_str)
my_function()
</code></pre>
<blockquote>
<p>you are inside the isRunning</p>
</blockquote>
<p>Note that I let the <code>Server</code> class inherit from <code>object</code> to make it a so-called new-style class, and that <code>isRunning</code> gets an argument <code>self</code>, which tells python that this should be an instance method. <code>my_server.__getattribute__</code> will get a reference to the bound function <code>my_server.isRunning</code>, which you then call. </p>
<p>You could also do something like this:</p>
<pre><code>function_map = {
'check_if_running': my_server.isRunning
}
cmd_str = 'check_if_running'
my_function = function_map[cmd_str]
my_function()
</code></pre>
<p>so you don't have to name your functions exactly the way that your command strings are called (in python, the naming convention for methods is generally <code>like_this</code>, not <code>likeThis</code>)</p>
|
python|python-3.x
| 1 |
1,906,216 | 62,582,883 |
Cannot Install AutoItLibrary for Robot Framework on Windows 10
|
<p>I cannot install the autoitlibrary for robot framework on windows 10, when I try the commands below:</p>
<pre><code>pip install robotframework-autoitlibrary
</code></pre>
<p>OR</p>
<pre><code>pip install -U robotframework-autoitlibrary --no-cache-dir --pre
</code></pre>
<p>It begins the installation, but then it gives me the error:</p>
<pre><code>C:\WINDOWS\system32>pip install -U robotframework-autoitlibrary --no-cache-dir --pre
Collecting robotframework-autoitlibrary
Downloading robotframework-autoitlibrary-1.2.5.tar.gz (696 kB)
|████████████████████████████████| 696 kB 6.8 MB/s
Requirement already satisfied, skipping upgrade: pywin32 in c:\users\guilherme\appdata\roaming\python\python38\site-packages (from robotframework-autoitlibrary) (227)
Requirement already satisfied, skipping upgrade: pillow in c:\users\guilherme\appdata\local\programs\python\python38\lib\site-packages (from robotframework-autoitlibrary) (7.1.2)
</code></pre>
<p>Using legacy <code>setup.py</code> install for <code>robotframework-autoitlibrary</code>, since package <strong><code>wheel</code> is not installed</strong>.</p>
<pre><code>Installing collected packages: robotframework-autoitlibrary
Running setup.py install for robotframework-autoitlibrary ... error
ERROR: Command errored out with exit status 2:
command: 'c:\users\guilherme\appdata\local\programs\python\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Guilherme\\AppData\\Local\\Temp\\pip-install-cuz2ut7_\\robotframework-autoitlibrary\\setup.py'"'"'; __file__='"'"'C:\\Users\\Guilherme\\AppData\\Local\\Temp\\pip-install-cuz2ut7_\\robotframework-autoitlibrary\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Guilherme\AppData\Local\Temp\pip-record-p7h0dafs\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\guilherme\appdata\local\programs\python\python38\Include\robotframework-autoitlibrary'
cwd: C:\Users\Guilherme\AppData\Local\Temp\pip-install-cuz2ut7_\robotframework-autoitlibrary\
Complete output (3 lines):
Don't think we need to unregister the old one...
%SYSTEMROOT%\system32\regsvr32.exe /S c:\users\guilherme\appdata\local\programs\python\python38\Lib\site-packages\AutoItLibrary\lib\AutoItX3.dll
AutoItLibrary requires win32com. See http://starship.python.net/crew/mhammond/win32/.
**----------------------------------------**
ERROR: Command errored out with exit status 2: 'c:\users\guilherme\appdata\local\programs\python\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Guilherme\\AppData\\Local\\Temp\\pip-install-cuz2ut7_\\robotframework-autoitlibrary\\setup.py'"'"'; __file__='"'"'C:\\Users\\Guilherme\\AppData\\Local\\Temp\\pip-install-cuz2ut7_\\robotframework-autoitlibrary\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Guilherme\AppData\Local\Temp\pip-record-p7h0dafs\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\guilherme\appdata\local\programs\python\python38\Include\robotframework-autoitlibrary' Check the logs for full command output.
</code></pre>
<p>Details:</p>
<ul>
<li>I've already tried running the prompt as Admin as you can see above, but didn't work too.</li>
<li>My python is the last version: <code>Python 3.8.3 (64bit)</code></li>
<li>I've already have installed robot framework: <code>Robot Framework 3.2.1 (Python 3.8.3 on win32)</code></li>
</ul>
<p>Can someone help me fix this?!</p>
|
<p>Worked for me when I opened the command window as administrator.</p>
|
python|windows-10|robotframework
| 1 |
1,906,217 | 71,440,950 |
Why does my Python distribution install each package in its own directory in site-packages?
|
<p>I created a distribution package called <code>myapi-1.0.0.tar.gz</code> that has two python packages inside it (api and helpers). When I <code>pip install</code> it in my virtual environment, it <code>api</code> and <code>helpers</code> python packages are installed into their own folder in the root site-packages, instead of all being installed in a <code>myapi</code> folder.</p>
<p>This is the file structure of my project:</p>
<pre><code>myapi/
├── api
│ ├── api.py
│ └── __init__.py
├── dist
│ ├── myapi-1.0.0-py3-none-any.whl
│ └── myapi-1.0.0.tar.gz
├── helpers
│ ├── helper_1.py
│ └── __init__.py
├── __init__.py
├── pyproject.toml
├── setup.cfg
└── setup.py
</code></pre>
<p>After running <code>pip install myapi-1.0.0.0.tar.gz</code>, <code>pip list</code> shows that myapi version 1.0.0 is installed.</p>
<p>However in <code>.venv/lib/python3.8/site-packages</code>, these folders are created:</p>
<pre><code>myapi/.venv/lib/python3.8/site-packages/api/*
myapi/.venv/lib/python3.8/site-packages/helpers/*
myapi/.venv/lib/python3.8/site-packages/myapi-1.0.0.dist-info/
</code></pre>
<p>For every package and sub package I have in my project, when installed as a distribution package with pip, they are installed into the root of <code>site-packages</code>.</p>
<p>How do I get my distribution package to install all the packages and files as they exist in my project under the folder 'myapi' in <code>site-packages</code>?</p>
<p>note that all __init__.py files and helper_1.py/api.py are empty.</p>
<p>setup.cfg:</p>
<pre><code>[metadata]
name = myapi
version = 1.0.0
[options]
packages = find:
</code></pre>
<p>setup.py</p>
<pre><code>import setuptools
setuptools.setup()
</code></pre>
<p>pyproject.toml</p>
<pre><code>[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
</code></pre>
<p>I have setup.py present in the project to allow me to create an editable installation, and pyproject.toml there to satisfy PEP standards, while most of the other configuration I try to put into setup.cfg</p>
|
<p>Change your file structure to the following.</p>
<pre><code>myapi/
├── myapi/
│ ├── api
│ │ ├── api.py
│ │ └── __init__.py
│ ├── helpers
│ │ ├── helper_1.py
│ │ └── __init__.py
│ └── __init__.py
├── pyproject.toml
├── setup.cfg
└── setup.py
</code></pre>
|
python|pip|packaging|pypi
| 0 |
1,906,218 | 70,544,786 |
how to write this romove_stopwords faster python?
|
<p>I have a function <code>remove_stopwords</code> like this. How do I make it run faster?</p>
<pre><code>temp.reverse()
def drop_stopwords(text):
for x in temp:
elif len(x.split()) > 1:
text_list = text.split()
for y in range(len(text_list)-len(x.split())):
if " ".join(text_list[y:y+len(x.split())]) == x:
del text_list[y:y+len(x.split())]
text = " ".join(text_list)
else:
text = " ".join(text for text in text.split() if text not in vietnamese)
return text
</code></pre>
<p>time to solve a text in my data is 14s and if I have some trick like this time for will decrease to 3s:</p>
<pre><code>
temp.reverse()
def drop_stopwords(text):
for x in temp:
if len(x.split()) >2:
if x in text:
text = text.replace(x,'')
elif len(x.split()) > 1:
text_list = text.split()
for y in range(len(text_list)-len(x.split())):
if " ".join(text_list[y:y+len(x.split())]) == x:
del text_list[y:y+len(x.split())]
text = " ".join(text_list)
else:
text = " ".join(text for text in text.split() if text not in vietnamese)
return text
</code></pre>
<p>but I think it may get wrong some where in my language. How can I rewrite this function in Python to make it faster (in C and C++ I can solve it easily with the function above :(( )</p>
|
<p>Your function does a lot of the same thing over and over, particularly repeated <code>split</code> and <code>join</code> of the same <code>text</code>. Doing a single <code>split</code>, operating on the list, and then doing a single <code>join</code> at the end might be faster, and would definitely lead to simpler code. Unfortunately I don't have any of your sample data to test the performance with, but hopefully this gives you something to experiment with:</p>
<pre><code>temp = ["foo", "baz ola"]
def drop_stopwords(text):
text_list = text.split()
text_len = len(text_list)
for word in temp:
word_list = word.split()
word_len = len(word_list)
for i in range(text_len + 1 - word_len):
if text_list[i:i+word_len] == word_list:
text_list[i:i+word_len] = [None] * word_len
return ' '.join(t for t in text_list if t)
print(drop_stopwords("the quick brown foo jumped over the baz ola dog"))
# the quick brown jumped over the dog
</code></pre>
<p>You could also just try iteratively doing <code>text.replace</code> in all cases and seeing how that performs compared to your more complex <code>split</code>-based solution:</p>
<pre><code>temp = ["foo", "baz ola"]
def drop_stopwords(text):
for word in temp:
text = text.replace(word, '')
return ' '.join(text.split())
print(drop_stopwords("the quick brown foo jumped over the baz ola dog"))
# the quick brown jumped over the dog
</code></pre>
|
python|pandas|stop-words
| 1 |
1,906,219 | 63,445,211 |
Is it possible to open chrome inspect element with selenium in python?
|
<p>I need to open the inspect element in a chrome browser for a project I'm working on and I can't figure out if it's no possible or what. If I try and just use F12 like so:</p>
<pre><code>action = ActionChains(driver)
action.send_keys(Keys.F12)
action.perform()
</code></pre>
<p>Then nothing happens at all. Same results if I try using the full shortcut (Control+Shift+i):</p>
<pre><code>action = ActionChains(driver)
action.key_down(Keys.CONTROL)
action.key_down(Keys.SHIFT)
action.send_keys('i')
action.perform()
action.key_up(Keys.SHIFT)
action.key_up(Keys.CONTROL)
action.perform()
</code></pre>
<p>If I use a different shortcut, such as Control+a to highlight everything on a given page, it works. I've thought about the possibility of somehow right-clicking and then having it click on the inspect button, but I'm unsure how feasible that is. If anyone has any tips at all I'd really appreciate it.</p>
<p>I don't know if I'm just doing something entirely wrong or if maybe it just isn't possible but either way I'd like to get some closure at the least.</p>
|
<p>I think you can read <a href="https://chromedriver.chromium.org/capabilities" rel="nofollow noreferrer" title="You can go chromedriver website">Chrome options</a>! and I think you can use this options like that:</p>
<pre><code>chromeOptions = ChromeOptions();
chromeOptions.addArguments("--start-maximized");
driver = ChromeDriver(chromeOptions);
</code></pre>
|
python|python-3.x|selenium|selenium-webdriver|selenium-chromedriver
| 0 |
1,906,220 | 55,901,649 |
SELECT command wont find column name with a colon
|
<p>I have a python script to retrieve a value (table ID) from a PostgreSQL database. The column name contains a colon though and I believe this is stopping it working. I've tested this on columns without colons and it does get the ID correctly.</p>
<p>The line in question is</p>
<pre><code>cur.execute("SELECT tID from titles where name like 'METEOROLOG:WINDSPEED_F' order by structure, comp1, comp2")
rowswind=cur.fetchall()
</code></pre>
<p>When I print rowswind nothing is returned (just empty brackets)</p>
<p>I have also tried..</p>
<pre><code>cur.execute('SELECT tID from titles where name like "METEOROLOGY:WINDSPEED_F" order by structure, comp1, comp2')
</code></pre>
<p>But that comes back with the error </p>
<blockquote>
<p>psycopg2.ProgrammingError: column "METEOROLOGY:WINDSPEED_F" does not
exist</p>
</blockquote>
<p>(it definitely does).</p>
<p>I've also tried escaping the colon any way I can think of (i.e. back slash) but nothing works, I just get syntax errors. </p>
<p>Any advice would be welcome. Thanks.</p>
<p>ADDITION 20190429</p>
<p>I've now tried parameterizing the query but also with no success.</p>
<pre><code>wind=('METEOROLOGY:WINDSPEED_F')
sql="SELECT tID from titles where name like '{0}' order by structure, comp1, comp2".format(wind)
</code></pre>
<p>I've tried many different combinations of double and single quotes to try and escape the colon with no success.</p>
|
<blockquote>
<p>psycopg2.ProgrammingError: column "METEOROLOGY:WINDSPEED_F" does not exist</p>
</blockquote>
<p>You're getting this error because you're using double quotes around the targeted value in your query's <code>WHERE</code> statement, here:</p>
<pre><code>cur.execute('SELECT tID from titles where name like "METEOROLOGY:WINDSPEED_F" order by structure, comp1, comp2')
</code></pre>
<p>You're getting 0 results back here:</p>
<pre><code>cur.execute("SELECT tID from titles where name like 'METEOROLOG:WINDSPEED_F' order by structure, comp1, comp2")
</code></pre>
<p>because 0 rows exist with the value "METEOROLOG:WINDSPEED_F" in the <code>name</code> column. <strong>This might just be because you're spelling METEOROLOGY wrong.</strong></p>
<p>The way you're using <code>LIKE</code>, you might as well be using <code>=</code>. <code>LIKE</code> is great if you're going to use <code>%</code> to find other values <em>like</em> that value.</p>
<p>Example:</p>
<pre><code>SELECT *
FROM
TABLE
WHERE
UPPER(NAME) LIKE 'JOSH%'
</code></pre>
<p>This would return results for these values in <code>name</code>: JOSHUA, JoShUa, joshua, josh, JOSH. If I straight up did <code>NAME LIKE 'JOSH'</code> then I would only find results for the exact value of <code>JOSH</code>.</p>
<p>Since you are making the value all caps in your <code>WHERE</code>, try this adding an <code>UPPER()</code> to your query like this:</p>
<pre><code>cur.execute("SELECT tID from titles where UPPER(name) like 'METEOROLOG:WINDSPEED_F' order by structure, comp1, comp2")
</code></pre>
|
python|postgresql|psycopg2
| 0 |
1,906,221 | 56,490,222 |
Unable to resolve the 'UnboundLocalError' in python3.7
|
<p>I am calculating two ratios: ratio1 and ratio2. They are calculated by using the key of a dictionary. If they do not find the key, they simply print it without an error.</p>
<pre><code> try:
#RATIO FOR THE LEFT LEG
ratio1 = distance(dict[x],dict[y])
print(ratio1)
except KeyError:
print('Left Ratio Not Available')
try:
#RATIO FOR THE RIGHT LEG
ratio2 = distance(dict[p],dict[q])
print(ratio2)
except KeyError:
print('Right Ratio Not Available')
</code></pre>
<p>Till here my code works fine. But as I proceed to find the Max out of both the ratios, </p>
<pre><code> try:
print('max ratio is : ', max(ratio1,ratio2))
except KeyError:
try:
print(ratio1)
except KeyError:
try:
print(ratio2)
finally:
print('No Ratio Available.')
</code></pre>
<p>I get 'UnboundLocalError'.</p>
<pre><code> UnboundLocalError: local variable 'ratio1' referenced before assignment
</code></pre>
<p>I even used 'global'. But either way, I am getting the same error.
Please tell me how to handle this appropriately.</p>
|
<p>I think that your code works fine. The problem is that you catch a keyerror in the first try-except statement and move on to the next two try's. If the first one catches a KeyError and then you try to read from the variable called ratio1 then you get this kind of error because you didn't initiate the variable.</p>
<p>your code should look something like this:</p>
<pre><code>try:
# RATIO FOR THE LEFT LEG
ratio1 = distance(dict[x],dict[y])
print(ratio1)
except KeyError:
ratio1 = 0
print('Left Ratio Not Available')
try:
# RATIO FOR THE RIGHT LEG
ratio2 = distance(dict[p],dict[q])
print(ratio2)
except KeyError:
ratio2 = 0
print('Right Ratio Not Available')
print('max ratio is : ', max(ratio1,ratio2))
</code></pre>
|
python-3.x
| 2 |
1,906,222 | 56,795,473 |
iterating through length of a list
|
<p>given a list of nums, return True if the array contains a 3 next to a 3
...how do i solve this?
i tried using the range function but that doesnt seem to work..
for example, </p>
<pre><code>def myfunc(mylist):
for i in range(0, len(mylist) - 1):
return mylist[1] == 3 and mylist[i + 1] == 3
myfunc([4, 3, 3])
returns false
</code></pre>
<p>I'm a little confused actually
how to iterate through index count</p>
<pre><code>def myfunc(mylist):
for i in range(0, len(mylist) - 1):
return mylist[1] == 3 and mylist[i + 1] == 3
myfunc([4, 3, 3])
returns false
expected result = True
actual output = False
</code></pre>
|
<p>Using <code>zip</code> you can compare the list with itself:</p>
<pre><code>>>> l_true=[1,2,3,4,5,3,3,5,6,7,5,4]
>>> any( x==y==3 for x,y in zip( l_true, l_true[1:] ) )
True
>>> l_false=[1,2,3,4,5,3,1,5,6,7,5,4]
>>> any( x==y==3 for x,y in zip( l_false, l_false[1:] ) )
False
</code></pre>
<p><strong>Explanation:</strong></p>
<p><code>zip</code> takes one element at a time of each list, you can compare the list with itself switching one position one of the instances:</p>
<pre><code>[1,2,3,4,5,3,3,5,6,7,5,4]
[2,3,4,5,3,3,5,6,7,5,4] #<- switched list
^
|
- here !
</code></pre>
<p>Maybe it exists a more readable approach, but, <code>zip</code> and <code>any</code> are Python functions.</p>
|
python
| 2 |
1,906,223 | 69,711,829 |
Timer that prints elapsed time and resets with a button click
|
<p>I have a GUI where the user can click a button named "next set" that allows them to move onto the next task. I wanted to add a timer that starts as soon as they start the application and run the timer until they press the button "next set". When clicked, I want the time elapsed to print and the timer to restart until they press "next set" button again. I would like the timer to start automatically when the code runs. Currently, the "next set" button has two actions, one is to retrieve the next set of images and the other action I am trying to include is to reset the timer and print time elapsed. I also only included part of the code that felt relevant because it is long.</p>
<pre><code>import time
import tkinter as tk
import csv
from pathlib import Path
import PIL.Image
import PIL.ImageDraw
import PIL.ImageTk
MAX_HEIGHT = 500
IMAGES_PATH = Path("Images")
CSV_LABELS_KEY = "New Labels"
CSV_FILE_NAME_KEY = "FolderNum_SeriesNum"
CSV_BOUNDING_BOX_KEY = "correct_flip_bbox"
counter = 0
timer_id = None
class App(tk.Frame):
def __init__(self, master=None):
super().__init__(master) # python3 style
self.config_paths = ["config 1.yaml", "config 2.yaml", "config 3.yaml"]
self.config_index = 0
self.clickStatus = tk.StringVar()
self.loadedImages = dict()
self.loadedBoxes = dict() # this dictionary will keep track of all the boxes drawn on the images
self.master.title('Slideshow')
frame = tk.Frame(self)
tk.Button(frame, text=" Next set ", command=lambda:[self.get_next_image_set(), self.reset()]).pack(side=tk.RIGHT)
tk.Button(frame, text=" Exit ", command=self.destroy).pack(side=tk.RIGHT)
frame.pack(side=tk.TOP, fill=tk.BOTH)
self.canvas = tk.Canvas(self)
self.canvas.pack()
self._load_dataset()
self.reset()
self.start_timer = None
t = time()
t.start()
def start_timer(self, evt=None):
if self._start_timer is not None:
self._start_timer = time.perf_counter()
# global counter
# counter += 1
# label.config(text=str(counter))
# label.after(1000, count)
def reset(self):
if self._start_timer is None:
elapsed_time = time.perf_counter() - self._start_timer
self._start_timer = None
print('Time elapsed (hh:mm:ss.ms) {}'.format(elapsed_time))
def _load_dataset(self):
try:
config_path = self.config_paths[self.config_index]
self.config_index += 1
except IndexError:
return
image_data = loadData(config_path)
# drawing the image on the label
self.image_data = image_data
self.currentIndex = 0
# start from 0th image
self._load_image()
def _load_image(self):
imgName = self.image_data[self.currentIndex]['image_file']
if imgName not in self.loadedImages:
self.im = PIL.Image.open(self.image_data[self.currentIndex]['image_file'])
ratio = MAX_HEIGHT / self.im.height
# ratio divided by existing height -> to get constant amount
height, width = int(self.im.height * ratio), int(self.im.width * ratio)
# calculate the new h and w and then resize next
self.canvas.config(width=width, height=height)
self.im = self.im.resize((width, height))
if self.im.mode == "1":
self.img = PIL.ImageTk.BitmapImage(self.im, foreground="white")
else:
self.img = PIL.ImageTk.PhotoImage(self.im)
imgData = self.loadedImages.setdefault(self.image_data[self.currentIndex]['image_file'], dict())
imgData['image'] = self.img
imgData['shapes'] = self.image_data[self.currentIndex]['shapes']
# for next and previous so it loads the same image adn don't do calculations again
self.img = self.loadedImages[self.image_data[self.currentIndex]['image_file']]['image']
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.img)
self.show_drag_box()
def loadData(fname):
with open(fname, mode='r') as f:
return yaml.load(f.read(), Loader=yaml.SafeLoader)
if __name__ == "__main__":
data = loadData('config 1.yaml')
app = App(data)
app.pack() # goes here
app.mainloop()
</code></pre>
|
<p>I have used datetime instead of time, as subtracting two datetime objects will give an output with hours and minutes included, whereas subtracting two time objects only gives seconds. However, both will work, you may just need to do more reformatting using time.</p>
<p>Read the current time when the application starts and store it. Each time you press the button, subtract your stored time from the current time which gives you your time elapsed. Then simply store your new current time until the next button press. The code below demonstrates this.</p>
<pre><code>import tkinter as tk
import datetime as dt
class TimeButton(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
# Start timer
self.current_time = dt.datetime.today()
# Button
self.next_set = tk.Button(self, text='Next Set', command = self.clicked)
self.next_set.pack()
def clicked(self):
now = dt.datetime.today()
time_elapsed = now - self.current_time
print(time_elapsed)
self.current_time = now
if __name__ == "__main__":
window = tk.Tk()
button = TimeButton(window)
button.pack()
window.mainloop()
</code></pre>
|
python|user-interface|tkinter|timer
| 0 |
1,906,224 | 69,745,501 |
Attempting to build a loop to change one str out of 3 strs in python
|
<p>My goal is to create 3 lists.</p>
<p>The 1st one is the input: choose 3 from ABCD to create AAA, ABC...etc<br />
The 2nd one is the output: change the middle letter of each input and create a new list. eg: for AAA -> ABA,ACA,ADA. So 3 times the length of the input. <br />
The third one is the Change: I want to name each change as c_i, for example, AAA->ABA is C1.</p>
<p>For Input,</p>
<pre><code>>>> lis = ["A","B","C","D"]
>>> import itertools as it
>>> inp = list(it.product(lis, repeat = 3))
>>> print(inp)
[('A', 'A', 'A'), ('A', 'A', 'B'), ... ('D', 'D', 'C'), ('D', 'D', 'D')]
>>> len(inp)
64
</code></pre>
<p>But I am stuck on how to create the output list. Any idea is appreciated!</p>
<p>Thanks</p>
|
<p>You can use list comprehension:</p>
<pre class="lang-py prettyprint-override"><code>import itertools
lst = ['A', 'B', 'C', 'D']
lst_input = list(itertools.product(lst, repeat=3))
lst_output = [(tup[0], x, tup[2]) for tup in lst_input for x in lst if tup[1] is not x]
lst_change = [f'C{i}' for i in range(1, len(lst_output) + 1)]
print(len(lst_input), len(lst_output), len(lst_change))
print(lst_input[:5])
print(lst_output[:5])
print(lst_change[:5])
# 64 192 192
# [('A', 'A', 'A'), ('A', 'A', 'B'), ('A', 'A', 'C'), ('A', 'A', 'D'), ('A', 'B', 'A')]
# [('A', 'B', 'A'), ('A', 'C', 'A'), ('A', 'D', 'A'), ('A', 'B', 'B'), ('A', 'C', 'B')]
# ['C1', 'C2', 'C3', 'C4', 'C5']
</code></pre>
<p>For each tuple in <code>lst_input</code>, the middle item is replaced by all the candidate characters, but the replacement is thrown out if that replacement character is the same as the original character (<code>if tup[1] is not x</code>).</p>
|
python
| 1 |
1,906,225 | 18,098,636 |
SOAP Solution in python
|
<p>i'm rather new to SOAP and web services and i tried to create working and stable SOAP environment. After some reading i decided to use suds client and soaplib server.
I'm using python2.7 and i've installed suds and soaplib by using easy_install so it's rather default combination of programs. Operating system is newest Ubuntu 13.</p>
<p>I've created 2 scripts that are based on tutorial hello_world example :
<a href="http://soaplib.github.io/soaplib/2_0/pages/helloworld.html" rel="nofollow">http://soaplib.github.io/soaplib/2_0/pages/helloworld.html</a></p>
<p>After some minor changes:</p>
<ul>
<li>adding <code>from soaplib.core.service import soap</code> in server </li>
<li>adding name of service in <code>hello_client = Client('http://localhost:7789/HelloWorldService?wsdl')</code> in client</li>
</ul>
<p>I got a working solution that allows me to run server (port is busy) and suds client gives me a returning info after use of say_hello function.</p>
<p>Problem is that i can't create new methods in this server using definition used in example. Even simple changing name from say_hello to say_hello2 gives me error :
suds.MethodNotFound: Method not found: 'Application.Application.say_hello2'</p>
<p>Please help me to solve this issue :)</p>
<p>I was thinking about other thing too. sopalib seems inactive since 2010 and maybe here lies some problem? Maybe there are better, faster and more efficient solutions to SOAP connections than SUDS+soaplib? If so please advice me something.</p>
<p>Thanks for help
Mike</p>
|
<p>Seems like problem is due to suds , cache</p>
<pre><code>from suds.client import Client
hello_client = Client('http://localhost:7789/HelloWorldService?wsdl')
hello_client.options.cache.clear() #make this line
result = hello_client.service.say_hello2(...) # parameters inside
</code></pre>
|
python|soap|suds|soaplib
| 1 |
1,906,226 | 60,839,907 |
How to search for products by UPC using python bindings for Ebay's findItemsByProduct API?
|
<p>I'm trying to find products by UPC using <a href="https://developer.ebay.com/DevZone/finding/CallRef/findItemsByProduct.html" rel="nofollow noreferrer">EBay's Product Find Items by Product ID</a>, specifically using the <a href="https://github.com/timotheus/ebaysdk-python" rel="nofollow noreferrer">Python bindings</a>.</p>
<p>I'm trying:</p>
<pre class="lang-py prettyprint-override"><code> api = Connection(
appid='my id', config_file=None)
response = api.execute('findItemsByProduct', {
'productId': 820103794923,
'itemFilter': [
{'name': 'MinQuantity', 'value': 1},
</code></pre>
<p>But I get:</p>
<pre><code>{'ack': 'Failure', 'errorMessage': {'error': {'errorId': '4', 'domain': 'Marketplace', 'severity': 'Error', 'category': 'Request', 'message': 'Product ID is required.', 'subdomain': 'Search'}}, 'version': '1.13.0', 'timestamp': datetime.datetime(2020, 3, 24, 21, 46, 52)}
</code></pre>
<p>Whats the correct argument?</p>
|
<pre><code>api = Connection(config_file=yaml_path)
response = api.execute('findItemsByProduct',
'<productId type="ReferenceID">820103794923</productId><itemFilter><name>MinQuantity</name><value>1</value></itemFilter>')
response.reply
</code></pre>
<p>{'ack': 'Success', 'version': '1.13.0', 'timestamp': datetime.datetime(2020, 3, 26, 10, 13, 10), 'searchResult': {'_count': '0'}, 'paginationOutput': {'pageNumber': '0', 'entriesPerPage': '100', 'totalPages': '0', 'totalEntries': '0'}, 'itemSearchURL': '<a href="https://www.ebay.com/sch/?_samilow=1&_LH_MIL=1&_ddo=1&_ipg=100&_pgn=1&_productid=820103794923" rel="nofollow noreferrer">https://www.ebay.com/sch/?_samilow=1&_LH_MIL=1&_ddo=1&_ipg=100&_pgn=1&_productid=820103794923</a>'}</p>
|
python|ebay-api|ebay-sdk
| 0 |
1,906,227 | 60,807,875 |
Execution time surpassed while traversing through a list of values
|
<p>I'm working through a challenge to see if a given sequence is strictly increasing if one and only one element is removed from it. The output should be a <strong>True</strong> or <strong>False</strong>. This is my code:</p>
<pre><code>def almostIncreasingSequence(sequence):
for i in range(len(sequence)):
element = sequence[i]
del sequence[i]
if all(i < j for i, j in zip(sequence, sequence[1:])):
return True
sequence.insert(i, element)
return False
</code></pre>
<p>It works most of the times but there are 2 problems with this code:</p>
<ol>
<li><p>The output is <strong>undefined</strong> when these are the inputs: <code>[30, 60, 50, 80, 100, 200, 150]</code>, <code>[1000, 1000, 2000, 3000, 4000, 5000, 5000]</code></p></li>
<li><p>The execution time is surpassed when this is the input: <code>[-9996, -9995, -9994, -9993, -9991, -9989, -9987, -9986, -9985, -9983, -9982, -9980, -9978, -9977, -9976, -9975, -9974, -9972, -9968, -9966, -9965, -9961, -9957, -9956, -9955, -9954, -9952, -9948, -9942, -9939, -9938, -9936, -9935, -9932, -9931, -9927, -9925, -9923, -9922, -9921, -9920, -9919, -9918, -9908, -9905, -9902, -9901, -9900, -9899, -9897, -9896, -9894, -9888, -9886, -9880, -9878, -9877, -9876, -9874, -9872, -9871, -9870, -9869, -9868, -9867, -9865, -9857, -9856, -9855, -9854, -9853, -9852, -9851, -9849, -9848, -9846, -9845, -9843, -9842, -9841, -9840, -9837, -9834, -9828, -9826, -9824, -9823, -9820, -9816, -9814, -9812, -9811, -9810, -9809, -9807, -9806, -9804, -9803, -9801, -9800]</code></p></li>
</ol>
<p>My guess is that the fact that my code being resource-intensive isn't the only thing wrong with it, as the inputs in #1 were quite small. However, I don't know what it could be. </p>
|
<pre><code>def strictly_increasing_but_one(sequence):
sequence = np.array(sequence)
# The differences should always be positive
# if we have a strictly increasing sequence
differences = np.diff(sequence)
if (differences <= 0).sum() > 1:
# We found more than one element which is smaller
# than the previous element
return False
# However, it could be that there were elements which were
# greater than their predecessors but still lower than their
# pre-predecessors (check test4 for an example). Hence, we need to
# remove the previously found smaller elements and check again:
keep = np.insert(differences > 0, 0, True)
differences = np.diff(sequence[keep])
return (differences <= 0).sum() == 0
test1 = [30, 60, 50, 80, 100, 200, 150]
test2 = [1000, 1000, 2000, 3000, 4000, 5000, 5000]
test3 = [-9996, -9995, -9994, -9993, -9991, -9989, -9987, -9986, -9985, -9983, -9982, -9980, -9978, -9977, -9976, -9975, -9974, -9972, -9968, -9966, -9965, -9961, -9957, -9956, -9955, -9954, -9952, -9948, -9942, -9939, -9938, -9936, -9935, -9932, -9931, -9927, -9925, -9923, -9922, -9921, -9920, -9919, -9918, -9908, -9905, -9902, -9901, -9900, -9899, -9897, -9896, -9894, -9888, -9886, -9880, -9878, -9877, -9876, -9874, -9872, -9871, -9870, -9869, -9868, -9867, -9865, -9857, -9856, -9855, -9854, -9853, -9852, -9851, -9849, -9848, -9846, -9845, -9843, -9842, -9841, -9840, -9837, -9834, -9828, -9826, -9824, -9823, -9820, -9816, -9814, -9812, -9811, -9810, -9809, -9807, -9806, -9804, -9803, -9801, -9800]
test4 = [1000, 2000, 1500, 1800, 5000]
strictly_increasing_but_one(test1) # False
strictly_increasing_but_one(test2) # False
strictly_increasing_but_one(test3) # True
strictly_increasing_but_one(test4) # False
</code></pre>
<p><strong>Explaination</strong>: Imagine you have a strictly increasing sequence of numbers, then the difference between each element and the previous element should always be positive:</p>
<pre><code>for all x[i]: x[i] > x[i-1]
</code></pre>
<p>All elements which are lower than their previous element, would cause negative differences. We can calculate the differences with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html" rel="nofollow noreferrer"><code>numpy.diff</code></a> and then check how many of them are negative. If we find more than one, we know that there are at least two elements which we would need to remove to make the sequence strictly increasing (this is covered by the if-statement).</p>
<p>However, there could still be elements that are greater than their immediate predecessors but lower than the elements before (see <code>test4</code>). Hence, we remove the <em>disturbers</em> from before and check again whether we find any negative differences. If we don't, we can be sure that the sequence is now strictly increasing.</p>
|
python|execution-time
| 1 |
1,906,228 | 66,308,540 |
got retcode=10021 in python with MT5
|
<p>I'm trying to create a trading bot that makes orders instead of making them manually from the MetaTrader5 App, I make the function below</p>
<p>Note: BoS: Buy or Sell | sl: Stop Loss | tp: Take Profit | lot: Volume</p>
<pre><code>def MetaTrader_Order(symbol, BoS, price, sl, tp, lot):
# connect to MetaTrader 5
if not mt5.initialize():
print("initialize() failed")
mt5.shutdown()
# prepare the buy request structure
symbol_info = mt5.symbol_info(symbol)
if symbol_info is None:
print(symbol, " not found, can not call order_check()")
# if the symbol is unavailable in MarketWatch, add it
if not symbol_info.visible:
print(symbol, " is not visible, trying to switch on")
if not mt5.symbol_select(symbol,True):
print("symbol_select({}) failed, exit",symbol)
deviation = 20
if BoS == "SELL":
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": lot,
"type": mt5.ORDER_TYPE_SELL,
"price": price,
"sl": sl,
"tp": tp,
"deviation": deviation,
"magic": 234000,
"comment": "python script open",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_RETURN,
}
elif BoS == "BUY":
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": lot,
"type": mt5.ORDER_TYPE_BUY,
"price": price,
"sl": sl,
"tp": tp,
"deviation": deviation,
"magic": 234000,
"comment": "python script open",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_RETURN,
}
else:
request = None
# send a trading request
result = mt5.order_send(request)
# check the execution result
print("1. order_send(): {} {} at price {}, with lot {}, with deviation {}".format(BoS, symbol, price, lot, deviation))
if result.retcode != mt5.TRADE_RETCODE_DONE:
print("2. order_send failed, retcode={}".format(result.retcode))
# request the result as a dictionary and display it element by element
result_dict=result._asdict()
for field in result_dict.keys():
print(" {}={}".format(field,result_dict[field]))
# if this is a trading request structure, display it element by element as well
if field=="request":
traderequest_dict=result_dict[field]._asdict()
for tradereq_filed in traderequest_dict:
print(" traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed]))
else:
print("2. order_send done, ", result)
</code></pre>
<p>when I try to pass arguments to function like that:</p>
<p><code>MetaTrader_Order("GBPUSD", "SELL", 1.40001, 1.5, 1.3, 0.1)</code></p>
<p>it gives me an output like this:</p>
<pre><code>1. order_send(): SELL GBPUSD at price 1.40001, with lot 0.01, with deviation 20
2. order_send failed, retcode=10021
retcode=10021
deal=0
order=0
volume=0.0
price=0.0
bid=0.0
ask=0.0
comment=No prices
request_id=0
retcode_external=0
request=TradeRequest(action=1, magic=234000, order=0, symbol='GBPUSD', volume=0.01, price=1.40001, stoplimit=0.0, sl=1.5, tp=1.3, deviation=20, type=1, type_filling=2, type_time=0, expiration=0, comment='python script open', position=0, position_by=0)
traderequest: action=1
traderequest: magic=234000
traderequest: order=0
traderequest: symbol=GBPUSD
traderequest: volume=0.01
traderequest: price=1.40001
traderequest: stoplimit=0.0
traderequest: sl=1.5
traderequest: tp=1.3
traderequest: deviation=20
traderequest: type=1
traderequest: type_filling=2
traderequest: type_time=0
traderequest: expiration=0
traderequest: comment=python script open
traderequest: position=0
traderequest: position_by=0
</code></pre>
<p>if I try to put price automatically like this: <code>price = mt5.symbol_info_tick(symbol).ask</code>
it works and sends the order to MetaTrader5 with no problems</p>
<p>but really I wont to send order with a specific price that I entered, not the market price</p>
<p>.<br />
.<br />
.<br />
MT5 Documentation: <a href="https://www.mql5.com/en/docs/integration/python_metatrader5" rel="nofollow noreferrer">https://www.mql5.com/en/docs/integration/python_metatrader5</a>
MT5<br />
order_send: <a href="https://www.mql5.com/en/docs/integration/python_metatrader5/mt5ordersend_py" rel="nofollow noreferrer">https://www.mql5.com/en/docs/integration/python_metatrader5/mt5ordersend_py</a><br />
MT5 Return Codes: <a href="https://www.mql5.com/en/docs/constants/errorswarnings/enum_trade_return_codes" rel="nofollow noreferrer">https://www.mql5.com/en/docs/constants/errorswarnings/enum_trade_return_codes</a></p>
<p>also see <code>TRADE_ACTION_PENDING</code> on this page: <a href="https://www.mql5.com/en/docs/constants/structures/mqltraderequest" rel="nofollow noreferrer">https://www.mql5.com/en/docs/constants/structures/mqltraderequest</a> (it's in another language)</p>
|
<p>I solved the problem by writing this part of the code like that:</p>
<pre><code>if BoS == "SELL":
if price < mt5.symbol_info_tick(symbol).bid:
price = mt5.symbol_info_tick(symbol).bid
request = {
"action": mt5.TRADE_ACTION_PENDING,
"symbol": symbol,
"volume": lot,
"type": mt5.ORDER_TYPE_SELL_LIMIT,
"price": price,
"sl": sl,
"tp": tp,
"deviation": deviation,
"magic": 234000,
"comment": "python script open",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_RETURN,
}
elif BoS == "BUY":
if price > mt5.symbol_info_tick(symbol).ask:
price = mt5.symbol_info_tick(symbol).ask
request = {
"action": mt5.TRADE_ACTION_PENDING,
"symbol": symbol,
"volume": lot,
"type": mt5.ORDER_TYPE_BUY_LIMIT,
"price": price,
"sl": sl,
"tp": tp,
"deviation": deviation,
"magic": 234000,
"comment": "python script open", ## may delete some items
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_RETURN,
}
</code></pre>
<p>Notice: <code>"action": mt5.TRADE_ACTION_PENDING,</code><br />
And: <code>"type": mt5.ORDER_TYPE_SELL_LIMIT,</code></p>
|
python|algorithmic-trading|trading|forex|metatrader5
| 2 |
1,906,229 | 72,794,777 |
Received incompatible tensor at flattened index 4 from table 'uniform_table'
|
<p>I'm trying to adapt the TensorFlow Agents tutorial to a custom environment. It's not very complicated and meant to teach me how this works. The game is basically a 21x21 grid with tokens the agent can collect for a reward by walking around. I can validate the environment, the agent, and the replay buffer, but when I try to train the model, i get an error message (see bottom). Any advice would be welcome !</p>
<p>The agent class is:</p>
<pre><code>import numpy as np
import random
from IPython.display import clear_output
import time
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import tensorflow as tf
import numpy as np
from tf_agents.environments import py_environment
from tf_agents.environments import tf_environment
from tf_agents.environments import tf_py_environment
from tf_agents.environments import utils
from tf_agents.specs import array_spec
from tf_agents.environments import wrappers
from tf_agents.environments import suite_gym
from tf_agents.trajectories import time_step as ts
class cGame (py_environment.PyEnvironment):
def __init__(self):
self.xdim = 21
self.ydim = 21
self.mmap = np.array([[0]*self.xdim]*self.ydim)
self._turnNumber = 0
self.playerPos = {"x":1, "y":1}
self.totalScore = 0
self.reward = 0.0
self.input = 0
self.addRewardEveryNTurns = 4
self.addBombEveryNTurns = 3
self._episode_ended = False
## player = 13
## bomb = 14
self._action_spec = array_spec.BoundedArraySpec(shape=(), dtype=np.int32, minimum=0, maximum=3, name='action')
self._observation_spec = array_spec.BoundedArraySpec(shape = (441,), minimum=np.array([-1]*441), maximum = np.array([20]*441), dtype=np.int32, name='observation') #(self.xdim, self.ydim) , self.mmap.shape, minimum = -1, maximum = 10
def action_spec(self):
return self._action_spec
def observation_spec(self):
return self._observation_spec
def addMapReward(self):
dx = random.randint(1, self.xdim-2)
dy = random.randint(1, self.ydim-2)
if dx != self.playerPos["x"] and dy != self.playerPos["y"]:
self.mmap[dy][dx] = random.randint(1, 9)
return True
def addBombToMap(self):
dx = random.randint(1, self.xdim-2)
dy = random.randint(1, self.ydim-2)
if dx != self.playerPos["x"] and dy != self.playerPos["y"]:
self.mmap[dy][dx] = 14
return True
def _reset (self):
self.mmap = np.array([[0]*self.xdim]*self.ydim)
for y in range(self.ydim):
self.mmap[y][0] = -1
self.mmap[y][self.ydim-1] = -1
for x in range(self.xdim):
self.mmap[0][x] = -1
self.mmap[self.ydim-1][x] = -1
self.playerPos["x"] = random.randint(1, self.xdim-2)
self.playerPos["y"] = random.randint(1, self.ydim-2)
self.mmap[self.playerPos["y"]][self.playerPos["x"]] = 13
for z in range(10):
## place 10 targets
self.addMapReward()
for z in range(5):
## place 5 bombs
## bomb = 14
self.addBombToMap()
self._turnNumber = 0
self._episode_ended = False
#return ts.restart (self.mmap)
dap = ts.restart(np.array(self.mmap, dtype=np.int32).flatten())
return (dap)
def render(self, mapToRender):
mapToRender.reshape(21,21)
for y in range(self.ydim):
o =""
for x in range(self.xdim):
if mapToRender[y][x]==-1:
o=o+"#"
elif mapToRender[y][x]>0 and mapToRender[y][x]<10:
o=o+str(mapToRender[y][x])
elif mapToRender[y][x] == 13:
o=o+"@"
elif mapToRender[y][x] == 14:
o=o+"*"
else:
o=o+" "
print (o)
print ('TOTAL SCORE:', self.totalScore, 'LAST TURN SCORE:', self.reward)
return True
def getInput(self):
self.input = 0
i = input()
if i == 'w' or i == '0':
print ('going N')
self.input = 1
if i == 's' or i == '1':
print ('going S')
self.input = 2
if i == 'a' or i == '2':
print ('going W')
self.input = 3
if i == 'd' or i == '3':
print ('going E')
self.input = 4
if i == 'x':
self.input = 5
return self.input
def processMove(self):
self.mmap[self.playerPos["y"]][self.playerPos["x"]] = 0
self.reward = 0
if self.input == 0:
self.playerPos["y"] -=1
if self.input == 1:
self.playerPos["y"] +=1
if self.input == 2:
self.playerPos["x"] -=1
if self.input == 3:
self.playerPos["x"] +=1
cloc = self.mmap[self.playerPos["y"]][self.playerPos["x"]]
if cloc == -1 or cloc ==14:
self.totalScore = 0
self.reward = -99
if cloc >0 and cloc < 10:
self.totalScore += cloc
self.reward = cloc
self.mmap[self.playerPos["y"]][self.playerPos["x"]] = 0
self.mmap[self.playerPos["y"]][self.playerPos["x"]] = 13
self.render(self.mmap)
def runTurn(self):
clear_output(wait=True)
if self._turnNumber % self.addRewardEveryNTurns == 0:
self.addMapReward()
if self._turnNumber % self.addBombEveryNTurns == 0:
self.addBombToMap()
self.getInput()
self.processMove()
self._turnNumber +=1
if self.reward == -99:
self._turnNumber +=1
self._reset()
self.totalScore = 0
self.render(self.mmap)
return (self.reward)
def _step (self, action):
if self._episode_ended == True:
return self._reset()
clear_output(wait=True)
if self._turnNumber % self.addRewardEveryNTurns == 0:
self.addMapReward()
if self._turnNumber % self.addBombEveryNTurns == 0:
self.addBombToMap()
## make sure action does produce exceed range
#if action > 5 or action <1:
# action =0
self.input = action ## value 1 to 4
self.processMove()
self._turnNumber +=1
if self.reward == -99:
self._turnNumber +=1
self._episode_ended = True
#self._reset()
self.totalScore = 0
self.render(self.mmap)
return ts.termination(np.array(self.mmap, dtype=np.int32).flatten(), reward = self.reward)
else:
return ts.transition(np.array(self.mmap, dtype=np.int32).flatten(), reward = self.reward) #, discount = 1.0
def run (self):
self._reset()
self.render(self.mmap)
while (True):
self.runTurn()
if self.input == 5:
return ("EXIT on input x ")
env = cGame()
</code></pre>
<p>The class I want to use for training the model is:</p>
<pre><code>from tf_agents.specs import tensor_spec
from tf_agents.networks import sequential
from tf_agents.agents.dqn import dqn_agent
from tf_agents.utils import common
from tf_agents.policies import py_tf_eager_policy
from tf_agents.policies import random_tf_policy
import reverb
from tf_agents.replay_buffers import reverb_replay_buffer
from tf_agents.replay_buffers import reverb_utils
from tf_agents.trajectories import trajectory
from tf_agents.drivers import py_driver
from tf_agents.environments import BatchedPyEnvironment
class mTrainer:
def __init__ (self):
self.train_env = tf_py_environment.TFPyEnvironment(cGame())
self.eval_env = tf_py_environment.TFPyEnvironment(cGame())
self.num_iterations = 20000 # @param {type:"integer"}
self.initial_collect_steps = 100 # @param {type:"integer"}
self.collect_steps_per_iteration = 100 # @param {type:"integer"}
self.replay_buffer_max_length = 100000 # @param {type:"integer"}
self.batch_size = 64 # @param {type:"integer"}
self.learning_rate = 1e-3 # @param {type:"number"}
self.log_interval = 200 # @param {type:"integer"}
self.num_eval_episodes = 10 # @param {type:"integer"}
self.eval_interval = 1000 # @param {type:"integer"}
def createAgent(self):
fc_layer_params = (100, 50)
action_tensor_spec = tensor_spec.from_spec(self.train_env.action_spec())
num_actions = action_tensor_spec.maximum - action_tensor_spec.minimum + 1
def dense_layer(num_units):
return tf.keras.layers.Dense(
num_units,
activation=tf.keras.activations.relu,
kernel_initializer=tf.keras.initializers.VarianceScaling(
scale=2.0, mode='fan_in', distribution='truncated_normal'))
dense_layers = [dense_layer(num_units) for num_units in fc_layer_params]
q_values_layer = tf.keras.layers.Dense(
num_actions,
activation=None,
kernel_initializer=tf.keras.initializers.RandomUniform(
minval=-0.03, maxval=0.03),
bias_initializer=tf.keras.initializers.Constant(-0.2))
self.q_net = sequential.Sequential(dense_layers + [q_values_layer])
optimizer = tf.keras.optimizers.Adam(learning_rate=self.learning_rate)
#rain_step_counter = tf.Variable(0)
self.agent = dqn_agent.DqnAgent(
time_step_spec = self.train_env.time_step_spec(),
action_spec = self.train_env.action_spec(),
q_network=self.q_net,
optimizer=optimizer,
td_errors_loss_fn=common.element_wise_squared_loss,
train_step_counter=tf.Variable(0))
self.agent.initialize()
self.eval_policy = self.agent.policy
self.collect_policy = self.agent.collect_policy
self.random_policy = random_tf_policy.RandomTFPolicy(self.train_env.time_step_spec(),self.train_env.action_spec())
return True
def compute_avg_return(self, environment, policy, num_episodes=10):
#mT.compute_avg_return(mT.eval_env, mT.random_policy, 50)
total_return = 0.0
for _ in range(num_episodes):
time_step = environment.reset()
episode_return = 0.0
while not time_step.is_last():
action_step = policy.action(time_step)
time_step = environment.step(action_step.action)
episode_return += time_step.reward
total_return += episode_return
avg_return = total_return / num_episodes
print ('average return :', avg_return.numpy()[0])
return avg_return.numpy()[0]
def create_replaybuffer(self):
table_name = 'uniform_table'
replay_buffer_signature = tensor_spec.from_spec(self.agent.collect_data_spec)
replay_buffer_signature = tensor_spec.add_outer_dim(replay_buffer_signature)
table = reverb.Table(table_name,
max_size=self.replay_buffer_max_length,
sampler=reverb.selectors.Uniform(),
remover=reverb.selectors.Fifo(),
rate_limiter=reverb.rate_limiters.MinSize(1),
signature=replay_buffer_signature)
reverb_server = reverb.Server([table])
self.replay_buffer = reverb_replay_buffer.ReverbReplayBuffer(
self.agent.collect_data_spec,
table_name=table_name,
sequence_length=2,
local_server=reverb_server)
self.rb_observer = reverb_utils.ReverbAddTrajectoryObserver(
self.replay_buffer.py_client,
table_name,
sequence_length=2)
self.dataset = self.replay_buffer.as_dataset(num_parallel_calls=3,sample_batch_size=self.batch_size,num_steps=2).prefetch(3)
self.iterator = iter(self.dataset)
def testReplayBuffer(self):
py_driver.PyDriver(
self.train_env,
py_tf_eager_policy.PyTFEagerPolicy(
self.random_policy,
use_tf_function=True),
[self.rb_observer],
max_steps=self.initial_collect_steps).run(self.train_env.reset())
def trainAgent(self):
print (self.collect_policy)
# Create a driver to collect experience.
collect_driver = py_driver.PyDriver(
self.train_env,
py_tf_eager_policy.PyTFEagerPolicy(
self.agent.collect_policy,
batch_time_steps=False,
use_tf_function=True),
[self.rb_observer],
max_steps=self.collect_steps_per_iteration)
# Reset the environment.
time_step = self.train_env.reset()
for _ in range(self.num_iterations):
# Collect a few steps and save to the replay buffer.
time_step, _ = collect_driver.run(time_step)
# Sample a batch of data from the buffer and update the agent's network.
experience, unused_info = next(self.iterator)
train_loss = agent.train(experience).loss
step = agent.train_step_counter.numpy()
if step % log_interval == 0:
print('step = {0}: loss = {1}'.format(step, train_loss))
if step % eval_interval == 0:
avg_return = self.compute_avg_return(self.eval_env, agent.policy, num_eval_episodes)
print('step = {0}: Average Return = {1}'.format(step, avg_return))
self.returns.append(avg_return)
def run(self):
self.createAgent()
#self.compute_avg_return(self.train_env,self.eval_policy)
self.create_replaybuffer()
#self.testReplayBuffer()
self.trainAgent()
return True
mT = mTrainer()
mT.run()
</code></pre>
<p>It produces this error message:</p>
<p>InvalidArgumentError: Received incompatible tensor at flattened index 4 from table 'uniform_table'. Specification has (dtype, shape): (int32, [?]). Tensor has (dtype, shape): (int32, [2,1]).
Table signature: 0: Tensor<name: 'key', dtype: uint64, shape: []>, 1: Tensor<name: 'probability', dtype: double, shape: []>, 2: Tensor<name: 'table_size', dtype: int64, shape: []>, 3: Tensor<name: 'priority', dtype: double, shape: []>, 4: Tensor<name: 'step_type/step_type', dtype: int32, shape: [?]>, 5: Tensor<name: 'observation/observation', dtype: int32, shape: [?,441]>, 6: Tensor<name: 'action/action', dtype: int32, shape: [?]>, 7: Tensor<name: 'next_step_type/step_type', dtype: int32, shape: [?]>, 8: Tensor<name: 'reward/reward', dtype: float, shape: [?]>, 9: Tensor<name: 'discount/discount', dtype: float, shape: [?]> [Op:IteratorGetNext]</p>
|
<p>I got stuck with a similar issue, the reason for it is that, you are using tensorflow environment as the parameter of the <code>PyDriver</code> to collect the data. Tensorflow environment adds a batch dimension to all the tensors that it produces, therefore, each <code>time_step</code> generated will have an additional dimension whose value will be 1.</p>
<p>Now, when you retrieve the data from the replay buffer, each of <code>time_step</code> will have an additional dimension and it is not compatible with the data that the train function of the agent is expecting, hence the error.</p>
<p>You need to use a python environment here in order to collect the data with right dimension. Also, now you don't have to use <code>batch_time_steps = False</code>.</p>
<p>I am not sure how to collect the data with right dimensions with a tensorflow environment so I have modified your code a bit to allow data collection using python environment and it should run now.</p>
<p>PS - There were a few trivial bugs in the code you posted (ex. using <code>log_interval</code> instead of <code>self.log_interval</code> etc).</p>
<p><strong>Agent Class</strong>
`</p>
<pre><code> from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import random
from IPython.display import clear_output
import time
import abc
import tensorflow as tf
import numpy as np
from tf_agents.environments import py_environment
from tf_agents.environments import tf_environment
from tf_agents.environments import tf_py_environment
from tf_agents.environments import utils
from tf_agents.specs import array_spec
from tf_agents.environments import wrappers
from tf_agents.environments import suite_gym
from tf_agents.trajectories import time_step as ts
class cGame(py_environment.PyEnvironment):
def __init__(self):
self.xdim = 21
self.ydim = 21
self.mmap = np.array([[0] * self.xdim] * self.ydim)
self._turnNumber = 0
self.playerPos = {"x": 1, "y": 1}
self.totalScore = 0
self.reward = 0.0
self.input = 0
self.addRewardEveryNTurns = 4
self.addBombEveryNTurns = 3
self._episode_ended = False
## player = 13
## bomb = 14
self._action_spec = array_spec.BoundedArraySpec(shape=(),
dtype=np.int32,
minimum=0, maximum=3,
name='action')
self._observation_spec = array_spec.BoundedArraySpec(shape=(441,),
minimum=np.array(
[-1] * 441),
maximum=np.array(
[20] * 441),
dtype=np.int32,
name='observation') # (self.xdim, self.ydim) , self.mmap.shape, minimum = -1, maximum = 10
def action_spec(self):
return self._action_spec
def observation_spec(self):
return self._observation_spec
def addMapReward(self):
dx = random.randint(1, self.xdim - 2)
dy = random.randint(1, self.ydim - 2)
if dx != self.playerPos["x"] and dy != self.playerPos["y"]:
self.mmap[dy][dx] = random.randint(1, 9)
return True
def addBombToMap(self):
dx = random.randint(1, self.xdim - 2)
dy = random.randint(1, self.ydim - 2)
if dx != self.playerPos["x"] and dy != self.playerPos["y"]:
self.mmap[dy][dx] = 14
return True
def _reset(self):
self.mmap = np.array([[0] * self.xdim] * self.ydim)
for y in range(self.ydim):
self.mmap[y][0] = -1
self.mmap[y][self.ydim - 1] = -1
for x in range(self.xdim):
self.mmap[0][x] = -1
self.mmap[self.ydim - 1][x] = -1
self.playerPos["x"] = random.randint(1, self.xdim - 2)
self.playerPos["y"] = random.randint(1, self.ydim - 2)
self.mmap[self.playerPos["y"]][self.playerPos["x"]] = 13
for z in range(10):
## place 10 targets
self.addMapReward()
for z in range(5):
## place 5 bombs
## bomb = 14
self.addBombToMap()
self._turnNumber = 0
self._episode_ended = False
# return ts.restart (self.mmap)
dap = ts.restart(np.array(self.mmap, dtype=np.int32).flatten())
return (dap)
def render(self, mapToRender):
mapToRender.reshape(21, 21)
for y in range(self.ydim):
o = ""
for x in range(self.xdim):
if mapToRender[y][x] == -1:
o = o + "#"
elif mapToRender[y][x] > 0 and mapToRender[y][x] < 10:
o = o + str(mapToRender[y][x])
elif mapToRender[y][x] == 13:
o = o + "@"
elif mapToRender[y][x] == 14:
o = o + "*"
else:
o = o + " "
print(o)
print('TOTAL SCORE:', self.totalScore, 'LAST TURN SCORE:', self.reward)
return True
def getInput(self):
self.input = 0
i = input()
if i == 'w' or i == '0':
print('going N')
self.input = 1
if i == 's' or i == '1':
print('going S')
self.input = 2
if i == 'a' or i == '2':
print('going W')
self.input = 3
if i == 'd' or i == '3':
print('going E')
self.input = 4
if i == 'x':
self.input = 5
return self.input
def processMove(self):
self.mmap[self.playerPos["y"]][self.playerPos["x"]] = 0
self.reward = 0
if self.input == 0:
self.playerPos["y"] -= 1
if self.input == 1:
self.playerPos["y"] += 1
if self.input == 2:
self.playerPos["x"] -= 1
if self.input == 3:
self.playerPos["x"] += 1
cloc = self.mmap[self.playerPos["y"]][self.playerPos["x"]]
if cloc == -1 or cloc == 14:
self.totalScore = 0
self.reward = -99
if cloc > 0 and cloc < 10:
self.totalScore += cloc
self.reward = cloc
self.mmap[self.playerPos["y"]][self.playerPos["x"]] = 0
self.mmap[self.playerPos["y"]][self.playerPos["x"]] = 13
self.render(self.mmap)
def runTurn(self):
clear_output(wait=True)
if self._turnNumber % self.addRewardEveryNTurns == 0:
self.addMapReward()
if self._turnNumber % self.addBombEveryNTurns == 0:
self.addBombToMap()
self.getInput()
self.processMove()
self._turnNumber += 1
if self.reward == -99:
self._turnNumber += 1
self._reset()
self.totalScore = 0
self.render(self.mmap)
return (self.reward)
def _step(self, action):
if self._episode_ended == True:
return self._reset()
clear_output(wait=True)
if self._turnNumber % self.addRewardEveryNTurns == 0:
self.addMapReward()
if self._turnNumber % self.addBombEveryNTurns == 0:
self.addBombToMap()
## make sure action does produce exceed range
# if action > 5 or action <1:
# action =0
self.input = action ## value 1 to 4
self.processMove()
self._turnNumber += 1
if self.reward == -99:
self._turnNumber += 1
self._episode_ended = True
# self._reset()
self.totalScore = 0
self.render(self.mmap)
return ts.termination(np.array(self.mmap, dtype=np.int32).flatten(),
reward=self.reward)
else:
return ts.transition(np.array(self.mmap, dtype=np.int32).flatten(),
reward=self.reward) # , discount = 1.0
def run(self):
self._reset()
self.render(self.mmap)
while (True):
self.runTurn()
if self.input == 5:
return ("EXIT on input x ")
env = cGame()
</code></pre>
<p>`</p>
<p><strong>Driver Code</strong>
`</p>
<pre><code> from tf_agents.specs import tensor_spec
from tf_agents.networks import sequential
from tf_agents.agents.dqn import dqn_agent
from tf_agents.utils import common
from tf_agents.policies import py_tf_eager_policy
from tf_agents.policies import random_tf_policy
import reverb
from tf_agents.replay_buffers import reverb_replay_buffer
from tf_agents.replay_buffers import reverb_utils
from tf_agents.trajectories import trajectory
from tf_agents.drivers import py_driver
from tf_agents.environments import BatchedPyEnvironment
class mTrainer:
def __init__(self):
self.returns = None
self.train_env = tf_py_environment.TFPyEnvironment(cGame())
self.eval_env = tf_py_environment.TFPyEnvironment(cGame())
self.num_iterations = 20000 # @param {type:"integer"}
self.initial_collect_steps = 100 # @param {type:"integer"}
self.collect_steps_per_iteration = 100 # @param {type:"integer"}
self.replay_buffer_max_length = 100000 # @param {type:"integer"}
self.batch_size = 64 # @param {type:"integer"}
self.learning_rate = 1e-3 # @param {type:"number"}
self.log_interval = 200 # @param {type:"integer"}
self.num_eval_episodes = 10 # @param {type:"integer"}
self.eval_interval = 1000 # @param {type:"integer"}
def createAgent(self):
fc_layer_params = (100, 50)
action_tensor_spec = tensor_spec.from_spec(self.train_env.action_spec())
num_actions = action_tensor_spec.maximum - action_tensor_spec.minimum + 1
def dense_layer(num_units):
return tf.keras.layers.Dense(
num_units,
activation=tf.keras.activations.relu,
kernel_initializer=tf.keras.initializers.VarianceScaling(
scale=2.0, mode='fan_in', distribution='truncated_normal'))
dense_layers = [dense_layer(num_units) for num_units in fc_layer_params]
q_values_layer = tf.keras.layers.Dense(
num_actions,
activation=None,
kernel_initializer=tf.keras.initializers.RandomUniform(
minval=-0.03, maxval=0.03),
bias_initializer=tf.keras.initializers.Constant(-0.2))
self.q_net = sequential.Sequential(dense_layers + [q_values_layer])
optimizer = tf.keras.optimizers.Adam(learning_rate=self.learning_rate)
# rain_step_counter = tf.Variable(0)
self.agent = dqn_agent.DqnAgent(
time_step_spec=self.train_env.time_step_spec(),
action_spec=self.train_env.action_spec(),
q_network=self.q_net,
optimizer=optimizer,
td_errors_loss_fn=common.element_wise_squared_loss,
train_step_counter=tf.Variable(0))
self.agent.initialize()
self.eval_policy = self.agent.policy
self.collect_policy = self.agent.collect_policy
self.random_policy = random_tf_policy.RandomTFPolicy(
self.train_env.time_step_spec(), self.train_env.action_spec())
return True
def compute_avg_return(self, environment, policy, num_episodes=10):
# mT.compute_avg_return(mT.eval_env, mT.random_policy, 50)
total_return = 0.0
for _ in range(num_episodes):
time_step = environment.reset()
episode_return = 0.0
while not time_step.is_last():
action_step = policy.action(time_step)
time_step = environment.step(action_step.action)
episode_return += time_step.reward
total_return += episode_return
avg_return = total_return / num_episodes
print('average return :', avg_return.numpy()[0])
return avg_return.numpy()[0]
def create_replaybuffer(self):
table_name = 'uniform_table'
replay_buffer_signature = tensor_spec.from_spec(
self.agent.collect_data_spec)
replay_buffer_signature = tensor_spec.add_outer_dim(
replay_buffer_signature)
table = reverb.Table(table_name,
max_size=self.replay_buffer_max_length,
sampler=reverb.selectors.Uniform(),
remover=reverb.selectors.Fifo(),
rate_limiter=reverb.rate_limiters.MinSize(1),
signature=replay_buffer_signature)
reverb_server = reverb.Server([table])
self.replay_buffer = reverb_replay_buffer.ReverbReplayBuffer(
self.agent.collect_data_spec,
table_name=table_name,
sequence_length=2,
local_server=reverb_server)
self.rb_observer = reverb_utils.ReverbAddTrajectoryObserver(
self.replay_buffer.py_client,
table_name,
sequence_length=2)
self.dataset = self.replay_buffer.as_dataset(num_parallel_calls=3,
sample_batch_size=self.batch_size,
num_steps=2).prefetch(3)
self.iterator = iter(self.dataset)
def testReplayBuffer(self):
py_env = cGame()
py_driver.PyDriver(
py_env,
py_tf_eager_policy.PyTFEagerPolicy(
self.random_policy,
use_tf_function=True),
[self.rb_observer],
max_steps=self.initial_collect_steps).run(self.train_env.reset())
def trainAgent(self):
self.returns = list()
print(self.collect_policy)
py_env = cGame()
# Create a driver to collect experience.
collect_driver = py_driver.PyDriver(
py_env, # CHANGE 1
py_tf_eager_policy.PyTFEagerPolicy(
self.agent.collect_policy,
# batch_time_steps=False, # CHANGE 2
use_tf_function=True),
[self.rb_observer],
max_steps=self.collect_steps_per_iteration)
# Reset the environment.
# time_step = self.train_env.reset()
time_step = py_env.reset()
for _ in range(self.num_iterations):
# Collect a few steps and save to the replay buffer.
time_step, _ = collect_driver.run(time_step)
# Sample a batch of data from the buffer and update the agent's network.
experience, unused_info = next(self.iterator)
train_loss = self.agent.train(experience).loss
step = self.agent.train_step_counter.numpy()
if step % self.log_interval == 0:
print('step = {0}: loss = {1}'.format(step, train_loss))
if step % self.eval_interval == 0:
avg_return = self.compute_avg_return(self.eval_env,
self.agent.policy,
self.num_eval_episodes)
print(
'step = {0}: Average Return = {1}'.format(step, avg_return))
self.returns.append(avg_return)
def run(self):
self.createAgent()
# self.compute_avg_return(self.train_env,self.eval_policy)
self.create_replaybuffer()
# self.testReplayBuffer()
self.trainAgent()
return True
if __name__ == '__main__':
mT = mTrainer()
mT.run()
</code></pre>
<p>`</p>
|
python|tensorflow|keras|agent
| 0 |
1,906,230 | 68,128,389 |
How to separately change the opacity of a text on a button pygame?
|
<p>I have the following code below that is a class for a button taken from another post. I was wondering if I can change the opacity of the background of the button without changing the opacity of the text on it. How can I achieve this?</p>
<p>Code:</p>
<pre><code>import pygame
pygame.init()
font = pygame.font.SysFont('Microsoft New Tai Lue', 23)
class Button(pygame.sprite.Sprite):
# 1) no need to have 4 parameters for position and size, use pygame.Rect instead
# 2) let the Button itself handle which color it is
# 3) give a callback function to the button so it can handle the click itself
def __init__(self, color, color_hover, rect, callback, text='', outline=None):
super().__init__()
self.text = text
# a temporary Rect to store the size of the button
tmp_rect = pygame.Rect(0, 0, *rect.size)
self.org = self._create_image(color, outline, text, tmp_rect)
self.hov = self._create_image(color_hover, outline, text, tmp_rect)
self.image = self.org
self.rect = rect
self.callback = callback
def _create_image(self, color, outline, text, rect):
img = pygame.Surface(rect.size)
#img.set_alpha(110)
if outline:
img.fill(outline)
img.fill(color, rect.inflate(-4, -4))
else:
img.fill(color)
# render the text once here instead of every frame
if text != '':
text_surf = font.render(text, 1, pygame.Color('white'))
text_rect = text_surf.get_rect(center=rect.center)
img.blit(text_surf, text_rect)
return img
def update(self, events):
# here we handle all the logic of the Button
pos = pygame.mouse.get_pos()
hit = self.rect.collidepoint(pos)
self.image = self.hov if hit else self.org
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN and hit:
self.callback(self)
</code></pre>
<p>Any help is appreciated.</p>
|
<p>You need to create a <a href="https://www.pygame.org/docs/ref/surface.html" rel="nofollow noreferrer"><code>pygame.Surface</code></a> with an alpha channel per pixel. This can be done by setting the <code>pygame.SRCALPHA</code> flag:</p>
<pre class="lang-py prettyprint-override"><code>class Button(pygame.sprite.Sprite):
# [...]
def _create_image(self, color, outline, text, rect):
img = pygame.Surface(rect.size, pygame.SRCALPHA) # <---
if outline:
img.fill(outline)
img.fill(color, rect.inflate(-4, -4))
else:
img.fill(color)
</code></pre>
<p>Use a semitransparent color for the background of the button:</p>
<pre class="lang-py prettyprint-override"><code>color = (255, 0, 0, 127) # just for example red color with ~50% transparency
</code></pre>
<p>See also <a href="https://github.com/Rabbid76/PyGameExamplesAndAnswers/blob/master/documentation/pygame/pygame_text_and_font.md#transparent-text" rel="nofollow noreferrer">Transparent text</a></p>
<hr />
<p>Minimal example:</p>
<p><kbd><a href="https://replit.com/@Rabbid76/PyGame-TextTransparentBackground#main.py" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5jD0C.png" alt="" /> repl.it/@Rabbid76/PyGame-TextTransparentBackground</a></kbd></p>
<p><a href="https://i.stack.imgur.com/dW5OU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dW5OU.png" alt="" /></a></p>
<pre class="lang-py prettyprint-override"><code>import pygame
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
font = pygame.font.SysFont(None, 80)
text = font.render("Button", True, (255, 255, 255))
button = pygame.Surface((320, 120), pygame.SRCALPHA)
button.fill((255, 255, 255))
button.fill((196, 127, 127, 127), button.get_rect().inflate(-4, -4))
button.blit(text, text.get_rect(center = button.get_rect().center))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
window.blit(button, button.get_rect(center = window.get_rect().center))
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
</code></pre>
|
python|pygame
| 1 |
1,906,231 | 68,257,432 |
How to zip an html file from a stream/rendered dictionary?
|
<p>I am having trouble downloading an html file through the flask send_file.</p>
<ol>
<li><p>Basically, to download an html file alone, it works perfectly. by giving the stream to the send_file function as a parameter</p>
</li>
<li><p>However; I need to put this file into a zip along with other unrelated files. There, in the write function, neither the stream nor the string (result_html) work. I need somehow to transform it directly to an html file and put in the zip file</p>
</li>
</ol>
<p>I don't see how I could do this for the moment. I have the data (output) as a dict...</p>
<p>Thank you if you have any pointers</p>
<pre><code>from flask import render_template, send_file
from io import BytesIO
result_html = render_template('myResult.html', **output)
result_stream = BytesIO(str(result_html).encode())
with ZipFile("zipped_result.zip", "w") as zf:
zf.write(result_html)
# zf.write(other_files)
send_file(zf, as_attachment=True, attachment_filename="myfile.zip")
</code></pre>
|
<p>If I understand you correctly, it is sufficient to write the zip file in a stream and add the result of the rendering as a character string to the zip file. The stream can then be transmitted via send_file.</p>
<pre><code>from flask import render_template, send_file
from io import BytesIO
from zipfile import ZipFile
# ...
@app.route('/download')
def download():
output = { 'name': 'Unknown' }
result_html = render_template('result.html', **output)
stream = BytesIO()
with ZipFile(stream, 'w') as zf:
zf.writestr('result.html', result_html)
# ...
stream.seek(0)
return send_file(stream, as_attachment=True, attachment_filename='archive.zip')
</code></pre>
|
python|html|flask|zip|sendfile
| 1 |
1,906,232 | 73,147,045 |
Each process starts from the beginning of .py file
|
<p>I am new in multiprocessing. My problem is, each process starts from the beginning of .py file.
My code prints "Starting file" 3 times but it should only be printed once. Here is the output and code. Please help. Thanks.</p>
<p><a href="https://i.stack.imgur.com/BLsYE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BLsYE.png" alt="enter image description here" /></a></p>
<pre><code>import multiprocessing
from time import sleep
print("Starting file")
def worker1():
x=1
while 1<2:
print("worker1: "+str(x))
x=x+1
sleep(3)
def worker2():
x=2
while 1<2:
print("worker2: "+str(x))
x=x+2
sleep(2)
if __name__ == "__main__":
p1 = multiprocessing.Process(target=worker1)
p2 = multiprocessing.Process(target=worker2)
p1.start()
p2.start()
p1.join()
p2.join()
</code></pre>
|
<p>Move your <code>print("Starting file")</code> to inside your script entrypoint.</p>
<p>I'd have to read the source code to really verify, but basically, when you start a <code>multiprocessing.Process</code> with some target, the resulting <code>Process</code> is going to import the target's module, which causes it to run any code like <code>import</code> and free-standing statements, like the <code>print</code> statement you have. Since you are creating two processes, each one will execute your <code>print</code> statement, resulting in the two extra lines you see.</p>
<p>If I move your <code>print</code> to within the <code>__main__</code>, this works as you expect:</p>
<pre><code>import multiprocessing
from time import sleep
def worker1():
x=1
while 1<2:
print("worker1: "+str(x))
x=x+1
sleep(3)
def worker2():
x=2
while 1<2:
print("worker2: "+str(x))
x=x+2
sleep(2)
if __name__ == "__main__":
print("Starting file")
p1 = multiprocessing.Process(target=worker1)
p2 = multiprocessing.Process(target=worker2)
p1.start()
p2.start()
p1.join()
p2.join()
</code></pre>
<p>Output:</p>
<pre><code>> python mptest.py
Starting file
worker2: 2
worker1: 1
worker2: 4
worker1: 2
# and so on...
</code></pre>
<hr />
<h2>A deeper explanation</h2>
<p>I'll point out that the reason you're seeing what you're seeing is that you're on a platform that uses <code>spawn</code> to start the <code>multiprocessing</code> processes, which means Windows and macOS.</p>
<p>From the <a href="https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods" rel="nofollow noreferrer"><code>multiprocessing</code> documentation</a></p>
<blockquote>
<p><strong>spawn</strong></p>
<p>The parent process starts a fresh Python interpreter process.
The child process will only inherit those resources necessary to run
the process object’s <code>run()</code> method. In particular, unnecessary file
descriptors and handles from the parent process will not be inherited.
Starting a process using this method is rather slow compared to using
fork or forkserver.</p>
<p>Available on Unix and Windows. The default on Windows and macOS.</p>
<p><strong>fork</strong></p>
<p>The parent process uses <code>os.fork()</code> to fork the Python interpreter.
The child process, when it begins, is effectively identical to the
parent process. All resources of the parent are inherited by the child
process. Note that safely forking a multithreaded process is
problematic.</p>
<p>Available on Unix only. The default on Unix.</p>
</blockquote>
<p>If you ran your original code on something like a Linux-based system, you would not see your original issue because it would use <code>os.fork()</code> to start the subprocesses, so the children would get a copy of the parent's virtual memory.</p>
<pre><code># On my CentOS system
> python3 mptest.py
Starting file
worker2: 2
worker1: 1
</code></pre>
<p>However, if I change <code>multiprocessing</code> to use <code>spawn</code>, by using <code>multiprocessing.set_start_method</code>...</p>
<pre><code>if __name__ == "__main__":
# force 'spawn'
multiprocessing.set_start_method('spawn')
p1 = multiprocessing.Process(target=worker1)
p2 = multiprocessing.Process(target=worker2)
p1.start()
p2.start()
p1.join()
p2.join()
</code></pre>
<p>I get your original issue...</p>
<pre><code># still on my CentOS system, now with 'spawn' mode set
python3 mptest.py
Starting file
Starting file
Starting file
worker2: 2
worker1: 1
</code></pre>
<p>However, don't rely on that behaviorial difference of spawning vs. forking if you want your <code>multiprocessing</code> code to run on more than just your own system.</p>
|
python|python-multiprocessing
| 2 |
1,906,233 | 62,043,434 |
To find approximate DOB based on age and a date column
|
<p>I have three columns in a data frame: start_date, age and DOB.
But some of the DOB information is missing, while start_date and age are not. I wish to impute the empty cells of DOB column, with an approximate DOB, using the formula: start_date - age.</p>
<p>An example of the data frame:</p>
<pre><code>start_date | age | DOB
3/1/2017 87 11/1/1930
9/13/2017 31
7/26/2017 60
7/26/2017 52
4/1/2017 37 12/14/1979
</code></pre>
<p>My question is how to execute this, only on the empty cells of the DOB column of the data frame?
Is there any easy way?</p>
<p>Thanks and regards</p>
|
<p>Here's a way to do that: </p>
<pre><code>df.DOB = pd.to_datetime(df.DOB)
estimated_dob = pd.to_datetime(df.start_date) - pd.to_timedelta(df.age, unit='y')
df.loc[df.DOB.isna(), "DOB"] = estimated_dob[df.DOB.isna()]
#to remove the time part of the timestamp:
df["DOB"] = df["DOB"].dt.date
</code></pre>
<p>The result is: </p>
<pre><code> start_date age DOB
0 3/1/2017 87 1930-11-01
1 9/13/2017 31 1986-09-13
2 7/26/2017 60 1957-07-26
3 7/26/2017 52 1965-07-26
4 4/1/2017 37 1979-12-14
</code></pre>
|
python
| 0 |
1,906,234 | 35,336,142 |
Python - issue with using a list of frozenset entries in a for loop
|
<p>I am trying to learn the apriori machine learning algorithm from a book that uses Python, and as part of that learning, I am currently stuck with this following problem:</p>
<p>The following code construct seems to work fine:</p>
<pre><code>Ck = [[1], [2], [3], [4], [5]]
for tranid in range(10):
for candidate in Ck:
print("Printing candidate value: ", candidate)
</code></pre>
<p>However, the following does not work:</p>
<pre><code>Ck = [[1], [2], [3], [4], [5]]
Ck2 = map(frozenset, Ck)
for tranid in range(10):
for candidate in Ck2:
print("Printing candidate value: ", candidate)
</code></pre>
<p>When I map every element of my original iterable to a frozenset, I notice that the inner loop (<em>"for candidate in Ck2"</em>) executes only once. After that it never executes. The code above without the frozenset properly loops through the inner loop 10 times. However, with frozenset mapped, I can get the inner loop to execute only once.</p>
<p>Please help me with fixing this. The book has mapped the iterable values to frozenset because they don't want it to be mutable for the purposes of the algorithm. I am simply trying to follow it as is.</p>
<p>I am using Python 3.5.1 on Anaconda (Spyder).</p>
<p>Please help, as I am new to both Python and Machine Learning.</p>
<p>Thanks and Regards,
Mahesh. </p>
|
<p>The map operator does not return a list in python3 which
you can iterate repeatily, but a one-time-iterable iterator.
In python3.x, <code>map</code> works similar to <code>itertools.imap</code> in python2.x.</p>
<p>To solve the issue, use</p>
<pre><code> Ck2=list(map(frozenset, Ck)))
</code></pre>
<p>and see <a href="https://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x">Getting a map() to return a list in Python 3.x</a> for more information and other solutions.</p>
|
python|python-3.x|set|frozenset
| 5 |
1,906,235 | 35,744,235 |
Upload files to a specific Google Drive folder using python
|
<p>I'm creating a simple web app that saves some files in my Google Drive using the Auth2.0 authentication. Everything works well when I use the code below, but I struggle with some things here. The first one is to save the content in a different specified folder. The code below save the files in the root folder and I can't figure out why.The <em>upload_folder_id</em> evidently has the good value, that I omitted here. </p>
<pre><code>from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store, flags) \
if flags else tools.run(flow, store)
DRIVE = build('drive', 'v3', http=creds.authorize(Http()))
upload_folder_id = <my_folder_id>
FILES = (('hello.txt', None)) # More files will be added after
for filename, mimeType in FILES:
metadata = {'name': filename}
if mimeType:
metadata['mimeType'] = mimeType
''' I tried all this possibilities too
metadata['parentId'] = upload_folder_id
metadata['folderId'] = upload_folder_id
'''
metadata['parents'] = [{'id': upload_folder_id}]
res = DRIVE.files().create(body=metadata, media_body=filename).execute()
if res:
print('Uploaded "%s" (%s)' % (filename, res['mimeType']))
</code></pre>
<p>The second is the authentication step. The first time that I connected the application, I was redirected to a google web page where I grant the API access. Is there a way to do this without going through the web browser to validate the access? (It's fine doing that for my local tests but I'll not be able to do this in the production server).</p>
|
<p><strong>The code below save the files in the root folder and I can't figure out why.The upload_folder_id evidently has the good value, that I omitted here.</strong></p>
<p><code>parents</code> is supposed to be a string array, so there's no need for the <code>id</code> property to be there; just specify the parent folderId and I think you're good to go</p>
<p><strong>Is there a way to do this without going through the web browser to validate the access?</strong></p>
<p>The consent page is critical for the authentication process of the user, I don't think scraping can be a solution here. An alternative I can think of is for you to use Service Accounts, which is a server-to-server implementation so that the users don't need to login. The drawback here though is for the user doesn't own the data, the service account does.</p>
|
python|google-drive-api
| 0 |
1,906,236 | 59,025,559 |
Loop to find space with python
|
<pre><code>c = "ab cd ef gf"
n = []
for x in c:
if x == " ":
d = c.find(x)
n.append(d)
print(n)
</code></pre>
<p>I want this code to give me something like this. [2,5,8]
But instead it is giving me this. [2,2,2]</p>
<p>Please help me find the mistake. Thank you.</p>
|
<p><code>find()</code> will find the first instance, so it always finds the space at index 2. You could keep track of the index as you go with <code>enumerate()</code> so you don't need <code>find()</code>:</p>
<pre><code>c = "ab cd ef gf"
n = []
for i, x in enumerate(c):
if x == " ":
n.append(i)
print(n)
</code></pre>
<p>Alternatively as a list comprehension:</p>
<pre><code>[i for i, x in enumerate(c) if x == " "]
</code></pre>
|
python|loops|space
| 5 |
1,906,237 | 73,246,201 |
questions about filter function in python
|
<pre><code>def empty(s):
return s and s.strip()
print(list(filter(empty,['A','B',' C '])))
</code></pre>
<p>Operation results :['A', 'B', ' C ']
I was so confused about " C "
In my opinion: s.strip() cause to delete space of the " C " and return "C",function will be returned false,and filter will eliminate it.
so the result should be ['A','B'] ?</p>
<p>my English is not well,I'm tring to tell confusion clear.</p>
|
<p>Switch to '==' instead of 'and' because currently you just check if both s and its trimmed version are non empty:</p>
<pre><code>def empty(s):
return s == s.strip()
</code></pre>
<p>Output: ['A', 'B']</p>
|
python
| 0 |
1,906,238 | 73,403,652 |
python program that count modified binary digits by using regular expression
|
<p>I want to write a program in python, by using regular expression, that can count n numbers of digits (modified binary numbers) from a file that contain binary number
for example want to count 5 digits numbers which start from 1 and end with 0, so the number will be 10000, 10010, 10100, 10110, 11000, 11010, 11100, 11110, (this is modified binary numbers)
for example if I want to count 4 digits binary number which is start with 1 and end with 1,
what I am doing is (for example/to show you, instead of file I am using a binary string)</p>
<pre><code>
a_string = '011010010111001101101111011011010110110101110011010000110010010111000100100110110101101111011011110111011001101100011011010111011001101000011001001101100011100010010110110011111011001110001001011011'
s_0 = a_string.count('1000')
s_1 = a_string.count('1010')
s_2 = a_string.count('1100')
s_3 = a_string.count('1110')
print(1000, s_0, '\n', 1010, s_1, '\n', 1100, s_2, '\n', 1110, s_3)
</code></pre>
<p>result =</p>
<p>1000 = 7, 1010 = 7, 1100 = 13, 1110 = 11.
Please note, want to count each binary number separately</p>
|
<p>With your method you are including overlapping sequences in the total count. For instance, <code>a_string[9:13]</code> and <code>a_string[10:14]</code> both contain a 4-digit sequence starting with <code>1</code> and ending with <code>0</code>.</p>
<p>A regex may be useful if you wanted to exclude overlaps:</p>
<pre><code>#this will output 26, while the single count() calls would sum up 38
pat=r'1\d{2}0'
len(re.findall(pat,a_string))
</code></pre>
|
python|string|count|binary
| 0 |
1,906,239 | 31,644,154 |
Unicode into iterable list
|
<p>I'm having trouble using a list that is represented in unicode. I've tried looking at other questions and the json.dumps() function shows a u'string' but it isn't the case for me. I can't iterate over the list because python sees the whole thing as a string and gives me individual chars. Here is some code.</p>
<pre><code>print flist
print type(flist)
['a', 'b', 'c']
<type 'unicode'>
myjson = json.dumps(flist)
print myjson
print type(myjson)
"['a', 'b', 'c']"
<type 'str'>
</code></pre>
<p>Shouldn't it be? : </p>
<pre><code>[u'a', u'b', u'c']
</code></pre>
|
<p>Try ast.literal_eval</p>
<pre><code>import ast
ast.literal_eval(flist.decode())
</code></pre>
|
python|json
| 1 |
1,906,240 | 15,861,161 |
Pythonic way for checking if value exists in dictionary of dictionaries and taking corresponding actions
|
<p>I have created a dictionary of dictionaries as:</p>
<pre><code>from collections import defaultdict
d = defaultdict(dict)
</code></pre>
<p>Now I have some strings (let us call this set <code>A</code>) which have a dictionary of strings (as key) and integers (as value) corresponding to it. So the above data structure models this data completely. </p>
<p>Now I want to check if a string corresponding to a key in <code>A</code> exists in the dictionary. If it does not exist I want to add it and make its counter <code>1</code>. If it already exists, I want to increment the counter.</p>
<p>Is there is pythonic way to do this?</p>
|
<p>If you have the key to the nested <code>dict</code>, you can use a simple <code>in</code> test:</p>
<pre><code>if somestring in d[key]:
d[key][somestring] += 1
else:
d[key][somestring] = 1
</code></pre>
<p>but you could use a <a href="http://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a> instead:</p>
<pre><code>from collections import defaultdict, Counter
d = defaultdict(Counter)
d[key][somestring] += 1
</code></pre>
<p>Like a <code>defaultdict</code>, a <code>Counter</code> provides a default value for missing keys, defaulting to <code>0</code>.</p>
<p>Counters have other benefits; instead of looping over a set of strings and manually increasing the counter for those one by one, pass the whole sequence to the <code>.update()</code> method for the appropriate counter:</p>
<pre><code>d[key].update(sequence_of_strings)
</code></pre>
<p>and the <code>Counter</code> will count them all for you.</p>
<p>The <code>Counter</code> class is what other languages might call a Multi-Set or Bag type. They support interesting comparison and arithmetic operations too, do make sure you read the documentation for the type.</p>
|
python
| 4 |
1,906,241 | 15,843,419 |
python checking if coordinates already exist in list
|
<p>This work is for an assignment. I am working with a 2d array and so far I have found a path that I want to take through the array. There are other paths in the array and I want to be able to go through them as well but I cannot reuse any paths. My array looks like:</p>
<pre><code>0,2,4,1,6,0,0
2,0,0,0,5,0,0
4,0,0,0,5,5,0
1,0,0,0,1,1,0
6,5,0,1,0,5,5
0,0,5,1,5,0,0
0,0,0,0,5,0,0
</code></pre>
<p>My code for finding nearby neighbours is:</p>
<pre><code>def check_neighbours(Alist, node):
nodes = []
for i in range(0,2):
for j in range(0,2):
x = node[0]+i
y = node[1]+j
if x>=0 and y>=0 and (i!=0 or j!=0) and Alist[x][y]>0:
nodes.append([x, y])
</code></pre>
<p>I am appending each visited coordinate x,y to a list which builds up the full path taken. Here is an example of the output: </p>
<pre><code>inside pathing function
path taken is ['[0, 1]', '[0, 2]', '[0, 3]', '[0, 4]', '[1, 4]', '[2, 4]', '[2, 5]', '[3, 5]', '[4, 5]', '[4, 6]']
</code></pre>
<p>Because of the way I am searching for neighbours (having x and y separated) I cannot think of a way of testing whether or not the current coordinate that is built up is already located inside of the list. I think that the code would fit in between the following two lines: </p>
<pre><code>if x>=0 and y>=0 and (i!=0 or j!=0) and Alist[x][y]>0:
nodes.append([x, y])
</code></pre>
|
<p>What about</p>
<pre><code>nodes = []
nodes.append([1,1])
nodes.append([2,2])
nodes.append([3,3])
[1,1] in nodes
# True
[1,3] in nodes
# False
</code></pre>
<p>I'm not really clear on your question, so this may be off.</p>
<p>That being said, since, in order to be added to the <code>nodes</code> list, it has to be either one column to the right, one below, or both, of the previous node. And since you're only considering nodes to the right and below (<code>range(0,2)</code>), you can never get duplicates in your list.</p>
|
python|list|multidimensional-array
| 0 |
1,906,242 | 59,750,959 |
how to use the sep parameter in the print function correctly
|
<p>I have been experimenting with building dictionaries in python. Please consider the following code:</p>
<pre><code>brad_pitt = {
'name': ['brad pitt'],
'profession': ['actor'],
'birthday': ['18.12.1963'],
'sign': ['sagittarius'],
'birthplace': ['shawnee / oklahoma (usa)'],
'nationality': ['usa'],
'height': ['182 cm'],
'weight': ['76 kg'],
'marital status': ['married'],
'sex': ['male'],
'ex-partner': ['gwyneth paltrow', 'jennifer aniston', 'angelina jolie'],
'eye color': ['blue'],
}
julia_roberts = {
'name': ['julia roberts'],
'profession': ['actor'],
'birthday': ['28.10.1967'],
'sign': ['scorpion'],
'birthplace': ['atlanta / georgia (usa)'],
'nationality': ['usa'],
'height': ['174 cm'],
'weight': ['57 kg'],
'marital status': ['married'],
'sex': ['female'],
'ex-partner': ['liam neeson'],
'eye color': ['brown'],
}
george_clooney = {
'name': ['george clooney'],
'profession': ['actor'],
'birthday': ['06.05.1961'],
'sign': ['taurus'],
'birthplace': ['lexington / kentucky (usa)'],
'nationality': ['usa'],
'height': ['180 cm'],
'weight': ['74 kg'],
'marital status': ['married'],
'sex': ['male'],
'ex-partner': ['naomi campbell', 'elle macpherson', 'renée zellweger', 'amal clooney'],
'eye color': ['brown'],
}
people = [brad_pitt, julia_roberts, george_clooney]
for person in people:
for key, value in person.items():
if len(value) > 1:
print(f"{key.title()}: ", end="")
for partner in value:
print(f"{partner}".title(), sep=',', end="")
print()
else:
print(f"{key.title()}: {value[0].title()}")
print()
</code></pre>
<p>I expected the ex-partners to be separated by a comma...</p>
<p>I don't see the mistake in my print statement.</p>
<p>I used the optional parameter sep to separate the different entries from the list.</p>
|
<p><code>sep</code> is for passing multiple arguments to <code>print</code>. Rather set <code>end=","</code>.</p>
<p>Better yet, just do this:</p>
<pre><code>for key, value in person.items():
print(f"{key.title()}: {','.join(v.title() for v in value)}")
</code></pre>
|
python|function|printing|parameters|separator
| 1 |
1,906,243 | 59,694,223 |
Directory compression in python
|
<p>I will try to explain it on example. </p>
<pre><code>abc
├── test
├── dir1
├── dir2
├── not_for_zipping.txt
</code></pre>
<p><strong>I want to compress all directories in <em>test</em> dir (in this example it is <em>dir1</em> and <em>dir2</em>)</strong>
Right now I made it like this:</p>
<pre><code> directory = dlg.lineEdit_zipfile_path2.text() // this should be path to test dir. (.../abc/test/)
arr = os.listdir(directory)
for item in arr:
allfiles2zip = directory + item
try:
shutil.make_archive(item,'zip', + allfiles2zip)
except OSError:
pass
</code></pre>
<p>it looks like it is working but all directories (<em>dir1</em> and <em>dir2</em>) are compressed to: .../abc/<strong><em>here</em></strong></p>
<pre><code>abc
├── dit1.zip
├── dir2.zip
├── test
├── dir1
├── dir2
├── not_for_zipping.txt
</code></pre>
<p>but I would like to receive those files in selected path (directory) ...abc/test/<strong><em>here</em></strong></p>
<pre><code>abc
├── test
├── dir1
├── dir2
├── not_for_zipping.txt
├── dir1.zip
├── dir2.zip
</code></pre>
<p>Do you have any idea how can I change it ?
By the way, do you have any better way for this case ?</p>
|
<p>You can use path in file name</p>
<pre><code>make_archive('test/' + item, 'zip', ...)
</code></pre>
<p>Eventually you can change folder before compressing</p>
<pre><code>old_folder = os.getcwd()
os.chdir('test')
shutil.make_archive(item, 'zip', ...)
os.chdir(old_folder)
</code></pre>
|
python|zip|compression|shutil
| 0 |
1,906,244 | 49,207,097 |
Counting specific words in a sentence
|
<p>I am currently trying to solve this homework question.</p>
<p>My task is to implement a function that returns a vector of word counts in a given text. I am required to split the text into words then use <code>NLTK's</code> tokeniser to tokenise each sentence.</p>
<p>This is the code I have so far:</p>
<pre><code>import nltk
import collections
nltk.download('punkt')
nltk.download('gutenberg')
nltk.download('brown')
def word_counts(text, words):
"""Return a vector that represents the counts of specific words in the text
>>> word_counts("Here is sentence one. Here is sentence two.", ['Here', 'two', 'three'])
[2, 1, 0]
>>> emma = nltk.corpus.gutenberg.raw('austen-emma.txt')
>>> word_counts(emma, ['the', 'a'])
[4842, 3001]
"""
from nltk.tokenize import TweetTokenizer
text = nltk.sent_tokenize(text)
words = nltk.sent_tokenize(words)
wordList = []
for sen in text, words:
for word in nltk.word_tokenize(sen):
wordList.append(text, words).split(word)
counter = TweetTokenizer(wordList)
return counter
</code></pre>
<p>There are two doctests that should give the result of:
[2, 1, 0] and [4842, 3001]</p>
<p>This is the error message I am getting from my code
<a href="https://i.stack.imgur.com/iSkpe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iSkpe.png" alt="enter image description here"></a></p>
<p>I've spent all day trying to tackle this and I feel I'm getting close but I don't know what I'm doing wrong, the script is giving me an error every time.</p>
<p>Any help will be very appreciated.
Thank you.</p>
|
<p>This is how I would use nltk to get to the result your homework wants:</p>
<pre><code>import nltk
import collections
from nltk.tokenize import TweetTokenizer
# nltk.download('punkt')
# nltk.download('gutenberg')
# nltk.download('brown')
def word_counts(text, words):
"""Return a vector that represents the counts of specific words in the text
word_counts("Here is one. Here is two.", ['Here', 'two', 'three'])
[2, 1, 0]
emma = nltk.corpus.gutenberg.raw('austen-emma.txt')
word_counts(emma, ['the', 'a'])
[4842, 3001]
"""
textTok = nltk.word_tokenize(text)
counts = nltk.FreqDist(textTok) # this counts ALL word occurences
return [counts[x] for x in words] # this returns what was counted for *words
r1 = word_counts("Here is one. Here is two.", ['Here', 'two', 'three'])
print(r1) # [2, 1, 0]
emma = nltk.corpus.gutenberg.raw('austen-emma.txt')
r2 = word_counts(emma, ['the', 'a'])
print(r2) # [4842, 3001]
</code></pre>
<p>Your code does multiple things that look just wrong:</p>
<blockquote>
<pre><code>for sen in text, words:
for word in nltk.word_tokenize(sen):
wordList.append(text, words).split(word)
</code></pre>
</blockquote>
<ul>
<li><code>sent_tokenize()</code> takes a string and returns a list of sentences from it - you store the results in 2 variables <code>text, words</code> and then you try to iterate over tuple of them? <code>words</code> is not a text with sentences to begin, this makes not much sense to me</li>
<li><code>wordList</code> is a list, if you use the <code>.append()</code> on it, <code>append()</code> returns <code>None</code>. <code>None</code>has no <code>.split()</code> function.</li>
</ul>
|
python|vector|nltk
| 4 |
1,906,245 | 49,278,571 |
Python, Machine Learning: Are there any API that can split dataset and shuffle?
|
<p>I have a dataset with 10000 samples, and 4 classes (0, 1, 2, 3) label.</p>
<pre><code>>>>data.shape
(10000, 250)
>>>label.shape
(10000,)
</code></pre>
<p>and, I wonder are there any API that could split the data into training and test data and shuffle?</p>
<p>for example:</p>
<pre><code>(training_data, training_label, test_data, test_label) = split_shuffle(data, label, 80) # 80 means 80% training, 20% test
</code></pre>
<p>What is the most efficient way to achieve such functions?</p>
<p>Further, what if we want 5-fold (straight) cross validation data? </p>
|
<p>SKLearn's <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="nofollow noreferrer">train_test_split</a> is what you're looking for, using the following:</p>
<pre><code>from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
</code></pre>
|
python|numpy|tensorflow|machine-learning|deep-learning
| 3 |
1,906,246 | 25,219,688 |
How to output the twilio sms logs in a csv file using Python API
|
<p>I am using this script for downloading the sms log file from the Twilio.</p>
<p><a href="https://github.com/asplunker/twilio-app/blob/master/bin/get_sms_logs.py" rel="nofollow">https://github.com/asplunker/twilio-app/blob/master/bin/get_sms_logs.py</a></p>
<p>In the first run its downloading the file properly but in the second run it throws "<code>index out of range error "</code></p>
<p>So the error is suspected in the function :</p>
<pre><code>def write_records():
# avoid duplicates
data = []
if os.path.exists(LOG_FILE):
with codecs.open(LOG_FILE) as d:
file_data = d.readlines()
for line in file_data:
print line
date = line.split(',')[1]
if date == LAST_ENTRY:
data.append(date)
with codecs.open(LOG_FILE, 'a') as f:
for record in reversed(RECORDS):
if not record.split(',')[1] in data:
f.write(record)
f.write('\n')
</code></pre>
<p>I am not sure if the output csv file in the first run doesn't specify each record in a single line.</p>
<p>Any pointers would be greatly appreciated.</p>
|
<p>I would add some error handling to find the state of objects at the time of failure.</p>
<p>Have you ever used try/except?
<a href="https://docs.python.org/2/tutorial/errors.html" rel="nofollow">https://docs.python.org/2/tutorial/errors.html</a></p>
<p>Basically you could set it up like this</p>
<pre><code>def write_records():
# avoid duplicates
try:
data = []
if os.path.exists(LOG_FILE):
with codecs.open(LOG_FILE) as d:
file_data = d.readlines()
for line in file_data:
print line
date = line.split(',')[1]
if date == LAST_ENTRY:
data.append(date)
with codecs.open(LOG_FILE, 'a') as f:
for record in reversed(RECORDS):
if not record.split(',')[1] in data:
f.write(record)
f.write('\n')
except IndexError:
#log variables here and examine the issue closely
</code></pre>
|
python|csv|twilio
| 1 |
1,906,247 | 71,014,894 |
How to disable some weights in keras?
|
<p>Imagine I am trying to fit a model the following way:</p>
<pre><code>import tensorflow as tf
x_in=tf.keras.layers.Input(shape=n)
x_out = tf.keras.layers.Dense(m, use_bias=False)(x_in)
model = tf.keras.Model(inputs=x_in, outputs=x_out)
</code></pre>
<p>Now the problem is that this will create nxm weights - in my model, however, I want most of the weights to be zero (in fact, only m weights are non-zero); So far, I implemented it by a custom weight constraint function; This however, proved to be extremely slow as the weights that I want to be 0 are nevertheless updated in every iteration and then manually set to 0 which takes a lot of time;</p>
<p>Is there a better way to do it? So a way to say something like "Disable weight w[i,j] whenever i!=(j+1)" such that only these m weights that are not disabled will really be updated in every iteration?</p>
|
<p>Could the following applied in suitable format solve your problem:</p>
<pre><code>import tensorflow as tf
import numpy as np
n=1
m=1
x_in=tf.keras.layers.Input(shape=n)
x_out = tf.keras.layers.Dense(m, use_bias=False,trainable=True)(x_in)
x_out_disabledweights = tf.keras.layers.Dense(m, use_bias=False,trainable=False)(x_in)
model_A = tf.keras.Model(inputs=x_in, outputs=x_out)
model_B = tf.keras.Model(inputs=x_in, outputs=x_out_disabledweights)
print(model_A.summary())
print(model_B.summary())
#by following the idea above, you are able to freeze the weights you want...
weights_before_update=model_B.get_weights()
#fix the weigth to desired value e.g. 0.12345
weights_before_update[0][0][0]=0.12345
#and set the weigths to the model:
model_B.set_weights(weights_before_update)
#and this way you can verify the weight has been updated...
weights_after_update=model_B.get_weights()
print("The weights after manual update...")
print(weights_after_update)
print("And the result of model with test input of one...")
test_result=model_B(np.ones(1))
print(test_result)
</code></pre>
<p>...please note the possibility to handle trainability of selected layers. You can design several different layers ... having individual characteristics of weights and their features.</p>
|
python|tensorflow|keras
| 0 |
1,906,248 | 6,289,080 |
App Engine: submitting form data to Google Spreadsheet
|
<p>We'd like to duplicate the Google Spreadsheet Form Wizard functionality within our App Engine application. The rational for this is that Google forms look ugly and the form wizard apparently does not provide enough hooks to make layout better.</p>
<p>Do you know any examples how to integrate Google Spreadsheet GData API in App Engine, so that the target spreadsheet and authentication tokens would be persistently stored? The spreadsheet is on our Google Apps domain, behind our own login and it should not be exposed to the site user in any point.</p>
<p>So we were thinking</p>
<p>1) Extract spreadsheet id and authentication token(s) from Google Spreadsheet API (how)</p>
<p>2) Store these in App Engine data store through App Engine console </p>
<p>3) Create a Django form and let our front-end developers to style it </p>
<p>5) Django form handler submits the results into the spreadsheet directly using GData API</p>
|
<p>Everything you write makes sense, but where's the question?
You can put python gdata client library into your GAE project.
You can expose the spreadsheet (make it accessible from the outer world), but leave it private, so nobody would be able to manually access it, and authenticate your GAE Django app. Trivially - with plain auth behind SSL, byt better with OAuth, see gdata docs: <a href="http://code.google.com/apis/documents/docs/3.0/developers_guide_python.html" rel="nofollow">http://code.google.com/apis/documents/docs/3.0/developers_guide_python.html</a></p>
<p>In order to get information for you spreadsheet - well, first manually create it, then from python code load documents list, it should have a single entry, dump its ID, and you will be able accessing it like 'spreadsheet:ID' from every method that expects Entry OR ID</p>
<p>You should also be (probably) able accessing it by URL passed to the same methods, bacuse I saw method parameter named entry_or_id_or_url.</p>
|
python|django|google-app-engine|gdata|google-spreadsheet-api
| 1 |
1,906,249 | 67,898,607 |
Installing pandas and pycryptodome dependencies in Dockerfile for python alpine image
|
<p>I am not able to install pandas and pycryptodome dependencies in the requirements.txt while taking the python:3.8-alpine docker image.</p>
<p>This is the Dockerfile:</p>
<pre><code>FROM python:3.9-alpine
WORKDIR /app
COPY database /app/database
COPY resolvers /app/resolvers
COPY schemas /app/schemas
COPY app.py /app/app.py
COPY requirements.txt /app/requirements.txt
ARG user=user
ARG group=group
ARG uid=6000
ARG gid=6000
RUN apk update
RUN addgroup -g ${gid} ${group} \
&& adduser -h /app -u ${uid} -G ${group} -s /bin/sh -D ${user}
RUN chown -R user:group /app
RUN pip3 install --upgrade pip
RUN apt-get update
RUN pip3 install -U --no-cache-dir -r /app/requirements.txt
USER user
EXPOSE 12000
CMD ["python","app.py"]
</code></pre>
<p>This is the requirements.txt file:</p>
<pre><code>graphene==2.1.6
Flask-GraphQL==2.0.0
Flask==1.1.1
python-dateutil==2.8.0
pandas==0.24.1
pytz==2018.5
pycryptodome==3.10.1
</code></pre>
<p>Ad it's giving the error like:</p>
<pre><code> ERROR: Command errored out with exit status 1:
command: /usr/local/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-_mil4d71/pandas_ce1b9432f9d34cbb838980507a5275a1/setup.py'"'"'; __file__='"'"'/tmp/pip-install-_mil4d71/pandas_ce1b9432f9d34cbb838980507a5275a1/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-mrmagy45
cwd: /tmp/pip-install-_mil4d71/pandas_ce1b9432f9d34cbb838980507a5275a1/
Complete output (18 lines):
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 344, in get_provider
module = sys.modules[moduleOrReq]
KeyError: 'numpy'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-install-_mil4d71/pandas_ce1b9432f9d34cbb838980507a5275a1/setup.py", line 732, in <module>
ext_modules=maybe_cythonize(extensions, compiler_directives=directives),
File "/tmp/pip-install-_mil4d71/pandas_ce1b9432f9d34cbb838980507a5275a1/setup.py", line 475, in maybe_cythonize
numpy_incl = pkg_resources.resource_filename('numpy', 'core/include')
File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 1130, in resource_filename
return get_provider(package_or_requirement).get_resource_filename(
File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 346, in get_provider
__import__(moduleOrReq)
ModuleNotFoundError: No module named 'numpy'
----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/81/fd/b1f17f7dc914047cd1df9d6813b944ee446973baafe8106e4458bfb68884/pandas-0.24.1.tar.gz#sha256=435821cb2501eabbcee7e83614bd710940dc0cf28b5afbc4bdb816c31cec71af (from https://pypi.org/simple/pandas/) (requires-python:>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
ERROR: Could not find a version that satisfies the requirement pandas==0.24.1 (from versions: 0.1, 0.2b0, 0.2b1, 0.2, 0.3.0b0, 0.3.0b2, 0.3.0, 0.4.0, 0.4.1, 0.4.2, 0.4.3, 0.5.0, 0.6.0, 0.6.1, 0.7.0rc1, 0.7.0, 0.7.1, 0.7.2, 0.7.3, 0.8.0rc1, 0.8.0rc2, 0.8.0, 0.8.1, 0.9.0, 0.9.1, 0.10.0, 0.10.1, 0.11.0, 0.12.0, 0.13.0, 0.13.1, 0.14.0, 0.14.1, 0.15.0, 0.15.1, 0.15.2, 0.16.0, 0.16.1, 0.16.2, 0.17.0, 0.17.1, 0.18.0, 0.18.1, 0.19.0rc1, 0.19.0, 0.19.1, 0.19.2, 0.20.0rc1, 0.20.0, 0.20.1, 0.20.2, 0.20.3, 0.21.0rc1, 0.21.0, 0.21.1, 0.22.0, 0.23.0rc2, 0.23.0, 0.23.1, 0.23.2, 0.23.3, 0.23.4, 0.24.0rc1, 0.24.0, 0.24.1, 0.24.2, 0.25.0rc0, 0.25.0, 0.25.1, 0.25.2, 0.25.3, 1.0.0rc0, 1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.0.5, 1.1.0rc0, 1.1.0, 1.1.1, 1.1.2, 1.1.3, 1.1.4, 1.1.5, 1.2.0rc0, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.2.4)
ERROR: No matching distribution found for pandas==0.24.1
The command '/bin/sh -c pip3 install -U --no-cache-dir -r /app/requirements.txt' returned a non-zero code: 1
</code></pre>
|
<p>If you don't have an excellent reason to use an Alpine image, don't. (See e.g. <a href="https://pythonspeed.com/articles/alpine-docker-python/" rel="nofollow noreferrer">Using Alpine can make Python Docker builds 50× slower</a>.)</p>
<p>With e.g. <code>slim-buster</code> you can use prebuilt wheels for Numpy and Pandas.</p>
<pre><code>FROM python:3.9-slim-buster
WORKDIR /app
COPY database /app/database
COPY resolvers /app/resolvers
COPY schemas /app/schemas
COPY app.py /app/app.py
COPY requirements.txt /app/requirements.txt
ARG user=user
ARG group=group
ARG uid=6000
ARG gid=6000
RUN addgroup -g ${gid} ${group} && adduser -h /app -u ${uid} -G ${group} -s /bin/sh -D ${user}
RUN chown -R user:group /app
RUN python -m pip install --upgrade pip setuptools wheel
RUN python -m pip install -U --no-cache-dir -r /app/requirements.txt
USER user
EXPOSE 12000
CMD ["python","app.py"]
</code></pre>
|
python|docker|dockerfile|alpine-linux|docker-image
| 1 |
1,906,250 | 30,736,198 |
Disabling tkinter ttk scale widget
|
<p>I am trying to disable all of the (ttk) widgets in a frame, but it appears that the scale widget is giving me some trouble, as it throws the following exception: </p>
<blockquote>
<p>_tkinter.TclError: unknown option "-state"</p>
</blockquote>
<p>Some relevant code:</p>
<pre><code>import tkinter as tk
from tkinter import ttk
def disable_widgets(parent):
for child in parent.winfo_children():
child.config(state = 'disabled')
root = tk.Tk()
# Frame full of widgets to toggle
frame_of_widgets = ttk.Frame(root)
frame_of_widgets.pack()
# Button to be disabled
button_to_disable = ttk.Button(frame_of_widgets)
button_to_disable.pack()
# Entry to be disabled
entry_to_disable = ttk.Entry(frame_of_widgets)
entry_to_disable.pack()
# Scale to be disabled
scale_to_disable = ttk.Scale(frame_of_widgets)
scale_to_disable.pack()
# Button that disables widgets in frame
disable_button = ttk.Button(root,text="Disable",command= lambda: disable_widgets(frame_of_widgets))
disable_button.pack()
root.mainloop()
</code></pre>
<p>It works for the button and entry, but not for the scale. I thought one of the benefits of ttk was making widgets more uniform with common methods and attributes, so I am guessing perhaps I am accessing all three of these widgets incorrectly?</p>
|
<p>For ttk widgets you use the <code>state</code> method. The <code>state</code> method for buttons and entry widgets are just a convenience function to mimic the standard button and entry widgets.</p>
<p>You can rewrite your function like this:</p>
<pre><code>def disable_widgets(parent):
for child in parent.winfo_children():
child.state(["disabled"])
</code></pre>
<p>ttk states are mentioned in the ttk documentation here (though the description borders on useless): <a href="https://docs.python.org/3.1/library/tkinter.ttk.html#widget-states" rel="noreferrer">https://docs.python.org/3.1/library/tkinter.ttk.html#widget-states</a></p>
|
python|user-interface|tkinter|ttk
| 9 |
1,906,251 | 30,434,106 |
Is there a more efficient way to satisfy project dependencies than pip?
|
<p>I work on a system and the hosting guys don't want to use an install script that uses pip. Now we have a large pip requirements file that install the dependencies. Is there any other way to do it than using pip? Can it be done using <code>yum</code> or <code>apt-get</code> ? We are using Linux. </p>
|
<p>For god's sake, please do not fall back to using the distribution's package manager just because your hosting guys do not understand what <code>pip</code>+<code>virtualenv</code> is good for.</p>
<p>Python packages in Linux distribution repositories are often outdated and may come with quirks that other Python package authors did not plan for. This is especially true for Python packages with compiled code. If a documentation tells you that a certain dependency should be obtained directly from PyPI via pip, then you better follow that requirement. Convince your hosting guys to use the right tools, namely <code>pip</code> combined with <code>virtualenv</code>. The latter will create an isolated environment and make sure that the system will stay clean (really, nobody needs to do a <code>sudo pip install</code>, which probably is the thing your hosting guys are afraid of).</p>
|
python|linux|django|dependencies|pip
| 2 |
1,906,252 | 72,415,920 |
Python tkinter lib not installing on Manjaro KDE
|
<p>None of my lib files are active they all have an icon next to them that looks like a txt file with a question mark.</p>
<p>I have tried using Tkinter and Turtle and both are having the same problems. I looked at my lib file in PyCharm to find that they are not enabled.</p>
<pre><code>Traceback (most recent call last):
File "/home/crystal/PycharmProjects/practice/pong.py", line 1, in <module>
import turtle
File "/usr/lib/python3.10/turtle.py", line 107, in <module>
import tkinter as TK
File "/usr/lib/python3.10/tkinter/__init__.py", line 37, in <module>
import _tkinter # If this fails your Python may not be configured for Tk
ImportError: libtk8.6.so: cannot open shared object file: No such file or directory
Process finished with exit code 1
</code></pre>
<p>I have tried using sudo install and pip install using all upper, all lower, a combo, etc. I have double checked my python3 install and it says: Python 3.10.4.<br />
I would like to be able to activate all of my lib files and not just Tkinter and Turtle.</p>
|
<p>According to Arch docs, <code>tk</code> should be installed (via <code>pacman</code>, or Manjaro package manager)</p>
<p><a href="https://wiki.archlinux.org/title/Python#Widget_bindings" rel="nofollow noreferrer">https://wiki.archlinux.org/title/Python#Widget_bindings</a></p>
<p>You can see in the package list, it installs the file mentioned in the error</p>
<p><a href="https://archlinux.org/packages/extra/x86_64/tk/" rel="nofollow noreferrer">https://archlinux.org/packages/extra/x86_64/tk/</a></p>
<p>It's unclear what other libraries you're referring to, but not all Python extensions/modules require external C libraries</p>
|
python|python-3.x|tkinter|manjaro
| 0 |
1,906,253 | 3,691,655 |
Embedding Python in an iPhone app
|
<p>So it's a new millennium; Apple has waved their hand; it's now legal to include a Python interpreter in an iPhone (App Store) app.</p>
<p>How does one go about doing this? All the existing discussion (unsurprisingly) refers to jailbreaking. (Older question: <a href="https://stackoverflow.com/questions/43315/can-i-write-native-iphone-apps-using-python">Can I write native iPhone apps using Python</a>)</p>
<p>My goal here isn't to write a PyObjC app, but to write a regular ObjC app that runs Python as an embedded library. The Python code will then call back to native Cocoa code. It's the "control logic is Python code" pattern.</p>
<p>Is there a guide to getting Python built in XCode, so that my iPhone app can link it? Preferably a stripped-down Python, since I won't need 90% of the standard library.</p>
<p>I can probably figure out the threading and Python-extension API; I've done that on MacOS. But only using command-line compilers, not XCode.</p>
|
<p>It doesn't really matter how you build Python -- you don't need to build it in Xcode, for example -- but what does matter is the product of that build.</p>
<p>Namely, you are going to need to build something like libPython.a that can be statically linked into your application. Once you have a .a, that can be added to the Xcode project for your application(s) and, from there, it'll be linked and signed just like the rest of your app.</p>
<p>IIRC (it has been a while since I've built python by hand) the out-of-the-box python will build a libPython.a (and a bunch of other libraries), if you configure it correctly.</p>
<p>Of course, your second issue is going to be cross-compiling python for ARM from your <em>86</em> box. Python is an autoconf based project and autoconf is a pain in the butt for cross-compilation.</p>
<p>As you correctly state, making it small will be critical.</p>
<p>Not surprising, either, is that you aren't the first person to want to do this, but not for iOS. Python has been squeezed into devices much less capable than those that run iOS. I found a thread with a bunch of links when googling about; it <a href="http://bytes.com/topic/python/answers/512131-python-embedded-systems" rel="noreferrer">might be useful</a>.</p>
<p>Also, you might want to join the <a href="https://lists.sourceforge.net/lists/listinfo/pyobjc-dev" rel="noreferrer">pyobjc-dev</a> list. While you aren't targeting a PyObjC based application (which, btw, is a good idea -- PyObjC has a long way to go before it'll be iOS friendly), the PyObjC community has been discussing this and Ronald, of anyone, is probably the most knowledgeable person in this particular area. Note that PyObjC will have to solve the embedded Python on iOS problem prior to porting PyObjC. Their prerequisite is your requirement, as it were.</p>
|
iphone|python|xcode
| 30 |
1,906,254 | 50,355,008 |
NameError: name 'ttk' is not defined
|
<p>trying to create a combobox, follow a tutorial on youtube from 2016 on making a currency calculator for my school work.</p>
<pre><code>box = ttk.Combobox(LeftMainFrame, textvariable=value0, state='readonly',font=('arial', 20, 'bold'),width=20)
box['values'] = (' ', 'USA', 'Kenya', 'Brazil', 'Canada', 'India', 'Phillappines')
box.current(0)
box.grid(row=4, column=2)
</code></pre>
<p>keeps saying ttk is not defined.</p>
<p>I know nothing about python
I am also using visual studio </p>
|
<p>From <a href="https://docs.python.org/2/library/ttk.html#using-ttk" rel="nofollow noreferrer">python's ttk doc (python 2)</a>, or <a href="https://docs.python.org/3.6/library/tkinter.ttk.html?highlight=ttk" rel="nofollow noreferrer">same for python 3</a>:</p>
<blockquote>
<p>To start using Ttk, import its module:</p>
</blockquote>
<pre><code>import ttk
</code></pre>
<blockquote>
<p>But code like this:</p>
</blockquote>
<pre><code>from Tkinter import *
</code></pre>
<blockquote>
<p>may optionally want to use this:</p>
</blockquote>
<pre><code>from Tkinter import *
from ttk import *
</code></pre>
<blockquote>
<p>And then several ttk widgets (Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale and Scrollbar) will automatically substitute for the Tk widgets.</p>
</blockquote>
<p>So, depending on your environment, you may have to import ttk:</p>
<pre><code>import ttk
</code></pre>
|
python|nameerror|ttk
| 0 |
1,906,255 | 50,619,495 |
How to generate a regular time series from date X to date Y with intervals of Z units?
|
<p>I am new to Python (from Matlab) and having some trouble with a simple task:</p>
<p>How can I create a regular time series from date X to date Y with intervals of Z units?</p>
<p>E.g. from 1st January 2013 to 31st January 2013 every 10 minutes</p>
<p>In Matlab:</p>
<pre><code>t = datenum(2013,1,1):datenum(0,0,0,0,10,0):datenum(2013,12,31);
</code></pre>
|
<p>If you can use <strong>pandas</strong> then use <strong><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html?highlight=date_range" rel="nofollow noreferrer">pd.date_range</a></strong></p>
<p><strong>Ex:</strong></p>
<pre><code>import pandas as pd
d = pd.date_range(start='2013/1/1', end='2013/12/31', freq="10min")
</code></pre>
|
python|datetime
| 0 |
1,906,256 | 45,201,195 |
Reading numpy matrix in batches in Tensorflow
|
<p>I am trying to run some regression models on GPU. While I get a very low GPU utilization upto 20%. After going through the code, </p>
<pre><code> for i in range(epochs):
rand_index = np.random.choice(args.train_pr,
size=args.batch_size)
rand_x = X_train[rand_index]
rand_y = Y_train[rand_index]
</code></pre>
<p>I use these three lines for selecting a random batch for each iteration. So, I wanted to ask when the training is going on, can I ready up one more batch for the next iteration?</p>
<p>I am working on a regression problem and not a classification problem. I have already seen threading in Tensorflow but found the examples only for images and there's no example for a big matrix of size 100000X1000 which is used for training. </p>
|
<p>You have a large numpy array that lies on the host memory. You want to be able to process it in parallel on the CPU and send batches to the device.</p>
<p>Since TF 1.4, the best way to do it is to use <code>tf.data.Dataset</code>, and particularly <code>tf.data.Dataset.from_tensor_slices</code>. However, as <a href="https://www.tensorflow.org/guide/datasets#consuming_numpy_arrays" rel="nofollow noreferrer">the documentation</a> points out, you should probably <em>not</em> provide your numpy arrays as arguments to this function, because it will end up being copied to device memory. What you should do instead is to use placeholders. The example given in the doc is pretty self-explanatory:</p>
<pre><code>features_placeholder = tf.placeholder(features.dtype, features.shape)
labels_placeholder = tf.placeholder(labels.dtype, labels.shape)
dataset = tf.data.Dataset.from_tensor_slices((features_placeholder, labels_placeholder))
# [Other transformations on `dataset`...]
iterator = dataset.make_initializable_iterator()
sess.run(iterator.initializer, feed_dict={features_placeholder: features,
labels_placeholder: labels})
</code></pre>
<p>Further preprocessing or data augmentation can be applied to the slices using the <code>.map</code> method. To make sure that those operations happen concurrently, make sure to use tensorflow operations only and avoid wrapping python operations with <code>tf.py_func</code>.</p>
|
python|numpy|tensorflow|gpu
| 3 |
1,906,257 | 45,232,362 |
Need improvement in the while loop in python program
|
<p>with some help of from this forum (@COLDSPEED...Thanks a lot )I have been able to read the latest file created in the directory. The program is looking for the max timestamp of file creation time. But I need two improvement</p>
<p>1.But what if 2 files are created in the same time stamp?
2.I want to skip the file which is already read(in case no new file arrives) when the while loop is checking for the latest file.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import os
import time
def detect_suspects(file_path, word_list):
with open(file_path) as LogFile:
Summary = {word: [] for word in word_list}
failure = ':'
for num, line in enumerate(LogFile, start=1):
for word in word_list:
if word in line:
failure += '<li>' + line + '</li>'
return failure
while True:
files = os.listdir('.')
latest_file = max(files, key=os.path.getmtime)
Error_Suspects = ['Error', 'ERROR', 'Failed', 'Failure']
print(latest_file)
Result = detect_suspects(latest_file, Error_Suspects)
print (Result)
time.sleep(5)
</code></pre>
</div>
</div>
</p>
|
<p>To address your first question, when 2 files have the exact same timestamp, max picks one and returns it. The first string that appears in the list that is associated with the max modification time is returned. </p>
<p>For your second question, you could make a small addition to your existing code by keeping track of the previous file and previous modification time.</p>
<pre><code>Error_Suspects = ['Error', 'ERROR', 'Failed', 'Failure']
prev_file = None
prev_mtime = None
while True:
files = os.listdir('.')
latest_file = max(files, key=os.path.getmtime)
if latest_file != prev_file or (latest_file == prev_file and prev_mtime != os.path.getmtime(latest_file):
Result = detect_suspects(latest_file, Error_Suspects)
prev_file = latest_file
prev_mtime = os.path.getmtime(latest_file)
time.sleep(5)
</code></pre>
<p>In this code, the <code>if</code> condition will execute your code only if 1) your new file is different from your old file, or 2) your old and new file is the same but it was modified since the last time. </p>
|
python-2.7|loops
| 0 |
1,906,258 | 44,908,357 |
Using urllib to get the final redirect of a webpage in Python 3.5
|
<p>As in <a href="https://stackoverflow.com/questions/3556266/how-can-i-get-the-final-redirect-url-when-using-urllib2-urlopen">this post</a>, I attempt to get the final redirect of a webpage as:</p>
<pre><code>import urllib.request
response = urllib.request.urlopen(url)
response.geturl()
</code></pre>
<p>But this doesn't work as I get the "HTTPError: HTTP Error 300: Multiple Choices" error when attempting to use <code>urlopen</code>.</p>
<p>See documentation for these methods <a href="https://docs.python.org/3.5/library/urllib.request.html#module-urllib.request" rel="nofollow noreferrer">here</a>.</p>
<p><strong>EDIT:</strong></p>
<p>This problem is different than the <a href="https://stackoverflow.com/questions/32641862/python-urllib2-httperror-http-error-300-multiple-choices">Python: urllib2.HTTPError: HTTP Error 300: Multiple Choices</a> question, because they skip the error-causing pages, while I have to obtain the final destination.</p>
|
<p>As suggested by @abccd, I used the <code>requests</code> library. So I will describe the solution.</p>
<pre><code>import requests
url_base = 'something' # You need this because the redirect URL is relative.
url = url_base + 'somethingelse'
response = requests.get(url)
# Check if the request returned with the 300 error code.
if response.status_code == 300:
redirect_url = url_base + response.headers['Location'] # Get new URL.
response = requests.get(redirect_url) # Make a new request.
</code></pre>
|
python|python-3.x|python-requests|python-3.5|urllib
| 0 |
1,906,259 | 45,223,177 |
Resending data in socket
|
<p>So I'm trying to send multiple packets over and over again to my VM, but after one attempt, I get the error: </p>
<pre><code>Traceback (most recent call last):
File "SMB_Test2.py", line 157, in <module>
s.sendall(SMB_COM_NEGOTIATE)
File "C:\Python27\Lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host
</code></pre>
<p>which I presume is due to repeated malformed data being sent (on purpose), but I want to know if and how there is a way around that. I'm essentially looking to repeatedly send that SMB_COM_NEGOTIATE many times. Thanks in advance. </p>
<pre><code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((addr, port))
s.settimeout(2)
print '[*] Connected to "%s:%d".' % (addr, port)
s.sendall(SMB_COM_NEGOTIATE)
a = 0
while a != 50000:
print a
a = a + 1
s.sendall(SMB_COM_NEGOTIATE)
print '[*] Sent to "%s:%d".' % (addr, port)
</code></pre>
<p>EDIT (off Jame's suggestion) - Still jumps right to an error:</p>
<pre><code>a = 0
try:
print "The value of 'a' is %r." % a
s.connect((addr, port))
print '[*] Connected to "%s:%d".' % (addr, port)
while a != 50000:
a = a + 1
s.sendall(SMB_COM_NEGOTIATE)
print '[*] Sent to "%s:%d".' % (addr, port)
print "The value 'a' is %r." % a
except:
print "[-] An error occured!!!"
s.close()
exit()
</code></pre>
<p>Output:</p>
<pre><code>The value of 'a' is 0.
[*] Connected to "192.168.xxx.xxx:xxx".
[*] Sent to "192.168.xxx.xxx:xxx".
The value 'a' is 1.
[-] An error occured!!!
</code></pre>
<p>Also tried this (almost identical):</p>
<pre><code>a = 0
print "The value of 'a' is %r." % a
s.connect((addr, port))
print '[*] Connected to "%s:%d".' % (addr, port)
def ok():
try:
while a != 50000:
a = a + 1
s.sendall(SMB_COM_NEGOTIATE)
print '[*] Sent to "%s:%d".' % (addr, port)
print "The value 'a' is %r." % a
except:
print "[-] An error occured!!!"
sleep(0)
s.close()
</code></pre>
<p>Which had an output (not even sending anything):</p>
<pre><code>The value of 'a' is 0.
[*] Connected to "192.168.xxx.xxx:xxx".
[-] An error occurred!!!
</code></pre>
|
<p>Here is a code fragment to illustrate my comment.</p>
<pre><code>import socket
def try_connect():
"""Tries to connect and send the SMB_COM_NEGOTIATE bytes.
Returns the socket object on success and None on failure.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
try:
s.connect((addr, port))
s.sendall(SMB_COM_NEGOTIATE)
except socket.timeout as e:
# got a socket timeout
return None
except OSError as e:
# got some other socket error
return None
return s
def try_connect_n_times(n):
"""Try up to n times to connect"""
for attempt in range(n):
s = try_connect()
if s:
return s
return None
try_connect_n_times(5000)
</code></pre>
|
python|python-2.7|sockets|virtual-machine|smb
| 0 |
1,906,260 | 64,999,216 |
Django ValueError: Field 'id' expected a number but got 'S'
|
<p>Below is my models that are used in view where errors occur and error occurs in StockQuantity model particularly, when i try to filter or use get to retreive query it says expected number but got 'stringvalue'</p>
<p><strong>models.py</strong></p>
<pre><code># Item
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
discount_price = models.FloatField(blank=True, null=True)
category = models.ForeignKey(
'Category', on_delete=models.CASCADE, null=True)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
# stock_quantity = models.IntegerField(blank=True, null=True)
cover_image = models.ImageField(blank=True, null=True,
upload_to=item_cover_upload_location, default='no-product-image.jpg')
is_footwear = models.BooleanField(default=False)
upload_date = models.DateTimeField(default=timezone.now)
# StockQuantity
class StockQuantity(models.Model):
item = models.ForeignKey('Item', on_delete=models.CASCADE, null=True)
color = models.ForeignKey(
'ItemColor', on_delete=models.CASCADE)
cloth_size = models.ForeignKey(
'ClothSize', on_delete=models.CASCADE, blank=True, null=True)
footwear_size = models.ForeignKey(
'FootwearSize', on_delete=models.CASCADE, blank=True, null=True)
stock_quantity = models.IntegerField(null=True, default=10)
#OrderItem
class OrderItem(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
footwear_size = models.CharField(max_length=50, null=True)
cloth_size = models.CharField(max_length=50, null=True)
color = models.CharField(max_length=50, null=True)
ordered = models.BooleanField(default=False)
#Order
class Order(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ref_code = models.CharField(max_length=20, blank=True, null=True)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
shipping_address = models.ForeignKey(
'Address', related_name='shipping_address', on_delete=models.SET_NULL, blank=True, null=True)
billing_address = models.ForeignKey(
'Address', related_name='billing_address', on_delete=models.SET_NULL, blank=True, null=True)
payment = models.ForeignKey(
'Payment', on_delete=models.SET_NULL, blank=True, null=True)
coupon = models.ForeignKey(
'Coupon', on_delete=models.SET_NULL, blank=True, null=True)
being_delivered = models.BooleanField(default=False)
received = models.BooleanField(default=False)
requested_refund = models.BooleanField(default=False)
refund_status = models.BooleanField(default=False)
#Payment
class Payment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL, blank=True, null=True)
paypal_transaction_id = models.CharField(max_length=50)
amount = models.FloatField()
timestamp = models.DateTimeField(default=timezone.now)
# ItemColor
class ItemColor(models.Model):
item_color = models.CharField(
max_length=25, null=True, blank=True)
item = models.ForeignKey('Item', on_delete=models.CASCADE, null=True)
def __str__(self):
return self.item_color
# ClothSize
class ClothSize(models.Model):
cloth_size = models.CharField(
max_length=25, null=True, blank=True)
item = models.ForeignKey('Item', on_delete=models.CASCADE, null=True)
def __str__(self):
return self.cloth_size
# FootwearSize
class FootwearSize(models.Model):
footwear_size = models.CharField(
max_length=25, null=True, blank=True)
item = models.ForeignKey('Item', on_delete=models.CASCADE, null=True)
</code></pre>
<p>Below is my views.py and specifically the view where the error is thrown, I have placed a comment for further help to acknowledge where error occurs particularly</p>
<p><strong>Views.py</strong></p>
<pre><code># View where the error occurs
def payment_complete(request):
body = json.loads(request.body)
order = Order.objects.get(
user=request.user, ordered=False, ref_code=body['orderid'])
payment = Payment(
user=request.user,
paypal_transaction_id=body['payid'],
amount=order.get_total()
)
payment.save()
order.ordered = True
order.payment = payment
order.received = True
order.save()
order_items = order.items.all()
order_items.update(ordered=True)
for item in order_items:
if item.item.is_footwear:\
# ERROR OCCURS BELOW ---------
st = StockQuantity.objects.get(
item=item.item, color=item.color, footwear_size=str(item.footwear_size))
else:
# ERROR OCCURS BELOW ---------
st = StockQuantity.objects.get(
item=item.item, color=item.color, cloth_size=str(item.cloth_size))
if st.stock_quantity > 0:
st.stock_quantity -= item.quantity
st.save()
item.save()
item.item.save()
else:
messages.warning("Item out of stock!!")
print("Quantity " + str(st.stock_quantity))
# order_item = OrderItem.objects.get(user=request.user, ordered=True)
messages.success(request, "Order placed successfully!!")
return redirect("/")
</code></pre>
<p><strong>Traceback and Errors</strong></p>
<pre><code>Django version 3.1.1, using settings 'djecommerce.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[25/Nov/2020 11:23:42] "GET /product/dummy-item-1/ HTTP/1.1" 200 15564
[25/Nov/2020 11:23:45] "POST /add-to-cart/dummy-item-1 HTTP/1.1" 302 0
[25/Nov/2020 11:23:45] "GET /order-summary/ HTTP/1.1" 200 9206
[25/Nov/2020 11:23:46] "GET /checkout/ HTTP/1.1" 200 37908
Using the defualt shipping address
Using the defualt billing address
[25/Nov/2020 11:23:51] "POST /checkout/ HTTP/1.1" 302 0
[25/Nov/2020 11:23:51] "GET /payment/paypal/ HTTP/1.1" 200 11866
Internal Server Error: /payment-complete/
Traceback (most recent call last):
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'S'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\core\views.py", line 446, in payment_complete
st = StockQuantity.objects.get(
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\query.py", line 418, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\sql\query.py", line 1319, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "C:\Users\halfs\Desktop\DJango\Django-ecommerce\env\lib\site-packages\django\db\models\fields\__init__.py", line 1776, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got 'S'.
[25/Nov/2020 11:24:18] "POST /payment-complete/ HTTP/1.1" 500 129792
[25/Nov/2020 11:24:19] "GET / HTTP/1.1" 200 15371
</code></pre>
<p>I understand what the problem is Django saves the foreign key by assigning ID and not the actual value but I don't know how to filter the objects, if I don't know object's id..
Thanks, any help is appreciated!!</p>
|
<p>When querying a ForeignKey field, you 'normally' pass an instance of the model. For example:</p>
<pre class="lang-py prettyprint-override"><code># Example models
class AnotherModel(models.Model):
name = models.CharField(...)
class MyModel(models.Model):
another_model = models.ForeignKey(AnotherModel,...)
# Get the instance
another_model_instance = AnotherModel.objects.get(id=1)
# Use the instance in the query
my_model = MyModel.objects.get(another_model=another_model_instance)
</code></pre>
<p>You can however, use <code>__</code> (double underscore) to 'hop' across and query a specific field. For example:</p>
<pre class="lang-py prettyprint-override"><code>my_model = MyModel.objects.get(another_model__name='Some name')
</code></pre>
<p>With the above example, we are querying using the <code>name</code> field on the <code>AnotherModel</code> model. We can use this to fix the query in your view.</p>
<pre class="lang-py prettyprint-override"><code># Taken from your payment_complete view
for item in order_items:
if item.item.is_footwear:
st = StockQuantity.objects.get(
item=item.item,
color__item_color=item.color,
footwear_size__footwear_size=str(item.footwear_size)
)
else:
st = StockQuantity.objects.get(
item=item.item,
color__item_color=item.color,
cloth_size__cloth_size=str(item.cloth_size)
)
</code></pre>
<p>Further reading: <a href="https://docs.djangoproject.com/en/3.1/topics/db/queries/" rel="noreferrer">https://docs.djangoproject.com/en/3.1/topics/db/queries/</a>.</p>
|
python|python-3.x|django|django-models
| 5 |
1,906,261 | 61,524,773 |
How to replace with second column with missing if 0?
|
<p>I have a csv file which is below</p>
<pre><code>ID,Name1,Name2
1,A,A
2,B,B
3,C,D
4,0,F
5,0,Z
</code></pre>
<p>The new table is below</p>
<pre><code>ID,NewName
1,A
2,B
3,C
4,F
5,Z
</code></pre>
<p>Basically if <code>0</code> coming in the <code>Name1</code> has to replace with <code>Name2</code></p>
|
<p>You can use <code>replace</code> then do <code>bfill</code></p>
<pre><code>df['Name']=df.drop('ID',1).replace({'0':np.nan}).bfill(1).iloc[:,0]
df
ID Name1 Name2 Name
0 1 A A A
1 2 B B B
2 3 C D C
3 4 0 F F
4 5 0 Z Z
</code></pre>
|
pandas
| 0 |
1,906,262 | 57,962,873 |
Easiest way to copy all fields from one dataclass instance to another?
|
<p>Let's assume you have defined a Python dataclass:</p>
<pre class="lang-py prettyprint-override"><code>@dataclass
class Marker:
a: float
b: float = 1.0
</code></pre>
<p><em>What's the easiest way to copy the values from an instance <code>marker_a</code> to another instance <code>marker_b</code>?</em></p>
<p>Here's an example of what I try to achieve:</p>
<pre class="lang-py prettyprint-override"><code>marker_a = Marker(1.0, 2.0)
marker_b = Marker(11.0, 12.0)
# now some magic happens which you hopefully can fill in
print(marker_b)
# result: Marker(a=1.0, b=2.0)
</code></pre>
<p><strong>As a boundary condition, I <em>do not want</em> to create and assign a new instance to <code>marker_b</code>.</strong></p>
<p>OK, I <em>could</em> loop through all defined fields and copy the values one by one, but there has to be a simpler way, I guess.</p>
|
<p>The <a href="https://docs.python.org/3/library/dataclasses.html#dataclasses.replace" rel="noreferrer"><code>dataclasses.replace</code></a> function returns a new copy of the object.
Without passing in any changes, it will return a copy with no modification:</p>
<pre><code>>>> import dataclasses
>>> @dataclasses.dataclass
... class Dummy:
... foo: int
... bar: int
...
>>> dummy = Dummy(1, 2)
>>> dummy_copy = dataclasses.replace(dummy)
>>> dummy_copy.foo = 5
>>> dummy
Dummy(foo=1, bar=2)
>>> dummy_copy
Dummy(foo=5, bar=2)
</code></pre>
<p>Note that this is a shallow copy.</p>
<h3>Edit to address comments:</h3>
<p>If a copy is undesirable, I would probably go with the following:</p>
<pre class="lang-py prettyprint-override"><code>for key, value in dataclasses.asdict(dummy).items():
setattr(some_obj, key, value)
</code></pre>
|
python|python-dataclasses
| 82 |
1,906,263 | 56,135,027 |
Permission denied on shutil.move on image files
|
<p>I am trying to move some files around. I can move any extension type except .png, .jpg, or .gif. When I try to move those types of files I get "IOError: [Errno 13] Permission denied" even though I am the admin. Code below</p>
<pre><code>import os, glob, shutil
dir = r'C:\\Users\\jcan4\\Desktop\\testmove\\*'
print(dir)
files = glob.glob(dir)
files.sort(key=os.path.getmtime)
for i, file in enumerate(files, start=1):
print(file)
oldext = os.path.splitext(file)[1]
shutil.move(file, 'Attachment-%s' % (i) + oldext)
</code></pre>
|
<p><strong>First things first</strong>, you're double escaping your <code>dir</code> variable:</p>
<pre class="lang-py prettyprint-override"><code>print(r'C:\\Users\\jcan4\\Desktop\\testmove\\*')
# Yields 'C:\\\\Users\\\\jcan4\\\\Desktop\\\\testmove\\\\*' !!
# What you really meant was either one of the following:
dir_harderToRead = 'C:\\Users\\jcan4\\Desktop\\testmove\\*'
dir_easyToRead = r'C:\Users\jcan4\Desktop\testmove\*'
</code></pre>
<p><strong>If you are still experiencing the error</strong>, it's because you are not giving the <em>python script</em> permissions to move the file. There are a couple ways to get around this:</p>
<h2>Windows</h2>
<p>(This applies to the asked question)</p>
<ol>
<li><p>Open command prompt (I see your file path and am assuming you're on windows) with administrative rights. (<a href="https://www.howtogeek.com/194041/how-to-open-the-command-prompt-as-administrator-in-windows-8.1/" rel="nofollow noreferrer">see here</a>)</p></li>
<li><p>Change ownership of the images to you. (see <a href="https://www.windowscentral.com/how-take-ownership-files-and-folders-windows-10" rel="nofollow noreferrer">here for windows 10</a> or <a href="https://gilsmethod.com/how-to-change-ownership-of-files-and-folders-in-windows-7" rel="nofollow noreferrer">here for windows 7</a>)</p></li>
</ol>
<h2>Linux (MacOS)</h2>
<p>(This applies to people on Linux that may have the same problem)</p>
<ol>
<li>Run the python script with root privileges:</li>
</ol>
<pre class="lang-sh prettyprint-override"><code># At command line
sudo python your_script_name.py
</code></pre>
<ol start="2">
<li>Change ownership of file to yourself:</li>
</ol>
<pre class="lang-sh prettyprint-override"><code># At command line
# Changes ownership of entire directory (CAREFUL):
chmod 755 /absolute/path/to/dir
chmod 755 relative/path/to/dir
# Or you can change file by file:
chmod 755 /absolute/path/to/file
chmod 755 relative/path/to/file
</code></pre>
<p>For more info, I used <a href="https://support.rackspace.com/how-to/checking-linux-file-permissions-with-ls/" rel="nofollow noreferrer">this site</a> on permissions. (If someone has a numerical value than <code>755</code> for chmod please say so.)</p>
|
python|shutil
| 0 |
1,906,264 | 55,206,523 |
ask user enter a file to run the program with python
|
<p>I have a program that concatenates French words separated by an asterisk in a text. As I want this program to be used by different users, I want to insert a line in the program asking the user to enter the path of the text file or simply enter the name of the text…How to do that? Just using function “input”? I have no idea…Is there an elegant way to ask that to the user to run the program? The program is below:</p>
<pre><code>import nltk
from nltk.tokenize import word_tokenize
import re
with open ('text-test.txt') as tx:
words = word_tokenize(tx.read().lower())
with open ('Fr-dictionary.txt') as fr:
dic = word_tokenize(fr.read().lower())
l=[ ]
errors=[ ]
out_file=open("newtext.txt","w")
for n,word in enumerate (words):
l.append(word)
if word == "*":
exp = words[n-1] + words[n+1]
print("\nconcatenation error:", exp)
if exp in dic:
l.append(exp)
l.append("$")
errors.append(words[n-1])
errors.append(words[n+1])
else:
continue
for i, w in enumerate(l):
if w == "*":
l.remove(l[i-1])
else:
continue
for i, w in enumerate(l):
if w == "$":
l.remove(l[i+1])
else:
continue
text=' '.join(l)
print('\n\n',text)
e=len(errors)
print('\n',e/2,'WORDS CONCATENATED IN TEXT',errors)
user=input('\nREMOVE * AND $ FROM TEXT? Type "Y" for yes or "N" for
no:')
for x in l:
if user=='Y' and x=='*':
l.remove(x)
elif user=='Y' and x=='$':
l.remove(x)
else:
continue
final_text=' '.join(l)
print('\n\n', final_text)
user2=input('\nWrite text to a file? Type "Y" for yes or "N" for no:')
if user2 =='Y':
out_file.write(final_text)
out_file.close()
print('\nText named "newtext.txt" written to a file')
</code></pre>
|
<p>You can do it any way you like, but having your users write out a full path to a file is tedious and error prone. What you could do is have a "watch folder". It's a folder that your script already knows about, maybe even in the same folder as your script. </p>
<p>A small example:</p>
<pre><code>import os
import sys
# This prints the folder where the script is run.
script_directory = os.path.dirname(sys.argv[0])
print(script_directory)
# This is the folder we want to keep track off
our_watched_folder = f'{script_directory}/watch_folder'
print(our_watched_folder)
# Let's see if a user dropped a new file in our folder
print("Files in watch folder")
for file in os.listdir(our_watched_folder):
print(file)
</code></pre>
<p>Output:</p>
<pre><code>C:/your_script_folder/
C:/your_script_folder/watch_folder
Files in watch folder
a_new_text_file.txt
some_old_textfile1.txt
some_old_textfile2.txt
</code></pre>
|
python|user-input
| 1 |
1,906,265 | 57,618,076 |
OpenCv raising error when numpy array fed into it
|
<p>I'm making a mandelbrot set zoom video maker and openCV is not allowing me to feed in my numpy array.</p>
<p>My end goal is to make a video that zooms in on "interesting" points in the mandelbrot set automaticly, but for now all I'm doing is zooming in on the center.</p>
<p>This is my code for making the video.</p>
<pre class="lang-py prettyprint-override"><code>from mandelbrot import getMandelbrot
import numpy as np
from cv2 import VideoWriter, VideoWriter_fourcc
import numpy
width = 500
height = 500
fps = 45
seconds = 1
fourcc = VideoWriter_fourcc(*'MP42')
video = VideoWriter('./mandelzoom.avi', fourcc, float(fps), (width, height))
for i in range(fps*seconds):
frame = getMandelbrot((-1/(i/(fps*seconds)+1), -1/(i/(fps*seconds)+1), 1/(i/(fps*seconds)+1), 1/(i/(fps*seconds)+1)), (width, height), 75)
video.write(np.array(frame, dtype=np.int8))
print("frame "+str(i)+" out of "+str(fps*seconds)+".")
video.release()
</code></pre>
<p>This is the mandelbrot module I have made.</p>
<pre class="lang-py prettyprint-override"><code>import colorsys
def hsv2rgb(h,s,v):
return [round(i * 255) for i in colorsys.hsv_to_rgb(h,s,v)]
def doesConverge(c, iterations, radius=2):
x=0
xpre=0
for i in range(iterations):
xpre=x
x=x*x+c
if abs(x)>radius:
return hsv2rgb(i/iterations, 1, 1)
if xpre==x:
return [0, 0, 0]
return [0, 0, 0]
def getMandelbrot(locationRect, size, iterations):
scaleX = size[0]/abs(locationRect[0]-locationRect[2])
scaleY = size[1]/abs(locationRect[1]-locationRect[3])
mandelbrot=[]
for i in range(size[1]):
mandelbrot.append([])
for j in range(size[0]):
mandelbrot[i].append(doesConverge(complex(j/scaleX+locationRect[0], i/scaleY+locationRect[1]), iterations))
return mandelbrot
</code></pre>
<p>When I run my video maker, it throws this error:</p>
<pre><code> File "C:/Users/Max/AppData/Local/Programs/Python/Python37/mandelzoom.py", line 15, in <module>
video.write(np.array(frame, dtype=np.int8))
cv2.error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_ffmpeg.cpp:298: error: (-215:Assertion failed) image.depth() == CV_8U in function 'cv::`anonymous-namespace'::CvVideoWriter_FFMPEG_proxy::write'
</code></pre>
|
<p>opencv is expecting an 8-bit unsigned type (<code>CV_8U</code>, which can contain values 0 to 255) but you're passing an 8-bit signed type (<code>np.int8</code>, which can contain values -128 to 127). Try using <code>np.uint8</code> instead of <code>np.int8</code> for the array type</p>
|
python|numpy|opencv
| 3 |
1,906,266 | 57,452,287 |
YUM package available in repo, but while install gives "No package"
|
<p>I am upgrading from python 2.7 to 3.6.</p>
<p>We are using JFrog artifactory repository for hosting packages.<br>
I have verified in the yum repo (artifactory) URL that the package python36 exists.</p>
<p>Following are the things tried:</p>
<pre><code>In /etc/yum.repos.d/epel.repo, added the baseurl of yum (artifactory) repo.
yum clean all
yum info python36 - Error: No matching Packages to list
yum install python36 - No package python36 available. Error: Nothing to do
</code></pre>
<p>But the install respond by saying "No package available".<br>
Please advise if I am missing anything here or need to look into other things.</p>
|
<p>For records -
With yum repolist and yum search working, yum install should be working.<br>
It turns out there was an issue with repo and artifacts were not discoverable.<br>
Now after repo being reloaded the things are working fine.</p>
|
python-3.6|yum|rhel7|epel
| 0 |
1,906,267 | 42,165,890 |
Python- unittest why SetUpClass gives attribute error
|
<p>I am using unittest and pytest</p>
<pre><code>@pytest.mark.usefixtures("oneTimeSetUp","setUp")
@ddt
class SendformTest(unittest.TestCase):
@pytest.fixture(autouse=True)
def classSetup(self,oneTimeSetUp):
self.sf = SendForms(self.driver)
self.ts = TestStatus(self.driver)
@classmethod
def setUpClass(self): ############ I want this method to run just once after login
self.sf.navigateToCCForms("img")
</code></pre>
<p>When I try to run this I get an attribute error:</p>
<blockquote>
<p><strong>AttributeError: type object 'SendformTest' has no attribute 'sf'</strong></p>
</blockquote>
|
<p>While I'm not entirely familiar with pytest, a quick google search took me to their page about using <a href="http://docs.pytest.org/en/latest/unittest.html" rel="nofollow noreferrer">pytest with unittest.TestCase</a>. The note at the bottom states:</p>
<blockquote>
<p>unittest.TestCase methods cannot directly receive fixture function arguments as implementing that is likely to inflict on the ability to run general unittest.TestCase test suites</p>
</blockquote>
<p>So my guess is your fixture is never running, leading to your setUp method's failure.</p>
|
python|selenium-webdriver|pytest|python-unittest
| 0 |
1,906,268 | 59,228,416 |
Merging 2 dataframes when key values are slightly different
|
<p>I would like to merge 2 dataframes, Problem is that the keys I am using do not contain the exact same values. So for example this is what df1 looks like</p>
<pre><code>name val3
Wilder Deontay 1
Fury Tyson 2
Ortiz Luis 3
Joshua Olaseni Oluwafemi Anthony 4
</code></pre>
<p>and df2</p>
<pre><code>name1 val
Deontay Wilder 19
Tyson Fury 20
Luis Ortiz 21
Anthony Joshua 10
</code></pre>
<p>The expected output is a merge of the two dataframes so</p>
<pre><code>name1 val val3
Deontay Wilder 19 1
Tyson Fury 20 2
Luis Ortiz 21 3
Anthony Joshua 10 4
</code></pre>
|
<p>Here is my solution,</p>
<pre class="lang-py prettyprint-override"><code>>>> import pandas as pd
>>> from fuzzywuzzy import fuzz
>>> data = {
'name': ['Wilder Deontay', 'Fury Tyson', 'Ortiz Luis', 'Joshua Olaseni Oluwafemi Anthony'],
'val3': [1, 2, 3, 4]
}... ... ...
>>> df1 = pd.DataFrame(data)
>>> data2 = {
'name1': ['Deontay Wilder', 'Tyson Fury', 'Luis Ortiz ', 'Anthony Joshua'],
'val': [19, 20, 21, 10]
}... ... ...
>>> df2 = pd.DataFrame(data2)
>>> df1['key'] = 1
>>> df2['key'] = 1
>>> merged = df1.merge(df2, on='key')
>>> merged['similarity'] = merged.apply(lambda row: fuzz.token_set_ratio(row['name'], row['name1']), axis=1)
>>> merged[merged.similarity == 100][['name1', 'val', 'val3']]
name1 val val3
0 Deontay Wilder 19 1
5 Tyson Fury 20 2
10 Luis Ortiz 21 3
15 Anthony Joshua 10 4
</code></pre>
<p>First I make cross merge and then I look at the similarity. For detailed information about <code>fuzzywuzzy</code> and <code>token_set_ratio</code>: <a href="https://stackoverflow.com/a/31823872/8205554">https://stackoverflow.com/a/31823872/8205554</a></p>
<p>Or you can use <code>fuzzymatcher</code>,</p>
<pre class="lang-py prettyprint-override"><code>>>> from fuzzymatcher import fuzzy_left_join
>>> fuzzy_left_join(df1, df2, 'name', 'name1')[['name1', 'val', 'val3']]
name1 val val3
0 Deontay Wilder 19 1
1 Tyson Fury 20 2
2 Luis Ortiz 21 3
3 Anthony Joshua 10 4
</code></pre>
|
python|pandas
| 1 |
1,906,269 | 58,441,004 |
Understanding variables stored in dir()
|
<p>From the python docs for <a href="https://docs.python.org/3/library/functions.html#dir" rel="nofollow noreferrer"><code>dir</code></a>:</p>
<blockquote>
<pre><code>Without arguments, return the list of names in the current local scope.
With an argument, attempt to return a list of valid attributes for that object.
</code></pre>
</blockquote>
<p>My reading of that is it would do the same as <code>locals()</code> would, but that is wrong:</p>
<pre><code>>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
</code></pre>
<p>What is the difference between these two built-ins, and why don't that provide the same result in this context?</p>
|
<p><code>dir()</code> returns a <strong>list</strong> of names in the current local scope, as the doc says. On the other hand, <a href="https://docs.python.org/3/library/functions.html#locals" rel="nofollow noreferrer"><code>locals()</code></a> returns a <strong>dictionary</strong>. This dictionary has the names as keys and their values as values. The names should be the same as the list returned by <code>dir()</code>.</p>
|
python
| 0 |
1,906,270 | 58,544,492 |
How to read files in other directory in python
|
<p>I want to open and read some files from different folders in Python3. The structure is like:</p>
<pre><code>snapshot
- folder1
- file 1
- file 2
- folder2
- file 3
- file 4
</code></pre>
<p>I tried using <code>pathlib</code>, but it is showed "\" instead "/". Is there other way to do it? The ideal result I want is this:</p>
<pre><code>"./snapshot/folder1/file 1"
"./snapshot/folder1/file 2"
"./snapshot/folder1/file 3"
"./snapshot/folder1/file 4"
</code></pre>
<p>This is my code:</p>
<pre><code>folders = Path('Snapshot/')**strong text**
for folder in folders.iterdir():
files = Path(f'./{folder}/')
for file in files.iterdir():
</code></pre>
|
<pre><code>import os
dirpath = 'snapshot'
for root, dirnames, fnames in os.walk(dirpath):
for fname in fnames:
print(os.path.join('.', root, fname))
</code></pre>
|
python
| 1 |
1,906,271 | 65,095,063 |
I can't run the Python Flask application, help needed
|
<p>When I run this Flask application logs in console seem to be fine, but I cannot find my webpage by the default url.
Error: Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. I entered this URL : <a href="http://127.0.0.1:5000/" rel="nofollow noreferrer">http://127.0.0.1:5000/</a> with the trailing slash.
Any thoughts?</p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World! <h1>Hello, World!<h1>"
if __name__ == '__main__':
app.run(debug = False)
</code></pre>
<p><img src="https://i.stack.imgur.com/b8iCT.png" alt="code and console log are on this screenshot" /></p>
<p><a href="https://i.stack.imgur.com/U6758.png" rel="nofollow noreferrer">The error webpage looks like this</a></p>
|
<p>As you can see in the screenshot, the webserver is running. Just go to your browser and type in the search bar:</p>
<pre><code>localhost:5000
</code></pre>
|
python|flask
| 1 |
1,906,272 | 22,444,147 |
Python: change part (single directory name) of path
|
<p>What would be the best way to change a single directory name (only the first occurence) within a path?</p>
<p>Example:</p>
<pre><code>source_path = "/path/to/a/directory/or/file.txt"
target_path = "/path/to/different/directory/or/file.txt"
</code></pre>
<p>I this case, the instruction would be: "replace the first directory of the name 'a' with a directory of the name 'different'"</p>
<p>I can think of methods where I would split up the path in its single parts first, then find the first "a", replace it and join it again. But I wonder if there is a more elegant way to deal with this. Maybe a built-in python function.</p>
|
<p>There is a function called <a href="http://docs.python.org/3.3/libray/os.path.html#os.path.split" rel="nofollow"><code>os.path.split</code></a> that can split a path into the final part and all leading up to it but that's the closest your going to get. Therefore the most elegant thing we can do is create a function that calls that continuously:</p>
<pre><code>import os, sys
def splitall(path):
allparts = []
while 1:
parts = os.path.split(path)
if parts[0] == path: # sentinel for absolute paths
allparts.insert(0, parts[0])
break
elif parts[1] == path: # sentinel for relative paths
allparts.insert(0, parts[1])
break
else:
path = parts[0]
allparts.insert(0, parts[1])
return allparts
</code></pre>
<p>Then you could use it like this, joining back together with <a href="http://docs.python.org/library/os.path.html#os.path.join" rel="nofollow"><code>os.path.join</code></a>:</p>
<pre><code>>>> source_path = '/path/to/a/directory/or/file'
>>> temp = splitall(source_path)
>>> temp
['path', 'to', 'a', 'directory', 'or', 'file']
>>> temp[2] = 'different'
>>> target_path = os.path.join(*temp)
>>> target_path
'path/to/different/directory/or/file'
</code></pre>
|
python|path|directory
| 2 |
1,906,273 | 22,792,634 |
Send the user an error message when they input anything apart from 4, 6 or 12
|
<p>In the following code, I want to add something that sends the user an error message when they input anything apart from 4, 6 or 12:</p>
<pre><code>import random
dice = input("""Hello there!
Welcome to the dice roll simulator.
There are three types of dice which you can roll:
a 4 sided die, a 6 sided die and a 12 sided die.
Please enter either 4,6 or 12 depending on which die you would like to roll.""")
if dice : 4 or 6 or 12
print("You have rolled a " + dice + " sided dice, with the result of : " + str((random.randrange(1,int(dice)))))
</code></pre>
|
<pre><code>if dice in (4, 6, 12):
print("...")
else:
print("error")
</code></pre>
<p>This is more pythonic than what I had earlier, but you should remember that <code>or</code> in Python doesn't work as intuitively as you might think; that is, <code>x == 6 or 7</code> must be written as <code>x == 6 or x == 7</code></p>
<p>As noted below, if you're using <code>input()</code> in Python 2.x, you don't have to cast it to an int but if you're using <code>raw_input()</code> in 2.x or <code>input()</code> in 3.x, you do have to cast, or else it will result in a <code>TypeError</code>.</p>
<p>Edit: Since you're using input, you're going to have to cast it to an int because <code>input</code> will return a string. </p>
<p>As Two-Bit Alchemist noted, in Python 2.x, <code>raw_input()</code> is equivalent to <code>input()</code> in Python 3.x.</p>
<p><code>input()</code> in Python 2.x is equivalent to <code>eval(input())</code> in Python3.x</p>
<p>For the differences in the input types in Python 2.x vs 3.x, see <a href="https://stackoverflow.com/questions/19036188/differences-between-input-commands-in-python-2-x-and-3-x">Differences between input commands in Python 2.x and 3.x</a></p>
|
python
| 1 |
1,906,274 | 45,366,023 |
Python-Function object creation
|
<p>As I understand from a book that function in Python is nothing but object of Function class. I have some doubts as below:</p>
<p>1.When this object gets created? At the time we define function or at the time we call a function?</p>
<p>2.If it is getting created at the time we define a function, then will it not be a waste of memory if we do not call that function anywhere in program ?</p>
<p>Looking for detail answer. </p>
|
<ol>
<li><p>As soon as you define a function or method (which is nothing but a bound function), Python creates a Function instance. This happens when your code is run for the first time.</p></li>
<li><p>Yes, it is a "waste" of memory, but consider how much memory that is compared to big arrays, binary files etc. Python is definitely not the most performant or resource-light language/interpreter, but it saves you lots of time on writing code (because your write less) and caring about optimisation (you usually don't). I mean seriously, what do a few KB in file size matter nowadays? Surely the loss in value is less than a minute of your attention.</p>
<p>The reason those unused functions can't be optimised away is that they might be used later on in the same script or by other scripts.</p></li>
</ol>
|
python|python-3.x|function|object
| 1 |
1,906,275 | 28,697,182 |
Variation in a parameter on an equation using Muller's method
|
<p>I am using the Meller's method program which I've found in this link:</p>
<p><a href="http://adorio-research.org/wordpress/?p=297" rel="nofollow">http://adorio-research.org/wordpress/?p=297</a></p>
<p>In the end of the routine it calculates the root of any fuction you input: </p>
<pre><code> if __name__ == "__main__":
def f(z):
return z**3 +1
xinit = 0.0
ztol = 1.0e-5
ftol = 1.0e-5
maxiter = 100
wantreal = False
nroots = 3
print zermuller(f, xinit, ztol, ftol, maxiter, wantreal, nroots)
</code></pre>
<p>However, I want to calculate for an equation like </p>
<pre><code> z**3 +w
</code></pre>
<p>where <code>w</code> would vary like from 1 to 2 in steps of 0.1 or something like that. So I have tried add a while command in the form:</p>
<pre><code>w = 8
while w < 9 :
w += 0.01 # Same as a = a + 1
if __name__ == "__main__":
def f(z):
return z**3 +w
xinit = 0.0
ztol = 1.0e-5
ftol = 1.0e-5
maxiter = 100
wantreal = False
nroots = 2
print zermuller(f, xinit, ztol, ftol, maxiter, wantreal, nroots)
</code></pre>
<p>But it doesn't do anything, only calculates for the first value of <code>w</code>, does any one know how I can make it to work, or what would be wrong in my <code>while</code> command.</p>
|
<p>Your code </p>
<pre><code>w = 8
while w < 9 :
w += 0.01 # Same as a = a + 1
</code></pre>
<p>is just an elaborate (and approximate) alternative to</p>
<pre><code>w = 9.01
</code></pre>
<p>You should call the function <em>inside</em> the loop</p>
<pre><code>def f(z):
return z**3 + w
xinit = 0.0
ztol = 1.0e-5
ftol = 1.0e-5
maxiter = 100
wantreal = False
nroots = 3
for i in range(11):
w = 8.0 + i/10.0
print zermuller(f, xinit, ztol, ftol, maxiter, wantreal, nroots)
</code></pre>
|
python|loops|while-loop
| 0 |
1,906,276 | 25,433,302 |
Passing a Variable fillColor to Google Map
|
<p>I am using Python and Flask to overlay a polygon on a Google map, with the bounds and colour of the polygon being passed in as variables.</p>
<p>My code draws simple square. I can pass the co-ordinates as variables fine</p>
<pre><code>`var sq1 = [
new google.maps.LatLng({{ result [7] }}, {{ result [8] }}),
new google.maps.LatLng({{ result [7] }}, {{ result [10] }}),
new google.maps.LatLng({{ result [9] }}, {{ result [10] }}),
new google.maps.LatLng({{ result [9] }}, {{ result [8] }}),
new google.maps.LatLng({{ result [7] }}, {{ result [8] }}),
];
sq1 = new google.maps.Polygon({
paths: sq1,
strokeWeight: 2,
fillOpacity: 1,
fillColor: '#FFFFFF',
});
</code></pre>
<p>But if I change</p>
<pre><code> fillColor: '#FFFFFF',
</code></pre>
<p>to</p>
<pre><code> fillColor: {{ result [12] }},
</code></pre>
<p>The it stops working. Result[12] returns #FFFFFF, I've also tried altering it to return '#FFFFFF' but to no avail.</p>
<p>Where am I going wrong?</p>
|
<p>When outputting values to be used for JavaScript, you need to make sure you escape your data property.</p>
<pre><code>fillColor: {{ result[12] }},
</code></pre>
<p>will output</p>
<pre><code>fillColor: #FFFFFF,
</code></pre>
<p>This isn't valid JavaScript. What you want it to output -- your first example had it -- is</p>
<pre><code>fillColor: '#FFFFFF",
</code></pre>
<p>There are two ways you could accomplish this. The simplest way to do it is</p>
<pre><code>fillColor: '{{ result[12] }}',
</code></pre>
<p>The other way to do this is a bit safer as it can be used for all variables being output to JavaScript. It is smart enough to put quotes around strings and treat numbers as such. It should also handle boolean values properly.</p>
<pre><code>fillColor: {{ result[12]|tojson|safe }},
</code></pre>
<p>An example of this is provided in the <a href="http://flask.pocoo.org/docs/0.10/templating/#standard-filters" rel="nofollow">Flask documentation</a>.</p>
|
python|google-maps|flask
| 2 |
1,906,277 | 25,589,019 |
Computing definite integrals in python
|
<p>I'm trying to write a loop that calculates the value of a definite integral at each step. The function <code>bigF</code> is very complicated. To put it in simple terms, it integrates a bunch of terms with respect to <code>s</code>, <code>from s=tn-(n/2)</code> to <code>s=tn+(n/2)</code>. After the integration, <code>bigF</code> still has a variable <code>t</code>. So you can say <code>bigF(t) = integral(f(s,t))</code>, where <code>f(s,t)</code> is the big mess of terms after <code>integrate.integ</code>. In the last line, I want to evaluate <code>bigF(t)</code> at <code>t=tn</code> after <code>bigF</code> computes the integral of <code>f(s,t)</code></p>
<p>After running, I get the error <code>global name 's' is not defined</code>. But <code>s</code> was meant to be just a dummy variable in the integration, since I am computing a convolution. What do I need to do?</p>
<pre><code>import numpy as np
import scipy.integrate as integ
import math
nt=5001#; %since (50-0)/.01 = 5000
dt = .01#; % =H
H=.01
theta_n = np.ones(nt)
theta_n[1]=0#; %theta_o
omega_n = np.ones(nt)
omega_n[1]=-0.4# %omega_o
epsilon=10^(-6)
eta = epsilon*10
t_o=0
def bigF(t, n):
return integrate.integ((422.11/eta)*math.exp((5*(4*((eta*t-s-tn)^2)/eta^2)-1)^(-1))*omega, s,tn-(n/2),tn+(n/2))
for n in range(1,4999)
tn=t_o+n*dt;
theta_n[n+1] = theta_n[n] + H*bigF(tn, n);
</code></pre>
|
<p>If you're doing a convolution, sounds like you want <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html" rel="nofollow">numpy.convolve</a>.</p>
|
python|integration|integral
| 0 |
1,906,278 | 61,904,022 |
Deploying a Python Library with C Dependencies to Heroku
|
<p>I am having some frustration deploying my project to Heroku. It depends upon a few python libraries for astrological software, which work fine on my local machine. But one of these libraries requires you to download some files and set the path to the downloaded files in order to run, and I think it is failing at this moment in the build process. The library is a Python extension to another library originally written in C. The python library is <a href="https://github.com/astrorigin/pyswisseph" rel="nofollow noreferrer">here</a>. I've been looking at some documentation <a href="https://devcenter.heroku.com/articles/stack-packages" rel="nofollow noreferrer">here</a> and <a href="https://devcenter.heroku.com/articles/python-c-deps" rel="nofollow noreferrer">here</a> and <a href="https://devcenter.heroku.com/categories/deploying-with-docker" rel="nofollow noreferrer">here</a>, but I've never built a docker image, and I'm not even sure it would be a solution to my problems. I also thought of adding a new buildpack, but also not sure it would solve the problem. My error is below, hopefully someone can point me in the right direction. I'm mostly looking for someone to tell me whether my problem could be solved with Docker or otherwise so that I don't waste time going down that path if it won't help. Thank you.</p>
<pre><code>Installing collected packages: pyswisseph
2020-05-20T00:01:48.839661+00:00 app[web.1]: Running setup.py install for pyswisseph: started
2020-05-20T00:01:48.839662+00:00 app[web.1]: Running setup.py install for pyswisseph: finished with status 'error'
2020-05-20T00:01:48.839662+00:00 app[web.1]:
2020-05-20T00:01:48.839801+00:00 app[web.1]: ERROR: Command errored out with exit status 1:
2020-05-20T00:01:48.839814+00:00 app[web.1]: command: /app/.local/share/virtualenvs/app-4PlAip0Q
/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-djfmycyt
/pyswisseph/setup.py'"'"'; __file__='"'"'/tmp/pip-install-djfmycyt/pyswisseph/setup.py'"'"';
f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"',
'"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-
wheel-vuz1lu7j
2020-05-20T00:01:48.839815+00:00 app[web.1]: cwd: /tmp/pip-install-djfmycyt/pyswisseph/
2020-05-20T00:01:48.839815+00:00 app[web.1]: Complete output (23 lines):
2020-05-20T00:01:48.839816+00:00 app[web.1]: Searching system libswe...
2020-05-20T00:01:48.839816+00:00 app[web.1]: pkg-config not found
2020-05-20T00:01:48.839816+00:00 app[web.1]: Using internal libswe
2020-05-20T00:01:48.839817+00:00 app[web.1]: /app/.local/share/virtualenvs/app-4PlAip0Q
/lib/python3.7/site-packages/setuptools/dist.py:454: UserWarning: Normalizing '2.08.00-1' to
'2.8.0.post1'
2020-05-20T00:01:48.839817+00:00 app[web.1]: warnings.warn(tmpl.format(**locals()))
2020-05-20T00:01:48.839818+00:00 app[web.1]: running bdist_wheel
2020-05-20T00:01:48.839818+00:00 app[web.1]: running build
2020-05-20T00:01:48.839818+00:00 app[web.1]: running build_ext
2020-05-20T00:01:48.839818+00:00 app[web.1]: building 'swisseph' extension
2020-05-20T00:01:48.839819+00:00 app[web.1]: creating build
2020-05-20T00:01:48.839819+00:00 app[web.1]: creating build/temp.linux-x86_64-3.7
2020-05-20T00:01:48.839819+00:00 app[web.1]: creating build/temp.linux-x86_64-3.7/libswe
2020-05-20T00:01:48.839820+00:00 app[web.1]: creating build/temp.linux-x86_64-3.7/swephelp
2020-05-20T00:01:48.839823+00:00 app[web.1]: gcc -pthread -Wno-unused-result -Wsign-compare
-DNDEBUG -g -fwrapv -O3 -Wall -fPIC -Ilibswe -Iswephelp -I/app/.local/share/virtualenvs
/app-4PlAip0Q/include -I/app/.heroku/python/include/python3.7m -c pyswisseph.c -o
build/temp.linux-x86_64-3.7/pyswisseph.o -std=gnu99
2020-05-20T00:01:48.839824+00:00 app[web.1]: In file included from /usr/lib/gcc/x86_64-linux-
gnu/7/include-fixed/syslimits.h:7:0,
2020-05-20T00:01:48.839824+00:00 app[web.1]: from /usr/lib/gcc/x86_64-linux-gnu/7/include-
fixed/limits.h:34,
2020-05-20T00:01:48.839825+00:00 app[web.1]: from /app/.heroku/python/include/python3.7m/Python.h:11,
2020-05-20T00:01:48.839825+00:00 app[web.1]: from pyswisseph.c:58:
2020-05-20T00:01:48.839828+00:00 app[web.1]: /usr/lib/gcc/x86_64-linux-gnu/7/include-fixed/limits.h:194:15: fatal error: limits.h: No such file or directory
2020-05-20T00:01:48.839829+00:00 app[web.1]: #include_next <limits.h> /* recurse down to the
real one */
2020-05-20T00:01:48.839829+00:00 app[web.1]: ^~~~~~~~~~
2020-05-20T00:01:48.839829+00:00 app[web.1]: compilation terminated.
2020-05-20T00:01:48.839846+00:00 app[web.1]: error: command 'gcc' failed with exit status 1
2020-05-20T00:01:48.839847+00:00 app[web.1]: ----------------------------------------
2020-05-20T00:01:48.839847+00:00 app[web.1]: ERROR: Failed building wheel for pyswisseph
</code></pre>
<p>EDIT - Here is the example setup.py code that is failing for reference :</p>
<pre><code># Test for pkg-config
has_pkgconfig = False
if swe_detection:
print('Searching system libswe...')
try:
import subprocess
try:
subprocess.check_output(['pkg-config'], stderr=subprocess.STDOUT)
except AttributeError: # < Python 2.7
# detection without pkg-config (or use popen)
pass
except subprocess.CalledProcessError:
has_pkgconfig = True
print('Found pkg-config')
except OSError:
print('pkg-config not found')
pass
except ImportError: # Python < 2.4
pass
#
# Find libswe-dev
libswe_found = False
if has_pkgconfig:
try:
swe_includes = subprocess.check_output(
['pkg-config', '--cflags', 'libswe-'+swe_version],
stderr=subprocess.STDOUT)
swe_libs = subprocess.check_output(
['pkg-config', '--libs', 'libswe-'+swe_version],
stderr=subprocess.STDOUT)
swe_sources = []
swe_depends = []
swe_defines = [('PYSWE_DEFAULT_EPHE_PATH',
'"/usr/share/libswe/ephe2:/usr/share/libswe/ephe"')]
libswe_found = True
print('pkg-config found libswe-'+swe_version)
except subprocess.CalledProcessError:
pass
#
# Another attempt at finding libswe-dev -- without pkg-config
# (pkg-config may be uninstalled but pc file should be in place)
# (and assuming there is only one version installed...)
if ( swe_detection and not libswe_found
and os.path.isfile( '/usr/lib/pkgconfig/libswe-'+swe_version+'.pc' )):
swe_includes = ['/usr/include']
swe_sources = []
swe_depends = []
swe_libs = ['swe']
swe_defines = [('PYSWE_DEFAULT_EPHE_PATH',
'"/usr/share/libswe/ephe2:/usr/share/libswe/ephe"')]
print('Found system libswe')
</code></pre>
|
<p>I fixed my issue. I think the build process was getting convoluted because I had a Rails app that was trying to run Python scripts, and I had two different buildpacks that were probably conflicting. I rewrote my app using just Python/Flask (it's just one page so far for testing deployment), and this seems to work (at least I've had no import/build errors). So, for anyone looking at this question, that was my fix. I used pipenv / a Pipfile instead of venv or virtualenv and gunicorn to deploy. </p>
|
python|c|linux|docker|heroku
| 0 |
1,906,279 | 24,380,853 |
Debug into libraries in python
|
<p>I'm trying to enter library function in PyCharm, to see what is happening there, but I can't: debugger shows me details and variables, moving inside step by step, but I don't see on my Window lines of code. I just can feel debugger is moving over them because it shows different internal variables.
I guess that happens because library is installed as binary package, without sources. </p>
<p>How should I install library to be able moving by it using debugger?</p>
<p>I tried both this installation types:</p>
<ul>
<li>I installed pip, and using it successfully installed suds.</li>
<li>I also downloaded suds sources (and build&installed from them, using setup.py).</li>
</ul>
<p>And both don't show me internal codelines. How can I move using debugger over library code?</p>
|
<p>I got it!</p>
<p>After building suds using setup.py, there appears directory <strong>suds</strong> with sources in: **BUILDING_DIR\build\lib**</p>
<p>It needs to copy it to **C:\PythonXX\Lib\site-packages**</p>
<p>and remove from there <strong>suds-Z.Z-pyX.X.egg</strong></p>
<p>then debugging starts to import sources from that directory and show code lines in debug. Bingo!</p>
|
python|debugging|python-2.7|pycharm
| 0 |
1,906,280 | 24,366,853 |
How to parse a list of SearchResults?
|
<p>I am using the App Engine search API and I'm trying to extract a list of doc_ids. Here is the result of my query:</p>
<pre><code>search.SearchResults(results=[
search.ScoredDocument(doc_id=u'-8853541246119947279', rank=0),
search.ScoredDocument(doc_id=u'-8853541246119948097', rank=0),
search.ScoredDocument(doc_id=u'-8853541246119946461', rank=0),
search.ScoredDocument(doc_id=u'51713103325273223', rank=0),
search.ScoredDocument(doc_id=u'5587798675278816831', rank=0),
search.ScoredDocument(doc_id=u'-8853541246119946464', rank=0),
search.ScoredDocument(doc_id=u'-3372400065395745350', rank=0),
search.ScoredDocument(doc_id=u'5587798675278815364', rank=0)
], number_found=8L)
</code></pre>
<p>How do I extract the <code>doc_id</code>s as a list?</p>
|
<p>Read through the documents more:</p>
<pre><code>results = index.search(search.Query(
#query and options here, including ids_only=True
))
doc_ids = [tmp_result.doc_id for tmp_result in results]
</code></pre>
|
python|google-app-engine
| 0 |
1,906,281 | 20,383,647 |
Pandas selecting by label sometimes return Series, sometimes returns DataFrame
|
<p>In Pandas, when I select a label that only has one entry in the index I get back a Series, but when I select an entry that has more then one entry I get back a data frame.</p>
<p>Why is that? Is there a way to ensure I always get back a data frame?</p>
<pre><code>In [1]: import pandas as pd
In [2]: df = pd.DataFrame(data=range(5), index=[1, 2, 3, 3, 3])
In [3]: type(df.loc[3])
Out[3]: pandas.core.frame.DataFrame
In [4]: type(df.loc[1])
Out[4]: pandas.core.series.Series
</code></pre>
|
<p>Granted that the behavior is inconsistent, but I think it's easy to imagine cases where this is convenient. Anyway, to get a DataFrame every time, just pass a list to <code>loc</code>. There are other ways, but in my opinion this is the cleanest.</p>
<pre><code>In [2]: type(df.loc[[3]])
Out[2]: pandas.core.frame.DataFrame
In [3]: type(df.loc[[1]])
Out[3]: pandas.core.frame.DataFrame
</code></pre>
|
python|pandas|dataframe|slice|series
| 144 |
1,906,282 | 71,864,143 |
Why am I missing required positional arguments when passing a function in Python?
|
<p>I am trying to minimize an error function with Scipy's fmin function. When attempting to pass the function into fmin, iIget an error saying that I am missing positional arguments. Here is the function, taking in arguments m and b:</p>
<pre><code>def gumbelError(m, b):
# define the gumbel function at the points of sorted mm
gumbel = np.exp(-np.exp(-np.divide(sortedmm - m, b)))
errors = gumbel - summed
return np.sum(np.power(errors, 2))
op.fmin(gumbelError, np.array(MLEmean, MLEsd))
</code></pre>
<p>This returns an error implying that I was trying to evaluate the function rather than passing it, and I don't know what is going wrong:</p>
<pre><code>TypeError: gumbelError() missing 1 required positional argument: 'b'
</code></pre>
|
<p>fmin can only manage functions with a single input. The problem here was that gumbelError took two inputs. This was solved by modifying gumbelError such that it took a single tuple input, which was then split within the function for use.</p>
|
python|function|scipy|scipy-optimize
| 0 |
1,906,283 | 21,373,259 |
SWIG in typemap works, but argout does not
|
<p>I have this file <code>foobar.h</code></p>
<pre><code>class Foobar {
public: void method(int arg[2]) {};
};
</code></pre>
<p>After compiling SWIG interface to Python, if I try to run this method from Python it says</p>
<pre><code>TypeError: in method 'Foobar_method', argument 2 of type 'int [2]'
</code></pre>
<p>Certainly. So I write this SWIG typemap:</p>
<pre><code>%typemap(in) int [2] {}
</code></pre>
<p>and when I compile this, Python runs this method without complaining. So I think, I understand how to write a typemap. </p>
<p>But, if I change the typemap to <code>argout</code>:</p>
<pre><code>%typemap(argout) int [2] {}
</code></pre>
<p>Now, Python goes back to the previous error. </p>
<p>I just do this directly from the SWIG manual, this should work without that error, just like <code>in</code> typemap.</p>
<p>What am I doing wrong???</p>
|
<h2>What's wrong?</h2>
<p>In short it's not an either/or proposition with these typemaps. </p>
<p>The key bit of information you're missing is the way multiple typemaps cooperate to wrap a single function.</p>
<p><code>argout</code> gets inserted in the generated wrapper <em>after</em> the call has happened. It's your opportunity to copy the (now modified) input back to Python in a sensible way.</p>
<p>That doesn't address the issue of how the argument gets created and passed in before the call however. </p>
<p>You can see this quite clearly by inspecting the code generated by this interface:</p>
<pre><code>%module test
%{
#include "test.h"
%}
%typemap(in) int[2] {
// "In" typemap goes here
}
%typemap(argout) int[2] {
// "argout" goes here
}
%include "test.h"
</code></pre>
<p>Which, when test.h is your example produces:</p>
<pre><code> // ... <snip>
arg1 = reinterpret_cast< Foobar * >(argp1);
{
// "In" typemap goes here
}
(arg1)->method(arg2);
resultobj = SWIG_Py_Void();
{
// "argout" goes here
}
return resultobj;
// ... <snip>
</code></pre>
<p>In those typemaps the goal of the "in" typemap is to make <code>arg2</code> a sensible value before the call and the "argout" typemap should do something sensible with the values after the call (possibly by changing the return value if you want).</p>
<hr>
<h2>What should be in the typemaps?</h2>
<p>Typically for a function like that you might want to have the input typemap populate a temporary array from some Python inputs.</p>
<p>To do that we're going to need to change the input typemap first, asking SWIG to create a temporary array for us:</p>
<p>It's important that we get SWIG to do this for us, using the notation of adding parenthesis after the type instead of adding it inside the body of the typemap so that the scope is correct for the variable. (If we didn't the temporary wouldn't be accessible from the "argout" typemap still and would be cleaned up before the call itself was made even).</p>
<pre><code>%typemap(in) int[2] (int temp[2]) {
// If we defined the temporary here then it would be out of scope too early.
// "In" typemap goes here
}
</code></pre>
<p>The code generated by SWIG now includes that temporary array for us, so we want to use the Python C API to iterate over our input. That might look something like:</p>
<pre><code>%typemap(in) int[2] (int temp[2]) {
// "In" typemap goes here:
for (Py_ssize_t i = 0; i < PyList_Size($input); ++i) {
assert(i < sizeof temp/sizeof *temp); // Do something smarter
temp[i] = PyInt_AsLong(PyList_GetItem($input, i)); // Handle errors
}
$1 = temp; // Use the temporary as our input
}
</code></pre>
<p>(We could have chosen to use <a href="http://docs.python.org/2/c-api/iter.html">Python iterator protocol</a> instead if we preferred).</p>
<p>If we compile and run the interface now we have enough to pass in an input, but nothing comes back yet. Before we write the "argout" typemap there's one thing still to notice in the generated code. Our temporary array in the generated code actually looks like <code>int temp2[2]</code>. That's not a mistake, SWIG has by default renamed the variable to be derived from the argument position in order to permit the same typemap to be applied multiple times to a single function call, once per argument if needed.</p>
<p>In my "argout" typemap I'm going to return another Python list with the new values. This isn't the only sane choice by a long way though - there are other options if you prefer.</p>
<pre><code>%typemap(argout) int[2] {
// "argout" goes here:
PyObject *list = PyList_New(2);
for (size_t i = 0; i < 2; ++i) {
PyList_SetItem(list, i, PyInt_FromLong(temp$argnum[i]));
}
$result = list;
}
</code></pre>
<p>The two points of note in this are firstly that we need to write <code>temp$argnum</code> explicitly to match the transformation that SWIG did on our temporary array and secondly that we're using <code>$result</code> as the output. </p>
<h3>Purely output arguments</h3>
<p>Often we have an argument that is just used for output, not input. For these it makes no sense to force the Python user to supply a list that's just going to be ignored. </p>
<p>We can do that by modifying the "in" typemap, using <code>numinputs=0</code> to indicate that no input is expected from Python. You'll need to take care of initializing the temporary appropriately here too. The typemap now becomes simply:</p>
<pre><code>%typemap(in,numinputs=0) int[2] (int temp[2]) {
// "In" typemap goes here:
memset(temp, 0, sizeof temp);
$1 = temp;
}
</code></pre>
<p>So now the "in" typemap doesn't actually take any input from Python at all. It can be seen as simply preparing the input to the native call.</p>
<p>By way of an aside you can avoid the name mangling that SWIG applies (with the cost of not being able to use the same typemap multiple times on the same function, or with another typemap that has a name clash) by using <code>noblock=1</code> in the "in" typemap. I wouldn't recommend that though.</p>
<h3>Non-fixed array length?</h3>
<p>Finally it's worth noting that we can write all of these typemaps to be more generic and work for any, fixed, size array. To do that we change 2 to "ANY" in the typemap matching and then use <code>$1_dim0</code> instead of 2 inside the typemap bodies, so the whole interface at the end of that becomes:</p>
<pre><code>%module test
%{
#include "test.h"
%}
%typemap(in,numinputs=0) int[ANY] (int temp[$1_dim0]) {
// "In" typemap goes here:
memset(temp, 0, sizeof temp);
$1 = temp;
}
%typemap(argout) int[ANY] {
// "argout" goes here:
PyObject *list = PyList_New($1_dim0);
for (size_t i = 0; i < $1_dim0; ++i) {
PyList_SetItem(list, i, PyInt_FromLong(temp$argnum[i]));
}
$result = list;
}
%include "test.h"
</code></pre>
|
python|swig
| 19 |
1,906,284 | 62,677,556 |
append element to subsist when condition matched
|
<pre><code>Group = [['car','truck'],['car','trusthost1 10.10.30.1','trusthost2 10.10.40.1','truck'],[car,trusthost1 10.10.30.1,trusthost2 10.10.50.1,truck,]['car','truck'],['car','trusthost1 10.10.35.1','trusthost2 10.10.44.1','truck']]
for i in Group:
for k in i:
if re.search('trusthost',str(k)):
i.append(k)
</code></pre>
<p>my above code is not working</p>
<p>every time when element include "trusthost" it should add after last element of sublist</p>
<p>expected result:</p>
<pre><code>Group = [['car','truck'],['car','truck''trusthost1 10.10.30.1','trusthost2 10.10.40.1',],['car','truck','trusthost1 10.10.30.1','trusthost2 10.10.50.1']['car','truck'],['car','truck','trusthost1 10.10.35.1','trusthost2 10.10.44.1',]]
</code></pre>
|
<pre><code>Group = [['car', 'truck'], ['car', 'trusthost1 10.10.30.1', 'trusthost2 10.10.40.1', 'truck'],
['car', 'trusthost1 10.10.30.1', 'trusthost2 10.10.50.1', 'truck'], ['car', 'truck'],
['car', 'trusthost1 10.10.35.1', 'trusthost2 10.10.44.1', 'truck']]
for lst in Group:
st = []
lst1 = []
for elem in lst:
if elem.startswith('trusthost'):
st.append(elem)
else:
lst1.append(elem)
lst1 += st
lst.clear()
for i in lst1:
lst.append(i)
print(Group)
</code></pre>
<p>This yields:</p>
<pre><code>[['car', 'truck'], ['car', 'truck', 'trusthost1 10.10.30.1', 'trusthost2 10.10.40.1'], ['car', 'truck', 'trusthost1 10.10.30.1', 'trusthost2 10.10.50.1'], ['car', 'truck'], ['car', 'truck', 'trusthost1 10.10.35.1', 'trusthost2 10.10.44.1']]
</code></pre>
<p>Hope this will help you.</p>
|
python
| 0 |
1,906,285 | 62,540,583 |
Parallelized DataFrame Custom Function Dask
|
<p>I am trying to use Dask to speed up a Python DataFrame for loop operation via Dask's multi-processing features. I am fully aware the for-looping dataframes is generally not best practice, but in my case, it is required. I have read pretty extensively through the documentation and other similar questions, but I cannot seem to figure my problem out.</p>
<pre class="lang-py prettyprint-override"><code>df.head()
Title Content
0 Lizzibtz @Ontario2020 @Travisdhanraj @fordnation Maybe. They are not adding to the stress of education during Covid. Texas sample. Plus…
1 Jess ️ @BetoORourke So ashamed at how Abbott has not handled COVID in Texas. A majority of our large cities are hot spots with no end in sight.
2 sidi diallo New post (PVC Working Gloves) has been published on Covid-19 News Info - Texas test
3 Kautillya @PandaJay What was the need to go to SC for yatra anyway? Isn't covid cases spiking exponentially? Ambubachi mela o… texas
4 SarahLou♡ RT @BenJolly9: 23rd June 2020 was the day Sir Keir Starmer let the Tories off the hook for their miss-handling of COVID-19. texas
</code></pre>
<p>I have a custom python function defined as:</p>
<pre class="lang-py prettyprint-override"><code>def locMp(df):
hitList = []
for i in range(len(df)):
print(i)
string = df.iloc[i]['Content']
# print(string)
doc = nlp(string)
ents = [e.text for e in doc.ents if e.label_ == "GPE"]
x = np.array(ents)
print(np.unique(x))
hitList.append(np.unique(x))
df['Locations'] = hitList
return df
</code></pre>
<p>This function adds a dataframe column of locations extracted from a library called spacy - I do not think that is important, but I want you to see the whole function.</p>
<p>Now, via the documentation and a few other questions out there. The way to use Dask's multiprocessing for a dataframe is to create a Dask dataframe, partition it, <code>map_partitions</code>, and <code>.compute()</code>. So, I have tried the following and some other options with no luck:</p>
<pre class="lang-py prettyprint-override"><code>part = 7
ddf = dd.from_pandas(df, npartitions=part)
location = ddf.map_partitions(lambda df: df.apply(locMp), meta=pd.DataFrame).compute()
# and...
part = 7
ddf = dd.from_pandas(df, npartitions=part)
location = ddf.map_partitions(locMp, meta=pd.DataFrame).compute()
# and simplifying from Dask documentation
part = 7
ddf = dd.from_pandas(df, npartitions=part)
location = ddf.map_partitions(locMp)
</code></pre>
<p>I have tried a few other things with <code>dask.delayed</code> but nothing seems to work. I either get a Dask Series or some other undesired output OR the function takes as long as or longer than just running it regularly. How can I use Dask to speed up custom DataFrame function operations and return a clean Pandas Dataframe?</p>
<p>Thank you</p>
|
<p>You could try letting Dask handle the application instead of doing the looping yourself:</p>
<pre class="lang-py prettyprint-override"><code>ddf["Locations"] = ddf["Content"].apply(
lambda string: [e.text for e in nlp(string).ents if e.label_ == "GPE"],
meta=("Content", "object"))
</code></pre>
|
python|pandas|dataframe|dask
| 1 |
1,906,286 | 70,256,742 |
Session cookies not passing properly while scraping
|
<p>I am trying to scrape Walmart, if I just dump the curl Payload in <code>requests</code> format, it works fine, the issue is <code>cookies</code>, if I omit, it gives a 403 error. I do not want to pass static cookies, I tried to pass session cookies but not working. Below is my code</p>
<p><strong>Passing Static Cookies</strong></p>
<pre><code>import requests
headers = {
'authority': 'www.walmart.com',
'pragma': 'no-cache',
'cache-control': 'no-cache',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
'dnt': '1',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36',
'sec-ch-ua-platform': '"macOS"',
'content-type': 'application/json',
'accept': '*/*',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'referer': 'https://www.walmart.com/store/5939-bellevue-wa/search?query=butter',
'accept-language': 'en-US,en;q=0.9,ur;q=0.8,zh-CN;q=0.7,zh;q=0.6',
'cookie': 'brwsr=3546b2d8-4454-11ec-8b5a-dbae802bd5ca; ACID=3e3752b6-a706-4ddf-95a2-ae88083ebe3e; hasACID=true; locGuestData=eyJpbnRlbnQiOiJTSElQUElORyIsInN0b3JlSW50ZW50IjoiUElDS1VQIiwibWVyZ2VGbGFnIjpmYWxzZSwicGlja3VwIjp7Im5vZGVJZCI6IjMwODEiLCJ0aW1lc3RhbXAiOjE2MzY3ODg5MDEyMTB9LCJwb3N0YWxDb2RlIjp7InRpbWVzdGFtcCI6MTYzNjc4ODkwMTIxMCwiYmFzZSI6Ijk1ODI5In0sInZhbGlkYXRlS2V5IjoicHJvZDp2MjozZTM3NTJiNi1hNzA2LTRkZGYtOTVhMi1hZTg4MDgzZWJlM2UifQ%3D%3D; vtc=T0u0KwKFJGHeU3asnYGQ_w; TBV=7; DL=94066%2C%2C%2Cip%2C94066%2C%2C; TB_Latency_Tracker_100=1; TB_Navigation_Preload_01=1; crumb=2RJK-XnGcnZ8WeLbzMNhC6uSY75Q9sqHRkR8eVTWjyH; tb_sw_supported=true; TB_SFOU-100=1; AID=wmlspartner%253Dimp_150372%253Areflectorid%253Dimp_zl3TTEwhgxyIUNGVPPU0LViWUkGxlaWkqz2KVY0%253Alastupd%253D1638813128173; locDataV3=eyJpbnRlbnQiOiJTSElQUElORyIsInBpY2t1cCI6W3siYnVJZCI6IjAiLCJub2RlSWQiOiIzMDgxIiwiZGlzcGxheU5hbWUiOiJTYWNyYW1lbnRvIFN1cGVyY2VudGVyIiwibm9kZVR5cGUiOiJTVE9SRSIsImFkZHJlc3MiOnsicG9zdGFsQ29kZSI6Ijk1ODI5IiwiYWRkcmVzc0xpbmUxIjoiODkxNSBHZXJiZXIgUm9hZCIsImNpdHkiOiJTYWNyYW1lbnRvIiwic3RhdGUiOiJDQSIsImNvdW50cnkiOiJVUyIsInBvc3RhbENvZGU5IjoiOTU4MjktMDAwMCJ9LCJnZW9Qb2ludCI6eyJsYXRpdHVkZSI6MzguNDgyNjc3LCJsb25naXR1ZGUiOi0xMjEuMzY5MDI2fSwiaXNHbGFzc0VuYWJsZWQiOnRydWUsInNjaGVkdWxlZEVuYWJsZWQiOnRydWUsInVuU2NoZWR1bGVkRW5hYmxlZCI6dHJ1ZX1dLCJkZWxpdmVyeSI6eyJidUlkIjoiMCIsIm5vZGVJZCI6IjMwODEiLCJkaXNwbGF5TmFtZSI6IlNhY3JhbWVudG8gU3VwZXJjZW50ZXIiLCJub2RlVHlwZSI6IlNUT1JFIiwiYWRkcmVzcyI6eyJwb3N0YWxDb2RlIjoiOTU4MjkiLCJhZGRyZXNzTGluZTEiOiI4OTE1IEdlcmJlciBSb2FkIiwiY2l0eSI6IlNhY3JhbWVudG8iLCJzdGF0ZSI6IkNBIiwiY291bnRyeSI6IlVTIiwicG9zdGFsQ29kZTkiOiI5NTgyOS0wMDAwIn0sImdlb1BvaW50Ijp7ImxhdGl0dWRlIjozOC40ODI2NzcsImxvbmdpdHVkZSI6LTEyMS4zNjkwMjZ9LCJpc0dsYXNzRW5hYmxlZCI6dHJ1ZSwic2NoZWR1bGVkRW5hYmxlZCI6dHJ1ZSwidW5TY2hlZHVsZWRFbmFibGVkIjp0cnVlLCJhY2Nlc3NQb2ludHMiOlt7ImFjY2Vzc1R5cGUiOiJERUxJVkVSWV9BRERSRVNTIn1dfSwic2hpcHBpbmdBZGRyZXNzIjp7ImxhdGl0dWRlIjozOC40NzM4LCJsb25naXR1ZGUiOi0xMjEuMzQzOSwicG9zdGFsQ29kZSI6Ijk1ODI5IiwiY2l0eSI6IlNhY3JhbWVudG8iLCJzdGF0ZSI6IkNBIiwiY291bnRyeUNvZGUiOiJVU0EiLCJnaWZ0QWRkcmVzcyI6ZmFsc2V9LCJhc3NvcnRtZW50Ijp7Im5vZGVJZCI6IjMwODEiLCJkaXNwbGF5TmFtZSI6IlNhY3JhbWVudG8gU3VwZXJjZW50ZXIiLCJhY2Nlc3NQb2ludHMiOm51bGwsImludGVudCI6IlBJQ0tVUCIsInNjaGVkdWxlRW5hYmxlZCI6ZmFsc2V9LCJpbnN0b3JlIjpmYWxzZSwicmVmcmVzaEF0IjoxNjM4ODM0NzI4MjkxLCJ2YWxpZGF0ZUtleSI6InByb2Q6djI6M2UzNzUyYjYtYTcwNi00ZGRmLTk1YTItYWU4ODA4M2ViZTNlIn0%3D; assortmentStoreId=3081; hasLocData=1; akavpau_p2=1638813728~id=0ddec06ac25050953645a4b5d72af4f0; adblocked=true; com.wm.reflector="reflectorid:imp_zl3TTEwhgxyIUNGVPPU0LViWUkGxlaWkqz2KVY0@lastupd:1638813132000@firstcreate:1636788901158"; next-day=null|true|true|null|1638862621; location-data=94066%3ASan%20Bruno%3ACA%3A%3A0%3A0|21k%3B%3B15.22%2C46y%3B%3B16.96%2C1kf%3B%3B19.87%2C1rc%3B%3B23.22%2C46q%3B%3B25.3%2C2nz%3B%3B25.4%2C2b1%3B%3B27.7%2C4bu%3B%3B28.38%2C2er%3B%3B29.12%2C1o1%3B%3B30.14|2|7|1|1xun%3B16%3B0%3B2.44%2C1xtf%3B16%3B1%3B4.42%2C1xwj%3B16%3B2%3B7.04%2C1ygu%3B16%3B3%3B8.47%2C1xwq%3B16%3B4%3B9.21; TB_DC_Flap_Test=0; bstc=cqPOkDdcHRbOOWnXljFUXU; mobileweb=0; xpa=; xpm=3%2B1638862621%2BT0u0KwKFJGHeU3asnYGQ_w~%2B0; _pxhd=1wGn8vPC/xYO43oIyZQIBmYn28J4J4/ceMd-WLk8e9M7Qyw0ToljNcm1zXiFNAC5tYcUXy88tg3nBqpdAuT5sQ==:dW/JtmJPPeYviWr1RnbGL8Q8fvsAnk/Tr319tYqmCEF-ZACrf9lbi8vQzvzKY6lDVRH5k5dW2zRPEnPwSFdhe9v-Q1NOMHusjxvPvQ2BFeM=; ak_bmsc=DEAF5D13B7E5DB9D1445A42C981F72DB~000000000000000000000000000000~YAAQP54QApQE/i99AQAATg3Tkw6GGZisOY9WqflSzzYhEOPbRvefmAkpiEYorVwUfg9UEAFnLY8StjWnjYCXsEqzFDDy+gnGpbydgZS+20l+VJJigKU51o2xuF8AJrgY5QzJhLMA/i9MxW5MRL+n0zV+BC1PLTb1hhelYx8GmmyDV+HifGBSgErgNtb6pUA5ydONX9EprYpZknQfqP30OmVWTnKkloTrQDkfJcJ0vI+P/MEZb8U2molWz/GdGwU+rbhcdSfa9oWaLaAp8E/DZjsY6YpmW4fmZNQTrUfa7P2db8EDnbWF1zi8r3D+51o2Hi7bd5Bi+8txdaDdl9YT3+Nr4VofqwkH5iXqOmidTDd/fO6qvtQyO0oau3Vjowa+xhn04TYYtlQjsb9A; xptwg=3271574160:209D26905C6B780:55789D4:D6539E2E:8EBD026C:E7FE99FF:; TS01b0be75=01538efd7c206a0dc58225169e0b825676e9c5e453ca7af568232e9be3e84e5a6227c4b728ed7713e869287e81ef2d29326fcd6cab; TS013ed49a=01538efd7c206a0dc58225169e0b825676e9c5e453ca7af568232e9be3e84e5a6227c4b728ed7713e869287e81ef2d29326fcd6cab; bm_mi=01610934A8DDD8546E2A0DEF61A8C91C~xOaPkjLqDDIuv11EPeZ1gIxvBQt6PD6zjA7Gd2qVQfVC6cwGG83ojqAvWCSM6IYwVuSjWY3iSyJNH7YzUX2nmRtIlmJUlrAz5tz3OU9v1zqnhHdq0QcCuMve0SUoKRpLcqWK65ocd9vpQR78SbT7CLWkBDckK4ro0g38t1cdBsBb8OZKF21D+M5ZU1pHVEuO3MvvWCWNDByoMpg9KcRVvq/67Rbu6fVBemqGJU3g54VcLF6BgDysyAiM1zrC5dHyOznoyGKalanQZpuh4hQQwg==; bm_sv=FA70A3C0284440D78F7D26E1C9316BD3~G6MyGle3ACdP7loWuTml7iej+WW4evzORtt1IKVCT/tduzxQYcbTI2Ti1xyqDnz8l6K0ty4wXsRVwrzTkcnDAzku7y4AVIZ5cKsSt9rThXIHazknmtE9Y0OSWFRz8IdFFrO5uHnXxAPnXTdp97vj7fYje/wT3m+GfZhmesPZZNs=',
}
params = (
('query', keyword),
('stores', '5939'),
('cat_id', '0'),
('ps', '24'),
('offset', '24'),
('prg', 'desktop'),
('zipcode', '98006'),
('stateOrProvinceCode', 'WA'),
)
session = requests.session()
r = session.get(
'https://www.walmart.com/store/electrode/api/search',
headers=headers,
params=params
)
print(r.status_code) #returns 200
</code></pre>
<p><strong>Passing runtime cookies(It does not work)</strong></p>
<pre><code>import requests
headers = {
'authority': 'www.walmart.com',
'pragma': 'no-cache',
'cache-control': 'no-cache',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
'dnt': '1',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36',
'sec-ch-ua-platform': '"macOS"',
'content-type': 'application/json',
'accept': '*/*',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'referer': 'https://www.walmart.com/store/5939-bellevue-wa/search?query=tillamook',
'accept-language': 'en-US,en;q=0.9,ur;q=0.8,zh-CN;q=0.7,zh;q=0.6'
}
params = (
('query', keyword),
('stores', '5939'),
('cat_id', '0'),
('ps', '24'),
('offset', '24'),
('prg', 'desktop'),
('zipcode', '98006'),
('stateOrProvinceCode', 'WA'),
)
# Get session cookies
session = requests.session()
r = session.get('https://www.walmart.com/')
cookies = session.cookies
cookies_dictionary = cookies.get_dict()
print(cookies)
r = session.get(
'https://www.walmart.com/store/electrode/api/search',
headers=headers,
params=params,
cookies=cookies # Not working
)
print(r.status_code) # Returns 403
</code></pre>
<p><strong>Update</strong>
<code>response.cookies</code> generate different cookies</p>
<pre><code>{'TS01b0be75': '01538efd7c044ddd7186ec7b8e9a2c7c3f59c4292535357d3ee83514b723af242e66b7d2d4bb89dca3c3512d765a35854d24b328b7', '_pxhd': 'f2ledR7-gSvtTHbIFTwB89DoCT99Whwim/4tbcl-XKEvqQH1mfG94waAxWYDdlEtAS7YXmgpcH9Wg7XztyrF-w==:DGocCdAUsAwd9NAEPkHiaYyPxwgpVX3GTvmhGfztbMb2T6hqgKWOgSYeW1U0qtgwsseesEz/fHMPnVceRuFkILyXsV9wDt9vKy708YcyTOk=', 'akavpau_p2': '1638865229~id=bd97f18a4cb5fae6b4f4625ef3799a9d'}
</code></pre>
|
<p>Try using selenium to fetch the cookies from that site first according to how @furas suggested in comments. You can then use those cookies within headers while issuing get requests to grab the required response and result. I found success using the following approach:</p>
<pre><code>import time
import requests
from selenium import webdriver
def get_cookies():
with webdriver.Chrome() as driver:
driver.get('https://www.walmart.com/store/5939-bellevue-wa/search?query=tillamook')
time.sleep(10)
driver_cookies = driver.get_cookies()
cookie = {c['name']:c['value'] for c in driver_cookies}
return cookie
headers = {
'accept': '*/*',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36',
'referer': 'https://www.walmart.com/store/5939-bellevue-wa/search?query=tillamook',
}
params = {
'query': 'tillamook',
'stores': '5939',
'cat_id': '0',
'ps': '24',
'offset': '24',
'prg': 'desktop',
'zipcode': '98006',
'stateOrProvinceCode': 'WA',
}
with requests.session() as session:
r = session.get(
'https://www.walmart.com/store/electrode/api/search',
headers=headers,
params=params,
cookies=get_cookies()
)
print(r.status_code) # Returns 200
print(r.json())
</code></pre>
|
python|web-scraping|cookies|python-requests
| 1 |
1,906,287 | 46,116,040 |
Onchange function for stage
|
<p>I have two fields in odoo10, and I want to add <code>@onchange</code> function for one of them. </p>
<p>In one field I added three workflows, in first workflow <code>work1</code> I added two stages (create, new). Similarly for second <code>work2</code> and third <code>work3</code>, I added two stages (draft, escalate) and (assign, pending).</p>
<p>When I select <code>work1</code> from workflow field then related stages should show in the stage field. So, can anyone solve this problem ? </p>
<p>My python code for that is below :</p>
<pre><code>work_flow_stage = fields.Many2one('stage.workflow', string="Work Flow", change_default=True, default=_work_flow_status)
work_stage = fields.Many2one('partner.state', string="Stage")
@api.onchange('work_flow_stage', 'work_stage')
@api.multi
def _work_flow_status(self):
stage = self.env['stage.workflow'].search([('work_stage', 'in', 'work_flow_stage')], limit=1)
print "stage", stage
return stage
</code></pre>
|
<p>That method doesn't assign anything to your current work_stage, it just return the value, that would be dismissed after execution. </p>
<p>I am assuming, that you have the same field <code>work_stage</code> in your <code>stage.workflow</code>.
If you want to do this via <code>@api.onchange</code> you could implement it in 2 ways:</p>
<pre><code>@api.onchange('work_flow_stage')
def _onchange_work_flow_stage(self):
return {
'value': {
'work_stage': self.work_flow_stage.work_stage.id
}
}
# ========= OR ===========
self.work_stage = self.work_flow_stage.work_stage.id
</code></pre>
<p>There might be a possibility to do this with the relation, like: </p>
<pre><code>work_flow_stage = fields.Many2one('stage.workflow', 'Work Flow', change_default=True)
work_stage = fields.Many2one('partner.state', 'Stage', related='work_flow_stage.work_stage')
</code></pre>
<p>Though, I'm not sure would it work when you'll change your work_flow_stage immediately. Please, send the feedback.</p>
<p>Hope, that will help. </p>
|
python|python-2.7|openerp|odoo-10
| 0 |
1,906,288 | 46,032,318 |
printing row-based data in a table format on python
|
<p>I have the below data in an array each line represents each index</p>
<pre><code>col1 col2 col3 subcol1 subcol2 subcol3
[3 spaces]subcol4 subcol5 subcol6
[2 spaces]col4 subcol7 subcol8 subcol9
[3 spaces]subcol10 subcol11 subcol2
</code></pre>
<p>I want to convert this data as shown below:</p>
<pre><code>-------------------------------------------------------
col1 | col2 | col3 | subcol1 | subcol2 | subcol13
--------------------------------
| | | subcol4 | subcol5 | subcol6
-----------------------------------------
| | col4 | subcol7 | subcol8 | subcol9
--------------------------------
| | | subcol10 | subcol11| subcol12
-------------------------------------------------------
</code></pre>
<p>How can I accomplish this?</p>
|
<p>You can use Tabulate for pretty similar results: <a href="https://pypi.python.org/pypi/tabulate" rel="nofollow noreferrer">https://pypi.python.org/pypi/tabulate</a></p>
<p>Setup:</p>
<pre><code>from tabulate import tabulate
data = [
['col1', 'col2', 'col3', 'subcol1', 'subcol2', 'subcol3'],
['', '', '', 'subcol4', 'subcol5', 'subcol6'],
['', '', 'col4', 'subcol7', 'subcol8', 'subcol9'],
['', '', '', 'subcol10', 'subcol11', 'subcol2'],
]
</code></pre>
<p>Then print:</p>
<pre><code>print tabulate(data[1:], headers=data[0], tablefmt='orgtbl')
</code></pre>
<p>Which will resolve to:</p>
<pre><code>| col1 | col2 | col3 | subcol1 | subcol2 | subcol3 |
|--------+--------+--------+-----------+-----------+-----------|
| | | | subcol4 | subcol5 | subcol6 |
| | | col4 | subcol7 | subcol8 | subcol9 |
| | | | subcol10 | subcol11 | subcol2 |
</code></pre>
<p>Or without headers:</p>
<pre><code>print tabulate(data, tablefmt='orgtbl')
</code></pre>
<p>Which will resolve to:</p>
<pre><code>| col1 | col2 | col3 | subcol1 | subcol2 | subcol3 |
| | | | subcol4 | subcol5 | subcol6 |
| | | col4 | subcol7 | subcol8 | subcol9 |
| | | | subcol10 | subcol11 | subcol2 |
</code></pre>
<p>Other available options for 'tablefmt' parameter</p>
<pre><code>- "plain"
- "simple"
- "grid"
- "fancy_grid"
- "pipe"
- "orgtbl"
- "jira"
- "psql"
- "rst"
- "mediawiki"
- "moinmoin"
- "html"
- "latex"
- "latex_booktabs"
- "textile"
</code></pre>
|
python
| 1 |
1,906,289 | 33,414,028 |
Anchor to End of Last Match
|
<p>In the process of working on <a href="https://stackoverflow.com/a/33412893/2642059">this answer</a> I stumbled on an anomaly with Python's repeating regexes.</p>
<p>Say I'm given a CSV string with an arbitrary number of quoted and unquoted elements:</p>
<blockquote>
<p>21, 2, '23.5R25 ETADT', 'description, with a comma'</p>
</blockquote>
<p>I want to replace all the <code>','</code>s outside quotes with <code>'\t'</code>. So I'd like an output of:</p>
<blockquote>
<p>21\t2\t'23.5R25 ETADT'\t'description, with a comma'</p>
</blockquote>
<p>Since there will be multiple matches in the string naturally I'll use the <code>g</code> regex modifier. The regex I'll use will match characters outside quotes or a quoted string followed by a <code>','</code>:</p>
<pre><code>('[^']*'|[^',]*),\s*
</code></pre>
<p>And I'll replace with:</p>
<pre><code>\1\t
</code></pre>
<p>Now the problem is the regex is <em>searching</em> not <em>matching</em> so it can choose to skip characters until it can match. So rather than my desired output I get:</p>
<blockquote>
<p>21\t2\t'23.5R25 ETADT'\t'description\twith a comma'</p>
</blockquote>
<p>You can see a live example of this behavior here: <a href="https://regex101.com/r/sG9hT3/2" rel="nofollow noreferrer">https://regex101.com/r/sG9hT3/2</a></p>
<h1>Q. Is there a way to anchor a <code>g</code> modified regex to begin matching at the character after the previous match?</h1>
<hr />
<p>For those familiar with Perl's mighty regexs, Perl provides the <a href="http://perldoc.perl.org/functions/pos.html" rel="nofollow noreferrer"><code>\G</code></a>. Which allows us to retrieve the end of the last position matched. So in Perl I could accomplish what I'm asking for with the regex:</p>
<pre><code>\G('[^']*'|[^',]*),\s*
</code></pre>
<p>This would force a mismatch within the final quoted element. Because rather than allowing the regex implementation to find a point where the regex matched the <code>\G</code> would force it to begin matching at the <em>first</em> character of:</p>
<blockquote>
<p>'description, with a comma'</p>
</blockquote>
|
<p>You can use the following regex with <code>re.search</code>:</p>
<pre><code>,?\s*([^',]*(?:'[^']*'[^',]*)*)
</code></pre>
<p>See <a href="https://regex101.com/r/vN3vO3/2" rel="nofollow">regex demo</a> (I change it to <code>,?[ ]*([^',\n]*(?:'[^'\n]*'[^',\n]*)*)</code> since it is a multiline demo)</p>
<p>Here, the regex matches (in a regex meaning of the word)...</p>
<ul>
<li><code>,?</code> - 1 or 0 comma</li>
<li><code>\s*</code> - 0 or more whitespace </li>
<li><code>([^',]*(?:'[^']*'[^',]*)*)</code> - Group 1 storing a captured text that consists of...
<ul>
<li><code>[^',]*</code> - 0 or more characters other than <code>,</code> and <code>'</code></li>
<li><code>(?:'[^']*'[^',]*)*</code> - 0 or more sequences of ...
<ul>
<li><code>'[^']*'</code> - a <code>'string'</code>-like substring containing no apostrophes</li>
<li><code>[^',]*</code> - 0 or more characters other than <code>,</code> and <code>'</code>.</li>
</ul></li>
</ul></li>
</ul>
<p>If you want to use a <code>re.match</code> and store the captured texts inside capturing groups, it is not possible since Python regex engine does not store all the captures in a stack as .NET regex engine does with <code>CaptureCollection</code>.</p>
<p>Also, Python regex does not support <code>\G</code> operator, so you cannot anchor any subpattern at the end of a successful match here.</p>
<p>As an alternative/workaround, you can use the following <strong><em>Python code to return successive matches and then the rest of the string</em></strong>:</p>
<pre><code>import re
def successive_matches(pattern,text,pos=0):
ptrn = re.compile(pattern)
match = ptrn.match(text,pos)
while match:
yield match.group()
if match.end() == pos:
break
pos = match.end()
match = ptrn.match(text,pos)
if pos < len(text) - 1:
yield text[pos:]
for matched_text in successive_matches(r"('[^']*'|[^',]*),\s*","21, 2, '23.5R25 ETADT', 'description, with a comma'"):
print matched_text
</code></pre>
<p>See <a href="http://ideone.com/GN9Ld3" rel="nofollow">IDEONE demo</a>, the output is</p>
<pre><code>21,
2,
'23.5R25 ETADT',
'description, with a comma'
</code></pre>
|
python|regex|search|match|repeat
| 2 |
1,906,290 | 33,131,417 |
Python - prime numbers
|
<p>I am creating a program in python which adds up the total of all the prime numbrs up to 10. My code so far is:</p>
<pre><code>total = 0
for i in range (10):
for a in range (2,i):
if i % a == 0:
break
else:
total += i
break
print total
</code></pre>
<p>My code does not include 2 as a prime number but does include 9. Can anybody spot the error?</p>
|
<p>Your <code>else:</code> clause needs to be with the <code>for</code> loop not <code>if</code> statement and no <code>break</code>.<br>
As pointed out 2 drops through immediately, which is perfectly okay as it is prime and the <code>else</code> clause is executed:</p>
<pre><code>total = 0
for num in range(2, 10): # Start from 2
for i in range(2, num):
if num%i==0:
break # Not prime, break causes else clause not to be executed
else:
total += num
print total
17
</code></pre>
<p>For very low numbers this will be fine, though you really only need to check to the sqrt of num.</p>
|
python|python-2.7|primes
| 2 |
1,906,291 | 12,885,797 |
Create a list from a string representing a list
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1926741/how-do-i-parse-a-string-representing-a-nested-list-into-an-actual-list">How do I parse a string representing a nested list into an actual list?</a> </p>
</blockquote>
<p>How could I get a list of errors from this string?</p>
<pre><code>>>> out = "<class 'api.exceptions.DataError'>:[u'Error 1', u'Another error']"
</code></pre>
<p>I tried using the json module but it didn't work.</p>
<pre><code>>>> import json
>>> errors = out.split(":")[-1]
>>> my_list = json.loads(errors)
</code></pre>
<p>I get this exception:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
</code></pre>
<p>Would you please suggest some way to adjust the code to get what I want?</p>
<p><strong>Edit: added the use case.</strong></p>
<p>The context where my question applies is:</p>
<pre><code>try:
# some code generating an xmlrpclib.Fault exception
pass
except xmlrpclib.Fault, err:
# here print dir(err) gives:
# ['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
# '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__',
# '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
# '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__',
# '__unicode__', '__weakref__', 'args', 'faultCode', 'faultString', 'message']
exit(err.faultString)
# exits with: "<class 'api.exceptions.DataError'>:[u'Error 1', u'Another error']"
</code></pre>
|
<p>You should use:</p>
<pre><code>import ast
ls="['a','b','c']"
ast.literal_eval(ls)
Out[178]: ['a', 'b', 'c']
</code></pre>
<p>or as a full:</p>
<pre><code>In [195]: ast.literal_eval(out.split(':')[1])
Out[195]: [u'Error 1', u'Another error']
</code></pre>
|
python|json|api|xmlrpcclient
| 4 |
1,906,292 | 64,573,496 |
create new dataframe out of selected row from multi dataframe pandas
|
<p>I have three dataframes. I want to select the row by date <code>2020-10-26</code> from all 3 dataframes and than I want to create a new dataframe. How to do it?</p>
<pre><code>import pandas as pd
from datetime import date
date1 = date.fromisoformat('2020-10-25')
date2 = date.fromisoformat('2020-10-26')
date3 = date.fromisoformat('2020-10-27')
for x in range(3):
df = pd.DataFrame([(date1,f'Stu{x}j', x+1, f'Varan{x}j', x*400+2),
(date2,f'aja{x}k', x+2, f'Del{x}j', x*634+3),
(date3,f'Aadi{x}t', x+4, f'Mumb{x}j', x*454+4),
(date2,f'har{x}h', x+5, f'bom{x}j', x*124+5)],
columns =['Date','Name', 'Age',
'City', 'Salary'])
df.set_index('Date', inplace = True)
print(df)
</code></pre>
|
<p>Below code would help you</p>
<pre><code>import pandas as pd
from datetime import date
date1 = date.fromisoformat('2020-10-25')
date2 = date.fromisoformat('2020-10-26')
date3 = date.fromisoformat('2020-10-27')
res = pd.DataFrame()
for x in range(3):
df = pd.DataFrame([(date1,f'Stu{x}j', x+1, f'Varan{x}j', x*400+2),
(date2,f'aja{x}k', x+2, f'Del{x}j', x*634+3),
(date3,f'Aadi{x}t', x+4, f'Mumb{x}j', x*454+4),
(date2,f'har{x}h', x+5, f'bom{x}j', x*124+5)],
columns =['Date','Name', 'Age',
'City', 'Salary'])
temp = df[df['Date'].isin([date2])]
res = res.append(temp)
print(res)
</code></pre>
<p>Old method:</p>
<pre><code>fr = [df1, df2, df3]
full = pd.concat(fr).reset_index()
full[full.Date.isin([date2])]
</code></pre>
|
python|pandas|dataframe
| 1 |
1,906,293 | 70,394,228 |
Detecting state mutation in Python
|
<p>Is there any way to detect state mutation in Python? I'm working on some software where all mutated state must be saved to an external database, and I'd like to write an automated test to detect state which has not been persisted.</p>
<p>More background on the problem: my software has a set of "worker" processes, and these processes can be restarted at any time. So it is necessary for a worker process to recover its state from the database if it is restarted.</p>
<p>My concern is that there may be state mutation which is not persisted to the database (and therefore not recovered when the worker is restarted). I'm wondering if there is any way to automatically defect this. I'd be happy to detect <em>all</em> state mutation and exclude that which I know is persisted to the database.</p>
|
<p>There is no "built-in" state change management as far as I know in Python. But something that will probably help you is the <a href="https://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">Observer Pattern</a>. To quote the beginning of the article :</p>
<blockquote>
<p>The observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.</p>
</blockquote>
<p>A typical solution is to have an <a href="https://docs.python.org/3/library/enum.html" rel="nofollow noreferrer">enumeration</a> of possible states. When an object changes state, you update the a state attribute through an enumeration and notify the observers.</p>
<pre class="lang-py prettyprint-override"><code>from enum import Enum, auto
class State(Enum):
START = auto()
ACTION = auto()
END = auto()
class MyObject: # observable
def __init__(self, conn):
self.observers = []
self.conn = conn
self.state = State.START
def subscribe(self, observer):
self.observers.append(observer)
def _notify(self):
for o in observers:
o.update()
def do_action(self, expr):
conn.execute(expr) # some SQL executed here
self.state = State.ACTION # update state
self._notify() # notify observers
def kill_conn(self):
conn.cancel()
self.state = State.END
self._notify()
class MyLogger: # observer
def __init__(self, my_object):
self.my_object = my_object
self.my_object.subscribe(self)
def update(self):
match self.my_object.state: # Python 3.10 structural pat matching
case State.START: pass # your code here
case State.ACTION: pass # your code here
case State.END: pass # write current object to log file?
case _: pass # 'default' behavior is catching the rest fails
</code></pre>
|
python|immutability
| 0 |
1,906,294 | 72,887,261 |
I don't understand this error, "Message: unknown error: net::ERR_CONNECTION_RESET" ? Selenium
|
<p>I'm trying to take screenshot from specifics urls
It actually works with some Urls but not all of them.</p>
<p>Here is the error I have with this url</p>
<p>(<a href="https://candidat.pole-emploi.fr/offres/recherche/detail/136QBXM" rel="nofollow noreferrer">https://candidat.pole-emploi.fr/offres/recherche/detail/136QBXM</a>) :</p>
<pre><code>Traceback (most recent call last):
2022-07-05T02:07:36.878958+00:00 app[worker.1]:
File "/app/main.py", line 132, in <module>
2022-07-05T02:07:36.879133+00:00 app[worker.1]:
driver.get("https://candidat.pole-emploi.fr/offres/recherche/detail/136QBXM")
2022-07-05T02:07:36.879146+00:00 app[worker.1]:
File"/app/.heroku/python/lib/python3.10/site-
packages/selenium/webdriver/remote/webdriver.py", line 447, in get
2022-07-05T02:07:36.879379+00:00 app[worker.1]:self.execute(Command.GET, {'url': url})
2022-07-05T02:07:36.879389+00:00 app[worker.1]:
File"/app/.heroku/python/lib/python3.10/site-
packages/selenium/webdriver/remote/webdriver.py", line 435, in execute
2022-07-05T02:07:36.879613+00:00
app[worker.1]:self.error_handler.check_response(response)
2022-07-05T02:07:36.879625+00:00 app[worker.1]:
File"/app/.heroku/python/lib/python3.10/
sitepackages/selenium/webdriver/remote/errorhandler.py", line 247, in
check_response
2022-07-05T02:07:36.879775+00:00 app[worker.1]: raise
exception_class(message, screen, stacktrace)
2022-07-05T02:07:36.879808+00:00 app[worker.1]:
selenium.common.exceptions.WebDriverException: Message: unknownerror:net::ERR_CONNECTION_RESET
</code></pre>
<p>Here is my code :</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from PIL import Image
import io
from PIL import ImageOps
op=webdriver.ChromeOptions()
op.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
op.add_argument("--headless")
op.add_argument("--no-sandbox")
op.add_argument("--disable-dev-sh-usage")
op.add_argument("start-maximized")
driver =webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"),options=op)
driver.get('https://candidat.pole-emploi.fr/offres/recherche/detail/136QBXM/')
WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH,'//*
[@id="footer_tc_privacy_button_2"]'))).click()
ac = driver.get_screenshot_as_png()
file_like_object = io.BytesIO(ac)
im = Image.open(file_like_object)
img_byte_arr = io.BytesIO()
file_like_object.save(img_byte_arr, format='PNG')
</code></pre>
<p><strong>What is the problem with my code? Are there any alternatives ?</strong></p>
|
<p>The reason for this error is that the connection couldn't be established.
I'll suggest to:</p>
<ul>
<li>validate the page is reachable</li>
<li>validate proxi rules</li>
<li>make sure firewall in not blocking</li>
<li>clear browser cache</li>
</ul>
<p>probably this may help you to shortcut the issue</p>
|
python|selenium|selenium-webdriver|selenium-chromedriver
| 0 |
1,906,295 | 72,979,325 |
Unable to read csv file on Google Colab
|
<p>I'm trying to read a sample dataset from Kaggle on Google Colab. I've tried to read the csv file by uploading it to my Google Drive as well as by loading it to my ipynb using the Kaggle API.</p>
<p>This is the command I'm trying:</p>
<pre><code>df=pd.read_csv("/content/quality/MiningProcess_Flotation_Plant_Database.csv",usecols=need_cols,dtype=data_dir)
</code></pre>
<p>For some weird reason, the error message is from the very first command I've given.</p>
<p><strong>TypeError: data type 'quality-prediction-in-a-mining-process' not understood</strong></p>
<p>Since then, I've tried to rename the folder. I've also tried reconnecting the runtime.</p>
<p><a href="https://i.stack.imgur.com/LGdlf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LGdlf.png" alt="Screenshot of the error" /></a></p>
|
<p>Try removing dtype and use this instead:</p>
<pre><code>df=pd.read_csv("/content/quality/MiningProcess_Flotation_Plant_Database.csv",usecols=[0,1])
</code></pre>
<p>need_cols should be like [0,1]</p>
|
python|pandas|csv|google-colaboratory
| 0 |
1,906,296 | 73,420,012 |
Attempting to add '$' before number
|
<p>Need a bit of help adding <code>$</code> right before each number is printed while also keeping the whole text centered, as of now the <code>$</code> gets pushed a bit further away then the price does cause of the <code>{:10}</code>.</p>
<p>I'm just starting so maybe there is an easy fix but I've attempted to use the .join method as well only for the whole text to be replaced with <code>$</code>, also using f-strings although I doubt that would make that much of an difference in me finding a solution. Had to write this cause it made me add more details to this.</p>
<pre><code>def centered_text(text: str = " ", width: int = 50) -> None:
"""
text: Text we want to print out
width: Max characters text can be
return: Return text centered
"""
if len(text) > width - 4:
print("Invalid choice, you put {} characters".format((len(text) - width)))
if text == "*":
print("*" * width)
else:
centered = text.center(width - 4)
output_sting = "**{}**".format(centered)
print(output_sting)
cart = []
special_items = {'Metal pipe': 5.99,
'Large table': 30.99,
'Battle ship': 12.99,
'Gaming PC': 1599.99,
'24-Pack of water': 19.99,
'Dog chew toy': 4.99,
'Space Ice cream': 8.99,
'Nerf gun': 10.99,
'Pokemon cards': 6.99,
'Desk': 49.99}
print("Welcome to Amazon, we have some special offers for you! Please enjoy these offers from the list below!")
centered_text("*")
for item, price in special_items.items():
x = "{:20} ${:10}".format(item, price)
centered_text(x)
centered_text("*")
</code></pre>
<p>Output should be something like this:</p>
<pre class="lang-none prettyprint-override"><code>**************************************************
** Metal pipe $5.99 **
** Large table $30.99 **
** Battle ship $12.99 **
** Gaming PC $1599.99 **
** 24-Pack of water $19.99 **
** Dog chew toy $4.99 **
** Space Ice cream $8.99 **
** Nerf gun $10.99 **
** Pokemon cards $6.99 **
** Desk $49.99 **
**************************************************
</code></pre>
|
<p>You need to add the <code>$</code> sign as part of the object being formatted.</p>
<pre class="lang-py prettyprint-override"><code>for item, price in special_items.items():
x = "{:20} {:>10}".format(item, f"${price}")
centered_text(x)
</code></pre>
<p>Here I just changed <code>price</code> to <code>f"${price}"</code>. That <code>></code> in <code>{:>10}</code> is for right alignment.</p>
<p>To be consistent in two decimal digit you can use <code>f"${price:.2f}</code></p>
|
python|python-3.x
| 2 |
1,906,297 | 66,498,142 |
How can I update subscriber tags using mailchimp3 for Python?
|
<p>I am trying to update the tags for members of a MailChimp list using the mailchimp3 package/API on a regular basis using purchase data from an external source. The tags need to be updated weekly based on recent purchases by customers. Sample data is below:</p>
<pre><code>original_contacts = pd.DataFrame{'First Name': {0: 'Michael',
1: 'James',
2: 'Josephine',
3: 'Art',
4: 'Lenna'},
'Last Name': {0: 'Ox',
1: 'Butt',
2: 'Darakjy',
3: 'Venere',
4: 'Paprocki'},
'Email': {0: 'mox@gmail.com',
1: 'jbutt@gmail.com',
2: 'josephine_darakjy@darakjy.org',
3: 'art@venere.org',
4: 'lpaprocki@hotmail.com'},
'Account Name': {0: 'Lenixi, Co.',
1: 'Lenixi, Co.',
2: 'Lenixi, Co.',
3: 'Fouray, Co.',
4: 'Fouray, Co.'},
'Purchase': {0: 'No Purchase',
1: 'No Purchase',
2: 'No Purchase',
3: 'Purchase',
4: 'No Purchase'}}
</code></pre>
<p>I have successfully been able to create new members and update the merge fields of existing members using this script that I modified from <a href="https://stackoverflow.com/questions/42828112/python-adding-subscribers-to-mailchimp-with-bulk-api-v3">this post</a>:</p>
<pre><code>list_id = '123456'
operations = []
for index, row in original_contacts.iterrows():
databody_item = {'email_address': row['Email'],
'status': 'subscribed',
'merge_fields': {
'FNAME': row['First Name'],
'LNAME': row['Last Name'],
'COMPANY': row['Account Name'],
},
'tags': [row['Purchase']]
}
operations.append(databody_item)
def upload_list(list_id, subscribers_data):
data = {'operations': create_subscriptions_data(list_id, subscribers_data)}
client.batches.create(data)
def create_subscriptions_data(list_id, users_data):
return [{'method': 'PUT',
'path': 'lists/{}/members/{}'.format(list_id, user['email_address']),
'body': json.dumps(user)} for user in users_data]
upload_list(list_id, operations)
</code></pre>
<p>The script above will create a tag for a new member, but does not update tags for existing members. I have also tried variations of the code below to see if I can update the tags for a single member, but have had no success:</p>
<pre><code>client.lists.members.tags.update(list_id = list_id, subscriber_hash='xxxxxxxxxxx', data = {'tags': [{'name': 'Purchase'}]})
</code></pre>
<p>This does not throw any errors, but also doesn't do anything to existing tags.</p>
<p>The only solution I have come up with is deleting all existing tags manually and updating every single contact with new tags. However, this is extremely inefficient and I would like to 1) avoid updating tags that haven't changed and 2) want to accomplish everything within my app.</p>
<p>All help is greatly appreciated! Thanks in advance!</p>
|
<p>You cannot update the tags for a user via a patch. It only works as describes in the documentation when you are adding a new subscriber.</p>
<p>I talked to Mailchimp and suggested they at least make that clearer in the documentation.</p>
|
python|mailchimp|mailchimp-api-v3.0|mailchimp-api-v3
| 0 |
1,906,298 | 64,875,956 |
The code runs on one pc but not on the other with the same version of python : python config problem?
|
<p>We work at 2 on a project in which we implement TCP mechanisms over UDP connexion. But it seems I have a python config problem. Both of us use Python 3. But the code does work for the other person and not for me.</p>
<p><a href="https://i.stack.imgur.com/JWSvr.png" rel="nofollow noreferrer">Here is what I obtain when I run the code</a></p>
<p>And here are my codes :</p>
<p>-server.py</p>
<pre><code>
IP = "127.0.0.1"
PORT_A = 7007
PORT_B = 6006
SYN_ACK = b"SYN_ACK6006"
END = b"END"
MAXLINE = 1024
buffer_fichier = bytearray()
buffer_ack = bytearray()
nb_segment = 0
timeout = 0.2
#socket creation
try:
socket_connect = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print("socket creation failed")
exit()
try:
socket_transfer = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print("socket creation failed")
exit()
socket_transfer.setblocking(0)
#socket bind
try:
socket_connect.bind((IP, PORT_A))
except socket.error:
print("socket bind failed")
exit()
print("Server waiting for a client")
#tree handshake connection
data, addr = socket_connect.recvfrom(1024)
print("Client: %s" % data)
socket_connect.sendto(SYN_ACK, addr)
print("ME: SYN_ACK")
data, addr = socket_connect.recvfrom(1024)
print("Client: %s" % data)
#open file and put it in a buffer
my_file = open("image.jpg", "rb")
bytes = my_file.read()
my_file.close()
for elem in bytes:
buffer_fichier.append(elem)
size = len(buffer_fichier)
#file sending
for i in range(0,size,MAXLINE):
buffer_segment = bytearray()
buffer_segment.append(nb_segment)
for j in range(i, i + MAXLINE):
if j < size:
buffer_segment.append(buffer_fichier[j])
else:
break
socket_transfer.sendto(buffer_segment, (IP, PORT_B))
nb_segment += 1
ready = select.select([socket_transfer], [], [], timeout)
if ready[0]:
data, addr = socket_transfer.recvfrom(1)
else:
print("pas de ack recu, probleme")
buffer_ack.append(data)
socket_transfer.sendto(END, (IP, PORT_B))
print("File of %d bytes received" % os.path.getsize("image.jpg"))
print("nb of ack received %d" % len(buffer_ack))
</code></pre>
<p>-client.py</p>
<pre><code>
IP = "127.0.0.1"
PORT_A = 7007
SYN = str.encode("SYN")
ACK = str.encode("ACK")
buffer_ack = bytearray()
#function to slip text and integer in a string
def text_num_split(item):
for index, letter in enumerate(item, 0):
if letter.isdigit():
return [item[:index],item[index:]]
#socket creation
try:
socket_connect = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print("socket creation failed")
exit()
try:
socket_transfer = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print("socket creation failed")
exit()
#tree handshake connexion
socket_connect.sendto(SYN, (IP, PORT_A))
print("Me: SYN")
data, addr = socket_connect.recvfrom(1024)
msg = text_num_split(data)
PORT_B= int(msg[1])
print("Server: %s" % data)
try:
socket_transfer.bind((IP, PORT_B)) #on bind la socket pour qu'elle ecoute
except socket.error: #sur le port ou le serveur envoie le fichier
print("socket bind failed")
exit()
socket_connect.sendto(ACK, addr)
print("Me: ACK")
#Receive file
my_file = open('my_file', 'w+b')
while True:
data, addr = socket_transfer.recvfrom(1025)
if(data == "END"):
break
else:
data = bytearray(data)
buffer_ack.append(data[0])
ack = str(data[0])
socket_transfer.sendto(ack, addr)
data.pop(0)
my_file.write(data)
my_file.close()
print("File of %d bytes sent" % os.path.getsize('my_file'))
print("nb of ack sent %d" % len(buffer_ack))
</code></pre>
<p>Does anyone see where the problem could be coming from ?</p>
<p>Thanks and have a nice day</p>
<p>Charlotte</p>
|
<p>The Problem is your <code>text_num_split</code> which assumes you pass it a <code>string</code>, you however pass a <code>bytestring</code>.<br>
A <code>bytestring</code> will be cast to <code>ints</code> by <code>enumerate</code>. <br></p>
<p>To fix this add this line to your <code>text_num_split</code></p>
<pre><code>item = item.decode("utf-8")
</code></pre>
|
python|python-3.x|sockets|configuration|config
| 0 |
1,906,299 | 63,993,139 |
How to split a list into two random parts
|
<p>I have 12 people who i need to divide into 2 different teams. What i need to do is pick random 6 numbers between 0 and 11 for the first team and do the same for the second one with no overlap. What is the most efficient way to do this?</p>
<pre><code>import random
A = random.choice([x for x in range(12)])
B = random.choice([x for x in range(12) if x != A])
C = random.choice([x for x in range(12) if (x != A) and (x != B)])
team1 = random.sample(range(0, 12), 6)
team2 = random.sample(range(0, 12), 6)
</code></pre>
<p>This is what i wrote so far.
Any help is appreciated.</p>
|
<p>You can use <code>set</code>s and <a href="https://docs.python.org/3/library/stdtypes.html#frozenset.difference" rel="noreferrer">set difference</a>, like this:</p>
<pre class="lang-py prettyprint-override"><code>import random
all_players = set(range(12))
team1 = set(random.sample(all_players, 6))
team2 = all_players - team1
print(team1)
print(team2)
</code></pre>
<p>Example Output:</p>
<pre><code>{1, 5, 8, 9, 10, 11}
{0, 2, 3, 4, 6, 7}
</code></pre>
|
python|list|random
| 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.