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,902,800 | 60,869,306 |
How to simple crop the bounding box in python opencv
|
<p>I am trying to learn opencv and implementing a research project by testing some used cases. I am trying to crop the bounding box of the inside the image using python opencv . I have successfully created the bounding box but failed in crop</p>
<p>this is the image </p>
<p><a href="https://i.stack.imgur.com/Vb3mO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Vb3mO.png" alt="enter image description here"></a></p>
<pre><code>import cv2
import matplotlib.pyplot as plt
img = cv2.imread("Segmentacion/Img_183.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dst = cv2.Canny(gray, 0, 150)
blured = cv2.blur(dst, (5,5), 0)
MIN_CONTOUR_AREA=200
img_thresh = cv2.adaptiveThreshold(blured, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
Contours,imgContours = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for contour in Contours:
if cv2.contourArea(contour) > MIN_CONTOUR_AREA:
[X, Y, W, H] = cv2.boundingRect(contour)
box=cv2.rectangle(img, (X, Y), (X + W, Y + H), (0,0,255), 2)
cropped_image = img[X:W, Y:H]
print([X,Y,W,H])
cv2.imwrite('contour.png', cropped_image )
</code></pre>
|
<p>I figured it out the formula for cropping the bounding box from the original image</p>
<pre><code>cropped_image = img[Y:Y+H, X:X+W]
print([X,Y,W,H])
plt.imshow(cropped_image)
cv2.imwrite('contour1.png', cropped_image)
</code></pre>
|
python|opencv|image-processing
| 21 |
1,902,801 | 65,956,940 |
ord () expected a character
|
<p>I want to decrypt the code via a txt file. But I got an error ord () expected a character, but a string of length 586 was found. Any suggestions for fix it? (i use python 3.9)</p>
<pre><code>def decrypt(string, shift):
cipher = ''
for char in string:
if char == ' ':
cipher = cipher + char
elif char.isupper():
cipher = cipher + chr((ord(char) - shift - 65) % 26 + 65)
else:
cipher = cipher + chr((ord(char) - shift - 97) % 26 + 97)
return cipher
text = open(input("enter string: "))
s = int(input("enter shift number: "))
print("original string: ", text)
print("after decryption: ", decrypt(text, s))
</code></pre>
|
<p><code>text</code> is an iterable that produces a sequence of strings, one per line from the file. As a result, <code>char</code> is an entire line of the file, not a single character of a given line.</p>
<p><code>decrypt</code> is fine (though you should use the <code>join</code> method rather than repeatedly appending characters to a growing string); it's your use of <code>text</code> that needs to be fixed.</p>
<pre><code>text = open(input("enter string: "))
s = int(input("enter shift number: "))
for line in text:
print("original string: ", line)
print("after decryption: ", decrypt(line, s))
</code></pre>
<p>If you want the entire file as a single string, call its <code>read</code> method directly:</p>
<pre><code>text = open(input("enter string: "))<b>.read()</b>
s = int(input("enter shift number: "))
print("original string: ", text)
print("after decryption: ", decrypt(text, s))</code></pre>
<p>(I'm deliberately ignoring any <code>str</code>-vs-<code>bytes</code> issues regarding the use of the data read from <code>text</code>.)</p>
|
python|caesar-cipher
| 3 |
1,902,802 | 66,083,259 |
Fractal design for svg file
|
<p>I'm very new to coding and I am attempting to create a box svg file with a fractal spiral design on one of the box wings. I'm having a difficult time with this and I'm hoping someone can offer some guidance as to where I'm going wrong.</p>
<p>Here is part of my code:</p>
<pre><code>import turtle
def spiral(x, y):
spiral1 = turtle.setpos({},{})
return spiral1.format(x,y)
t = turtle.Turtle()
t.pensize(1)
t.pencolor('orange')
t.speed(0)
for i in range (10):
t.circle(10 + i, 45)
spiral_1 = spiral(int(box_x)*96, int(box_height)*96)
</code></pre>
<p>this is giving me an error:unsupported operand type(s) for * 'dict' and 'float'</p>
<p>Essentially what I want to do is write this spiral onto my actual svg file which has specific coordinates I've already defined (i.e box_height)). I'm not quite sure where to go from here. I'd really appreciate your help.</p>
<p>Edit: perhaps I need to figure out how to generate the pattern with svg code rather than turtle</p>
|
<blockquote>
<p>I'm hoping someone can offer some guidance as to where I'm going wrong</p>
</blockquote>
<p>I'm having a hard time figuring out where you went <em>right</em>:</p>
<pre><code>spiral1 = turtle.setpos({},{})
</code></pre>
<p>This doesn't appear to be Python argument syntax and <code>setpos()</code> always returns <code>None</code> so there's no point in saving the result into <code>spiral1</code>.</p>
<pre><code>return spiral1.format(x,y)
</code></pre>
<p><code>None</code> doesn't have a <code>format()</code> method. Also, the <code>return</code> at this point in the code causes it to ignore the next six lines of code. Effectively, not drawing at all.</p>
<pre><code>spiral_1 = spiral(int(box_x)*96, int(box_height)*96)
</code></pre>
<p><code>spiral()</code> doesn't return anything useful, so no point saving the result. Let's rework your code so that it actually draws a spiral:</p>
<pre><code>from turtle import Screen, Turtle
box_x, box_y = 96, 96
def spiral(x, y):
turtle.penup()
turtle.setposition(x, y)
turtle.pendown()
for i in range(100):
turtle.circle(10 + i, 45)
screen = Screen()
turtle = Turtle()
turtle.pencolor('orange')
turtle.speed('fastest')
spiral(box_x, box_y)
screen.exitonclick()
</code></pre>
<p>I don't see why this question is tagged [fractals]. Nor do I see why it's tagged [xml] and [svg] as it's a simple Python syntax and turtle graphics question. And you really shouldn't be getting started with Python 2.7 as it is no longer supported.</p>
<p><a href="https://i.stack.imgur.com/dMljC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dMljC.png" alt="enter image description here" /></a></p>
|
python|python-2.7|turtle-graphics
| 1 |
1,902,803 | 69,092,512 |
PYODBC pass variable in connection string
|
<p>I'm trying to connect to MS Access database (.mdb) with pyodbc. The following connection string works properly:</p>
<pre><code>conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=\\abc123.org\Team\Resources\Inputs\Accounts.mdb;')
</code></pre>
<p>I need to iterate over several files, so I'm trying to pass a variable in for the file path. Variables will come from a list but as an example:</p>
<pre><code>file_path1 = '\\abc123.org\Team\Resources\Inputs\Accounts.mdb'
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ={};').format(file_path1)
</code></pre>
<p>I receive the following error:
Error: ('HY000', '[HY000] [Microsoft][ODBC Microsoft Access Driver] Not a valid file name. (-1044) (SQLDriverConnect); [HY000] [Microsoft][ODBC Microsoft Access Driver] Not a valid file name. (-1044)')</p>
<p>I receive the same error when trying:</p>
<pre><code>conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;') % file_path1
</code></pre>
<p>Would appreciate any help on how to pass the file path as a variable in the connection string, thank you!</p>
|
<p>I think I got it.</p>
<pre><code>file_path1 = '\\abc123.org\Team\Resources\Inputs\Accounts.mdb'
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ={};'.format(file_path1))
#^ format method is call on the string
</code></pre>
<p>Can you spot the difference ?</p>
<p>What you where doing was to call format on the <code>connect</code> method.
You have the same issue on the 2nd try too</p>
<pre><code>conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;' % file_path1)
#^ I have moved the parenthesis
</code></pre>
|
python|ms-access|pyodbc
| 0 |
1,902,804 | 68,874,634 |
cv2.error : OpenCV(4.5.3) Error: bad argument & overload resolution failed in cv.line
|
<p>I have a simple project with Raspi 4 with camera which the project is similar with car's reverse camera but without sensor. Here my code:</p>
<pre class="lang-python prettyprint-override"><code>import time
import cv2
import numpy as np
from picamera.array import PiRGBArray
from picamera import PiCamera
camera = PiCamera()
camera.resolution = (1080, 720) # camera resolution
camera.framerate = 25
rawCapture = PiRGBArray(camera, size=(1080,720))
kernel = np.ones((2,2),np.uint8)
time.sleep(0.1)
for still in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
image = still.array
#create a detection area
widthAlert = np.size(image, 1) #get width of image
heightAlert = np.size(image, 0) #get height of image
yAlert = (heightAlert/2) + 100 #determine y coordinates for area
cv2.line(image, (0,yAlert), (widthAlert,yAlert),(0,0,255),2) #draw a line to show area
lower = [1, 0, 20]
upper = [60, 40, 200]
lower = np.array(lower, dtype="uint8")
upper = np.array(upper, dtype="uint8")
#use the color range to create a mask for the image and apply it to the image
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask=mask)
dilation = cv2.dilate(mask, kernel, iterations = 3)
closing = cv2.morphologyEx(dilation, cv2.MORPH_GRADIENT, kernel)
closing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel)
edge = cv2.Canny(closing, 175, 175)
contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
threshold_area = 400
centres = []
if len(contours) !=0:
for x in contours:
#find the area of each contour
area = cv2.contourArea(x)
#find the center of each contour
moments = cv2.moments(x)
#weed out the contours that are less than our threshold
if area > threshold_area:
(x,y,w,h) = cv2.boundingRect(x)
centerX = (x+x+w)/2
centerY = (y+y+h)/2
cv2.circle(image,(centerX, centerY), 7, (255, 255, 255), -1)
if ((y+h) > yAlert):
cv2.putText(image, "ALERT!", (centerX -20, centerY -20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255),2)
cv2.imshow("Display", image)
rawCapture.truncate(0)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
</code></pre>
<p>The error i got is in:</p>
<pre class="lang-python prettyprint-override"><code> image = still.array
#create a detection area
widthAlert = np.size(image, 1) #get width of image
heightAlert = np.size(image, 0) #get height of image
yAlert = (heightAlert/2) + 100 #determine y coordinates for area
cv2.line(image, (0,yAlert), (widthAlert,yAlert),(0,0,255),2) #draw a line to show area
</code></pre>
<p>The problem is:
Traceback (most recent call last): File "/home/pi/Desktop/object_detector.py", line 20, in </p>
<p>cv2.line(image, (0,yAlert), (widthAlert,yAlert),(0,0,255),2) #draw a line to show area</p>
<p>cv2.error: OpenCV(4.5.3) error: (-5:Bad argument) in function 'line'</p>
<p>Overload resolution failed:</p>
<p>-can't parse 'pt1'. Sequence item with index 1 has wrong type</p>
<p>-can't parse 'pt1'. Sequence item with index 1 has wrong type</p>
|
<p>The value assigned to pt1 and pt2 should not have a floating point.</p>
<p>So this is working fine.</p>
<pre class="lang-py prettyprint-override"><code>import cv2
import numpy as np
h,w=100,100
im = ~np.zeros((h,w,3), np.uint8)
cv2.line(im, (0,10), (100,100),(0,0,255),2)
cv2.imshow('line',im)
cv2.waitKey(0)
</code></pre>
<p>Now if you change this line</p>
<pre class="lang-py prettyprint-override"><code>cv2.line(im, (0,10), (100,100),(0,0,255),2)
</code></pre>
<p>to this</p>
<pre class="lang-py prettyprint-override"><code>cv2.line(im, (0,10.1), (100,100),(0,0,255),2)
#OR
cv2.line(im, (0,10), (100,100.1),(0,0,255),2)
</code></pre>
<p>For the first one you get</p>
<blockquote>
<p>Can't parse 'pt1'. Sequence item with index 1 has a wrong type</p>
</blockquote>
<p>and for second one you get</p>
<blockquote>
<p>Can't parse 'pt2'. Sequence item with index 1 has a wrong type</p>
</blockquote>
<p>To fix this I can change</p>
<pre class="lang-py prettyprint-override"><code>cv2.line(im, (0,10.1), (100,100),(0,0,255),2)
</code></pre>
<p>to</p>
<pre class="lang-py prettyprint-override"><code>cv2.line(im, (0,int(10.1)), (100,100),(0,0,255),2)
</code></pre>
|
python-3.x|numpy|opencv
| 1 |
1,902,805 | 72,802,915 |
Databricks AutoML - dataset upload
|
<p>Whenever I upload a dataset into Databricks to run an AutoML experiment, Databricks automatically truncates the dataset to 1000 rows. Is there any way that I can, for example, upload a dataset with 9000+ rows into the data section of Databricks?</p>
<p>Thanks!</p>
|
<p>Databricks is sampling dataset to avoid out-of-memory issues.</p>
<p>If you are using Databricks Runtime 9.1 LTS ML or above, AutoML automatically samples your dataset if it is too large to fit into the memory of a single worker node.</p>
<p><strong>Workaround –</strong></p>
<p>Try to select Worker type with more memory.</p>
<p><a href="https://i.stack.imgur.com/0lnJt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0lnJt.png" alt="enter image description here" /></a></p>
<p>Refer - <a href="https://docs.microsoft.com/en-us/azure/databricks/applications/machine-learning/automl#limitations" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/databricks/applications/machine-learning/automl#limitations</a></p>
|
python|dataset|azure-databricks|automl
| 0 |
1,902,806 | 59,134,773 |
How to fine tune resnet50 with float16 in Keras?
|
<p>I'm trying to fine tune resnet50 in half precision mode without success. It seems there are parts of model which are not compatible with <code>float16</code>. Here is my code:</p>
<pre class="lang-py prettyprint-override"><code>dtype='float16'
K.set_floatx(dtype)
K.set_epsilon(1e-4)
model = Sequential()
model.add(ResNet50(weights='imagenet', include_top=False, pooling='avg'))
</code></pre>
<p>and I get this error:</p>
<pre><code>Traceback (most recent call last):
File "train_resnet.py", line 40, in <module>
model.add(ResNet50(weights='imagenet', include_top=False, pooling='avg'))
File "/usr/local/lib/python3.6/dist-packages/keras/applications/__init__.py", line 28, in wrapper
return base_fun(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/keras/applications/resnet50.py", line 11, in ResNet50
return resnet50.ResNet50(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/keras_applications/resnet50.py", line 231, in ResNet50
x = layers.BatchNormalization(axis=bn_axis, name='bn_conv1')(x)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py", line 457, in __call__
output = self.call(inputs, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/keras/layers/normalization.py", line 185, in call
epsilon=self.epsilon)
File "/usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py", line 1864, in normalize_batch_in_training
epsilon=epsilon)
File "/usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py", line 1839, in _fused_normalize_batch_in_training
data_format=tf_data_format)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/nn_impl.py", line 1329, in fused_batch_norm
name=name)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_nn_ops.py", line 4488, in fused_batch_norm_v2
name=name)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py", line 626, in _apply_op_helper
param_name=input_name)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py", line 60, in _SatisfiesTypeConstraint
", ".join(dtypes.as_dtype(x).name for x in allowed_list)))
TypeError: Value passed to parameter 'scale' has DataType float16 not in list of allowed values: float32
</code></pre>
|
<p>This was a <a href="https://github.com/keras-team/keras/issues/11989" rel="nofollow noreferrer">reported bug</a> and upgrading to <code>Keras==2.2.5</code> solved the issue.</p>
|
python|keras
| 1 |
1,902,807 | 73,075,589 |
Resize imshow output
|
<p>I have the following code below pasted below. When I run the <code>cv2.imshow('img', image)</code> located at the bottom of the code, the size of the output exceeds my screen. How do I resize the output to an e.g 900 size screen? I have looked at many forums but they don't seem to fix this. Please could someone help</p>
<pre class="lang-py prettyprint-override"><code># Import required modules
import cv2
import numpy as np
import os
import glob
# Define the dimensions of checkerboard
CHECKERBOARD = (9, 6)
# stop the iteration when specified
# accuracy, epsilon, is reached or
# specified number of iterations are completed.
criteria = (cv2.TERM_CRITERIA_EPS +
cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Vector for 3D points
threedpoints = []
# Vector for 2D points
twodpoints = []
# 3D points real world coordinates
objectp3d = np.zeros((1, CHECKERBOARD[0]
* CHECKERBOARD[1],
3), np.float32)
objectp3d[0, :, :2] = np.mgrid[0:CHECKERBOARD[0],
0:CHECKERBOARD[1]].T.reshape(-1, 2)
prev_img_shape = None
# Extracting path of individual image stored
# in a given directory. Since no path is
# specified, it will take current directory
# jpg files alone
images = glob.glob('*.jpeg')
for filename in images:
print(filename)
image = cv2.imread(filename)
grayColor = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Find the chess board corners
# If desired number of corners are
# found in the image then ret = true
ret, corners = cv2.findChessboardCorners(
grayColor, CHECKERBOARD,
cv2.CALIB_CB_ADAPTIVE_THRESH
+ cv2.CALIB_CB_FAST_CHECK +
cv2.CALIB_CB_NORMALIZE_IMAGE)
# If desired number of corners can be detected then,
# refine the pixel coordinates and display
# them on the images of checker board
if ret == True:
threedpoints.append(objectp3d)
# Refining pixel coordinates
# for given 2d points.
corners2 = cv2.cornerSubPix(
grayColor, corners, (11, 11), (-1, -1), criteria)
twodpoints.append(corners2)
# Draw and display the corners
image = cv2.drawChessboardCorners(image,
CHECKERBOARD,
corners2, ret)
cv2.imshow('img', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
|
<p>You need to call <code>cv.namedWindow()</code> <strong>with appropriate flags</strong>. Try <code>cv.WINDOW_NORMAL</code>. That's a good default.</p>
<p><em>Then</em> the window is resizable. Use <code>cv.resizeWindow()</code> to set an exact size.</p>
<p>This <em>does not require resizing</em> the image itself. The GUI handles that.</p>
|
python|opencv|imshow
| 1 |
1,902,808 | 62,209,331 |
Trying to open up Chrome Web driver, it opens and closes
|
<p>So when I open try to run it like this it works, but when i try to run it in my class it opens and closes</p>
<pre><code>from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
driver.get("https://instagram.com")
##But when I try it In my class it opens and closes,
from selenium import webdriver
from time import sleep
class InstaBot:
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.get("http://google.com")
InstaBot()```
</code></pre>
|
<p>I think you had not created a Instance of Class. Try this one.</p>
<pre><code>from selenium import webdriver
class MyClass():
def __init__(self):
self.driverpath = "C:/browserdrivers/chromedriver.exe"
def open_browser(self):
self.driver = webdriver.Chrome(self.driverpath)
def open_site(self, url):
self.driver.get(url)
c = MyClass()
c.open_browser()
c.open_site('https://instagram.com')
</code></pre>
|
python|selenium-chromedriver
| 0 |
1,902,809 | 35,596,571 |
Python Tkinter: adding a scrollbar to frame within a canvas
|
<p>I am quite new to Tkinter, but, nevertheless, I was asked to "create" a simple form where user could provide info about the status of their work (this is sort of a side project to my usual work).
Since I need to have quite a big number of text widget (where users are required to provide comments about status of documentation, or open issues and so far), I would like to have something "scrollable" (along the y-axis).</p>
<p>I browsed around looking for solutions and after some trial and error I found something that works quite fine.
Basically I create a canvas, and inside a canvas a have a scrollbar and a frame. Within the frame I have all the widgets that I need.</p>
<p>This is a snipet of the code (with just some of the actual widgets, in particular the text ones):</p>
<pre><code>from Tkinter import *
## My frame for form
class simpleform_ap(Tk):
# constructor
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.initialize()
#
def initialize(self):
#
self.grid_columnconfigure(0,weight=1)
self.grid_rowconfigure(0,weight=1)
#
self.canvas=Canvas(self.parent)
self.canvas.grid(row=0,column=0,sticky='nsew')
#
self.yscrollbar = Scrollbar(self,orient=VERTICAL)
self.yscrollbar.grid(column =4, sticky="ns")
#
self.yscrollbar.config(command=self.canvas.yview)
self.yscrollbar.pack(size=RIGTH,expand=FALSE)
#
self.canvas.config(yscrollcommand=self.yscrollbar.set)
self.canvas.pack(side=LEFT,expand=TRUE,fill=BOTH)
#
self.frame1 = Frame(self.canvas)
self.canvas.create_window(0,0,window=self.frame1,anchor='nw')
# Various Widget
# Block Part
# Label
self.labelVariableIP = StringVar() # Label variable
labelIP=Label(self.frame1,textvariable=self.labelVariableIP,
anchor="w",
fg="Black")
labelIP.grid(column=0,row=0,columnspan=1,sticky='EW')
self.labelVariableIP.set(u"IP: ")
# Entry: Single line of text!!!!
self.entryVariableIP =StringVar() # variable for entry field
self.entryIP =Entry(self.frame1,
textvariable=self.entryVariableIP,bg="White")
self.entryIP.grid(column = 1, row= 0, sticky='EW')
self.entryVariableIP.set(u"IP")
# Update Button or Enter
button1=Button(self.frame1, text=u"Update",
command=self.OnButtonClickIP)
button1.grid(column=2, row=0)
self.entryIP.bind("<Return>", self.OnPressEnterIP)
#...
# Other widget here
#
# Some Text
# Label
self.labelVariableText = StringVar() # Label variable
labelText=Label(self.frame1,textvariable=
self.labelVariableText,
anchor="nw",
fg="Black")
labelText.grid(column=0,row=curr_row,columnspan=1,sticky='EW')
self.labelVariableTexta.set(u"Insert some texts: ")
# Text
textState = TRUE
self.TextVar=StringVar()
self.mytext=Text(self.frame1,state=textState,
height = text_height, width = 10,
fg="black",bg="white")
#
self.mytext.grid(column=1, row=curr_row+4, columnspan=2, sticky='EW')
self.mytext.insert('1.0',"Insert your text")
#
# other text widget here
#
self.update()
self.geometry(self.geometry() )
self.frame1.update_idletasks()
self.canvas.config(scrollregion=(0,0,
self.frame1.winfo_width(),
self.frame1.winfo_height()))
#
def release_block(argv):
# Create Form
form = simpleform_ap(None)
form.title('Release Information')
#
form.mainloop()
#
if __name__ == "__main__":
release_block(sys.argv)
</code></pre>
<p>As I mentioned before, this scripts quite does the work, even if, it has a couple of small issue that are not "fundamental" but a little annoying.</p>
<p>When I launch it I got this (sorry for the bad screen-capture):
<a href="http://i.stack.imgur.com/sjcZ4.png" rel="nofollow">enter image description here</a></p>
<p>As it can be seen, it only shows up the first "column" of the grid, while I would like to have all them (in my case they should be 4)
To see all of the fields, I have to resize manually (with the mouse) the window.
What I would like to have is something like this (all 4 columns are there):
<a href="http://i.stack.imgur.com/DRRVA.png" rel="nofollow">enter image description here</a></p>
<p>Moreover, the scrollbar does not extend all over the form, but it is just on the low, right corner of the windows.</p>
<p>While the latter issue (scrollbar) I can leave with it, the first one is a little more important, since I would like to have the final user to have a "picture" of what they should do without needing to resize the windows.</p>
<p>Does any have any idea on how I should proceed with this?
What am I missing?</p>
<p>Thanks in advance for your help</p>
|
<p>In the <code>__init__</code> method of your class, you do not appear to have set the size of your main window. You should do that, or it will just set the window to a default size, which will only show whatever it can, and in your case, only 1 column. Therefore, in the <code>__init__</code> method, try putting <code>self.geometry(str(your_width) + "x" + str(your_height))</code> where <code>your_width</code> and <code>your_height</code> are whatever integers you choose that allow you to see what you need to in the window. </p>
<p>As for your scrollbar issue, all I had to do was change the way your scrollbar was added to the canvas to a <code>.pack()</code> and added the attributes <code>fill = 'y' and side = RIGHT</code> to it, like so: </p>
<pre><code>self.yscrollbar.pack(side = 'right', fill = 'y')
</code></pre>
<p>Also, you don't need: </p>
<pre><code>self.yscrollbar.config(command=self.canvas.yview)
self.yscrollbar.pack(size=RIGHT,expand=FALSE)
</code></pre>
<p>Just add the command option to the creation of the scrollbar, like so: </p>
<pre><code>self.scrollbar = Scrollbar(self,orient=VERTICAL,command=self.canvas.yview)
</code></pre>
<p>In all, the following changes should make your code work as expected:</p>
<ul>
<li><p>Add:</p>
<pre><code>def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.initialize()
# Resize the window from the default size to make your widgets fit. Experiment to see what is best for you.
your_width = # An integer of your choosing
your_height = # An integer of your choosing
self.geometry(str(your_width) + "x" + str(your_height))
</code></pre></li>
<li><p>Add and Edit:</p>
<pre><code># Add `command=self.canvas.yview`
self.yscrollbar = Scrollbar(self,orient=VERTICAL,command=self.canvas.yview)
# Use `.pack` instead of `.grid`
self.yscrollbar.pack(side = 'right', fill = 'y')
</code></pre></li>
<li><p>Remove:</p>
<pre><code>self.yscrollbar.config(command=self.canvas.yview)
self.yscrollbar.pack(size=RIGHT,expand=FALSE)
</code></pre></li>
</ul>
|
python|canvas|tkinter|scrollbar|tkinter-canvas
| 3 |
1,902,810 | 58,881,270 |
adding prefix to pandas column
|
<p>I'm trying to add a prefix to a DataFrame in pandas.
It supposes to be very easy: </p>
<pre><code>import pandas as pd
a=pd.DataFrame({
'x':[1,2,3],
})
#this one works;
"mm"+a['x'].astype(str)
0 mm1
1 mm2
2 mm3
Name: x, dtype: object
</code></pre>
<p>But surprisingly, if I want to use a prefix of single letter 'm', it stops working: </p>
<pre><code>#this one doesn't work
"m"+a['x'].astype(str)
TypeError Traceback (most recent call last)
<ipython-input-21-808db8051ebc> in <module>
1 #this one doesn't work
----> 2 "m"+a['x'].astype(str)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in wrapper(left, right)
1014 if is_scalar(right):
1015 # broadcast and wrap in a TimedeltaIndex
-> 1016 assert np.isnat(right)
1017 right = np.broadcast_to(right, left.shape)
1018 right = pd.TimedeltaIndex(right)
TypeError: ufunc 'isnat' is only defined for datetime and timedelta.
</code></pre>
<p>So my questions are: </p>
<ol>
<li><p>How to solve the problem?</p></li>
<li><p>What happened, it seems pandas is trying to do something fancy?</p></li>
<li><p>Why is 'm' is so special? (it seems other single letters are ok, e.g. 'b').</p></li>
</ol>
|
<p>The problem is that <code>"m"</code> is interpreted as <code>TimeDelta</code>:</p>
<pre><code>from pandas.core.dtypes.common import is_timedelta64_dtype
print(is_timedelta64_dtype("m"))
</code></pre>
<p><strong>Output</strong></p>
<pre><code>True
</code></pre>
<p>The function <code>is_timedelta64_dtype</code> is called when you do:</p>
<pre><code>res = "m" + a['x'].astype(str)
</code></pre>
<p><strong>Code (pandas)</strong></p>
<pre><code>elif is_timedelta64_dtype(right):
# We should only get here with non-scalar or timedelta64('NaT')
# values for right
# Note: we cannot use dispatch_to_index_op because
# that may incorrectly raise TypeError when we
# should get NullFrequencyError
orig_right = right
if is_scalar(right):
# broadcast and wrap in a TimedeltaIndex
assert np.isnat(right)
right = np.broadcast_to(right, left.shape)
right = pd.TimedeltaIndex(right)
</code></pre>
<p>Given that the value is an scalar also, it checks if it is NaT, </p>
<pre><code>assert np.isnat(right)
</code></pre>
<p>Which is what triggers the Exception. A simple workaround is to put "m" inside a list:</p>
<pre><code>res = ["m"] + a['x'].astype(str)
print(res)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>0 m1
1 m2
2 m3
Name: x, dtype: object
</code></pre>
|
python|pandas
| 3 |
1,902,811 | 31,279,175 |
With PyMongo how do I import indexes using create_index() that were exported with index_information()?
|
<p>What do you need to do to the output of index_information() such that it can then be re-imported using create_index() or create_indexes() ?</p>
<pre><code>>>> from pymongo import MongoClient
>>> client = MongoClient("mongodb://host1")
>>> db = client.MYDB
>>> collection = db.MYCOLLECTION
>>> index = db.provisioning.index_information()
>>> index
{u'_id_': {u'ns': u'MYDB.MYCOLLECTION', u'key': [(u'_id', 1)], u'v': 1}, u'Name_1': {u'unique': True, u'key': [(u'Name', 1)], u'v': 1, u'ns': u'MYDB.MYCOLLECTION', u'background': False}, u'MongoType_1': {u'key': [(u'MongoType', 1)], u'ns': u'MYDB.MYCOLLECTION', u'background': False, u'v': 1}}
>>> client2 = MongoClient("mongodb://host2")
>>> db2 = client2.MYDB
>>> collection2 = db2.MYCOLLECTION
>>> collection2.create_index(index)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/site-packages/pymongo/collection.py", line 1161, in create_index
keys = helpers._index_list(keys)
File "/usr/lib64/python2.6/site-packages/pymongo/helpers.py", line 55, in _index_list
raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list
>>> collection2.create_indexes(index)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/site-packages/pymongo/collection.py", line 1046, in create_indexes
raise TypeError("indexes must be a list")
TypeError: indexes must be a list
</code></pre>
|
<p>Try this basic code, this will iterate and add all index from one collection to other collection,</p>
<pre><code>from pymongo import MongoClient
client = MongoClient("mongodb://host1")
db = client.MYDB
collection = db.MYCOLLECTION
index = db.provisioning.index_information()
client2 = MongoClient("mongodb://host2")
db2 = client2.MYDB
collection2 = db2.MYCOLLECTION
for i in index.keys():
name_index = index[i]['key'][0][0]
order = index[i]['key'][0][1]
collection2.create_index([(name_index, order)])
</code></pre>
|
python|mongodb|pymongo
| 1 |
1,902,812 | 15,888,186 |
Can't run Python via IDLE from Explorer [2013] - IDLE's subprocess didn't make connection
|
<p><em>Resolved April 15, 2013.</em>
In windows 7 (64bit) windows explorer when I right clicked a Python file and selected "edit with IDLE" the editor opens properly but when I run (or f5) the Python 3.3.1 program, it fails with the <strong><em>"IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection."</em></strong> error message. All other methods of starting IDLE for running my python 3.3.1 programs worked perfectly.
Even the "Send to" method worked but it was unacceptably clunky. I've spend four days (so far) researching this and trying various things including reinstalling Python many times.
And NO it's not the FireWall blocking it. I've tried totally turning Firewall off and it had no effect.</p>
<p>Here's an important clue: In the beginning I installed and configured python 3.3 64 bit and <strong>everything</strong> worked including running from "edit with IDLE" but then recently when I needed a library only available in Python 2 I installed python 2.7.4 and from that point on the stated problem began. At one point I completely removed all traces of both versions and reinstalled Python 3.3.1 64 bit. Problem remained.</p>
<p>Then I tried have both <strong>32 bit</strong> versions installed but still no luck. Then at some point in my muddling around I lost the option to "edit with IDLE" and spent a day trying everything including editing in Regedit. No luck there either. I reinstalled Python 3.3.1 still no "edit with IDLE" then Finally I uninstalled all versions of Python and I removed python references to environment variables PATH and PYTHONPATH. Then I Deleted all the Python related keys in the windows registry, deleted the C:\python33 directory that the uninstall didn't bother to delete. Overkill, of course, then I restarted windows and installed Python 3.3.1 64 bit version again and thankfully the option to 'edit with IDLE' was back. I was <em>momentarily</em> happy, I opened windows explorer, right clicked on a python program, selected 'edit with IDLE' selected RUN (eyes closed) and you guessed it, same original error message <strong>"IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection."</strong></p>
<p>I am completely stuck on this issue and really need help. Pretty sure that you can see I and not a happy camper. And to top it all off, I guess I don't understand StackOverflow yet, I have had this plea for help up in various versions for 5 days and not one response from anyone. Believe me I've looked at every thing in stackoverflow plus other sites and I can't see the answer. Almost seems like I have to answer my own question and post it, trouble is, so far I can't. </p>
<p>Anyway, thanks for listening. Yes I'm pretty new to Python but I've been programming and overcoming problems for many years (too many perhaps). anyone? Not personally having someone that is familiar with Python makes this difficult, how can I get in touch with an expert in Python for a quick phone conversation? </p>
|
<p>I had this same problem today. I found another stack overflow post where someone had a <code>tkinter.py</code> file in the same directory as <code>python</code>, and they fixed it by removing that <code>tkinter.py</code> file. When I looked in my <code>python</code> directory, I realized I had created a script called <code>random.py</code> and put it there. I suspect that it conflicted with the normal random module in python. When I removed this file, python started working again. </p>
<p>So I would suggest you look in your main python directory and see if there are any <code>.py</code> files that you could move to different places. </p>
|
python-2.7|python-3.x|python-idle
| 15 |
1,902,813 | 25,408,393 |
Getting individual colors from a color map in matplotlib
|
<p>If you have a <a href="https://matplotlib.org/stable/tutorials/colors/colormaps.html" rel="noreferrer">Colormap</a> <code>cmap</code>, for example:</p>
<pre><code>cmap = matplotlib.cm.get_cmap('Spectral')
</code></pre>
<p>How can you get a particular colour out of it between 0 and 1, where 0 is the first colour in the map and 1 is the last colour in the map?</p>
<p>Ideally, I would be able to get the middle colour in the map by doing:</p>
<pre><code>>>> do_some_magic(cmap, 0.5) # Return an RGBA tuple
(0.1, 0.2, 0.3, 1.0)
</code></pre>
|
<p>You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the <code>cmap</code> object you have.</p>
<pre><code>import matplotlib
cmap = matplotlib.cm.get_cmap('Spectral')
rgba = cmap(0.5)
print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638401709, 1.0)
</code></pre>
<p>For values outside of the range [0.0, 1.0] it will return the under and over colour (respectively). This, by default, is the minimum and maximum colour within the range (so 0.0 and 1.0). This default can be changed with <code>cmap.set_under()</code> and <code>cmap.set_over()</code>. </p>
<p>For "special" numbers such as <code>np.nan</code> and <code>np.inf</code> the default is to use the 0.0 value, this can be changed using <code>cmap.set_bad()</code> similarly to under and over as above.</p>
<p>Finally it may be necessary for you to normalize your data such that it conforms to the range <code>[0.0, 1.0]</code>. This can be done using <a href="http://matplotlib.org/api/colors_api.html#matplotlib.colors.Normalize" rel="noreferrer"><code>matplotlib.colors.Normalize</code></a> simply as shown in the small example below where the arguments <code>vmin</code> and <code>vmax</code> describe what numbers should be mapped to 0.0 and 1.0 respectively.</p>
<pre><code>import matplotlib
norm = matplotlib.colors.Normalize(vmin=10.0, vmax=20.0)
print(norm(15.0)) # 0.5
</code></pre>
<p>A logarithmic normaliser (<a href="http://matplotlib.org/api/colors_api.html#matplotlib.colors.LogNorm" rel="noreferrer">matplotlib.colors.LogNorm</a>) is also available for data ranges with a large range of values.</p>
<p><em>(Thanks to both <a href="https://stackoverflow.com/users/325565/joe-kington">Joe Kington</a> and <a href="https://stackoverflow.com/users/380231/tcaswell">tcaswell</a> for suggestions on how to improve the answer.)</em></p>
|
python|matplotlib|colors
| 355 |
1,902,814 | 24,984,658 |
List stock data by weeks and days using Python
|
<p>I would like to list different stock data which were published in one week. The stock data should all be in seperate arrays. The different array elements should represent the different days and the arrays itself should be the different weeks. So for example <code>week_1[55.5,23.1,234.8,,23.6]</code>. The code I have tried until now can be viewed below, but unfortunately it simply doesn't work. I always get the error: <code>'str' object does not support item assignment</code>. Any simple ideas on how I could fix this?</p>
<p><strong>Python Code:</strong></p>
<pre><code>import datetime
# open csv file
lines = open("google.csv")
lines = lines.read()
lines = lines.split("\n")
i=0
while i<(len(lines)-1):
data = lines[i].split(',')
date2 = data[0].split('-')
week = date(int(date2[0]), int(date2[1]), int(date2[2])).isocalendar()[1]
# Create week array
weekN = "week_"+str(week)
weekN = []
# Get Stock Data
stockN = data[1]
#get day and add stock prices to week array
d = datetime.date(int(date2[0]), int(date2[1]), int(date2[2]))
if d.strftime("%a") == "Mon":
weekN[0] = stockN
if d.strftime("%a") == "Tue":
weekN[1] = stockN
if d.strftime("%a") == "Wed":
weekN[2] = stockN
if d.strftime("%a") == "Thu":
weekN[3] = stockN
if d.strftime("%a") == "Fri":
weekN[4] = stockN
i=i+1
</code></pre>
<p><strong>CSV File:</strong></p>
<pre><code>2011-02-07,610.16,618.39,609.21,614.29,1799600,614.29
2011-02-04,610.15,611.44,606.61,610.98,1550800,610.98
2011-02-03,609.48,611.45,606.13,610.15,1495100,610.15
2011-02-02,611.00,614.34,607.53,612.00,1760700,612.00
2011-02-01,604.49,613.35,603.11,611.04,2745300,611.04
2011-01-31,603.60,604.47,595.55,600.36,2804900,600.36
2011-01-28,619.07,620.36,599.76,600.99,4231100,600.99
</code></pre>
|
<p>In the following code:</p>
<ul>
<li>a dictionary is created, having keys like <code>'week_1'</code></li>
<li>each value is also a dictionary</li>
<li>use <code>with</code>, iterate over the lines of the file, parse dates using the standard library contents</li>
</ul>
<p>Thus we get</p>
<pre><code>import datetime
import time
from collections import defaultdict
weeks = defaultdict(dict)
with open('google.csv') as f:
for line in f:
data = line.split(',')
#get week
the_date = datetime.date(*time.strptime(data[0], '%Y-%m-%d')[:3])
_, week_number, day_number = the_date.isocalendar()
week = "week_{}".format(week_number)
stock = data[1]
if day_number in range(1, 6):
weeks[week][day_number - 1] = stock
</code></pre>
<p>Result:</p>
<pre><code>{'week_4': {4: '619.07'},
'week_5': {0: '603.60', 1: '604.49', 2: '611.00', 3: '609.48', 4: '610.15'},
'week_6': {0: '610.16'}}
</code></pre>
|
python|arrays|sorting|python-2.7|stocks
| 0 |
1,902,815 | 25,005,831 |
How to duplicate objects in Python/Pygame?
|
<p>So I'm playing around with a Pygame platformer. Right now I have a player character, a bumper, and background. The player can run around the floor of the level or the bumper and the screen can screen when the character runs against the edge.</p>
<p>What I'd like though is a way to have multiple bumpers without having to create each individually. Here is some relevant code.</p>
<p>This is creating the bumper before the game's main loop...</p>
<pre><code>bumper = pygame.image.load("bumper.png") #load bumper pic
bumperbounds = bumper.get_clip() #create boundaries for bumper
bumperbounds = bumperbounds.move (200, 250) #move the bumper to starting location
</code></pre>
<p>This is the code that makes the bumper stop the player from falling through. It just sets the landed value to 1...</p>
<pre><code> if playerbounds.left <= bumperbounds.right and playerbounds.right >= bumperbounds.left and playerbounds.bottom <= bumperbounds.top + 30 and playerbounds.bottom >= bumperbounds.top and gravity >=0: #if player lands on top of the bumper
landed = 1 #set player to landed
</code></pre>
<p>This is some code so that the player lands on the platform correctly. Basically it slows the player down at the last loop iteration from falling through the bumper so its exact falling speed lands the bottom of the player on the top of the bumper.</p>
<pre><code> if playerbounds.left <= bumperbounds.right and playerbounds.right >= bumperbounds.left and playerbounds.bottom <= bumperbounds.top and gravity > bumperbounds.top-playerbounds.bottom: #to land exactly on the top of the bumper
gravity = bumperbounds.top-playerbounds.bottom
</code></pre>
<p>This is to move the bumper when the screen is scrolling. This is just the right direction, the left one works basically the same.</p>
<pre><code> if xacc > 0:#if player is moving right
if playerx >= width * .8 and screenx < levelwidth - playerbounds.width:#if the screen is scrolling
screenx = screenx + xacc
bumperbounds = bumperbounds.move(-xacc, 0) #bumper moves on the screen
skybounds = skybounds.move(-xacc / 10, 0)
groundbounds = groundbounds.move(-xacc * 2, 0)
else:
playerbounds = playerbounds.move(xacc, 0)
playerx += xacc
xacc -= 1
</code></pre>
<p>This just shows the bump on the screen at the end of the loop.</p>
<pre><code> screen.blit(bumper,bumperbounds) #displays the bumper on the screen
</code></pre>
<p>Any help can be useful?!</p>
|
<p>You need create a class for the object you are creating.</p>
<p>For example:</p>
<pre><code>class Leaf:
def __init__(self):
self.leafimage = pygame.image.load('fallingleaf.jpg').convert()
self.leafrect = self.leafimage.get_rect()
xpos = random.randint(0, 640)
self.leafrect.midtop = (xpos, 0)
def move(self):
self.leafrect = self.leafrect.move([0, 1])
</code></pre>
<p>To create objects at the same time,</p>
<pre><code>leaves = []
for i in range(5):
leaves.append(Leaf())
</code></pre>
<p>With changing xpos value:</p>
<pre><code>class Leaf:
def __init__(self,xpos):
self.leafimage = pygame.image.load('fallingleaf.jpg').convert()
self.leafrect = self.leafimage.get_rect()
self.leafrect.midtop = (xpos, 0)
def move(self):
self.leafrect = self.leafrect.move([0, 1])
To create objects at the same time,
leaves = []
xpos= [20 30 40 50 60]
for i in range(5):
leaves.append(Leaf(xpos[i]))
</code></pre>
|
python|pygame
| 4 |
1,902,816 | 2,709,941 |
write error: Broken pipe
|
<p>I have to run a tool on around 300 directories. Each run take around 1 minute to 30 minute or even more than that. So, I wrote a python script having a loop to run the tool on all directories one after another.</p>
<p>my python script has code something like:</p>
<pre><code>for directory in directories:
os.popen('runtool_exec ' + directory)
</code></pre>
<p>But when I run the python script I get the following error messages repeatedly:</p>
<pre><code>..
tail: write error: Broken pipe
date: write error: Broken pipe
..
</code></pre>
<p>All I do is login on a remote server using ssh where the tool, python script, and subject directories are kept. When I individually run the tool from command prompt using command like:</p>
<pre><code>runtool_exec directory
</code></pre>
<p>it works fine. "broken pipe" error is coming only when I run using the python script.
Any idea, workaround?</p>
|
<p>The errors you see are because you're using <code>os.popen()</code> to run the command, which means a pipe is opened and connected to the command's <code>stdout</code>. Whenever the command (or anything it executes without redirecting <code>stdout</code>) wants to write to <code>stdout</code>, it'll try to write to the pipe. But you don't keep the pipe around, since you don't assign the result of <code>os.popen()</code> anywhere, so it's cleaned up by Python, and closed. So the processes that try to write to it encounter a broken pipe, and produce the error you see. (<code>os.popen()</code> does <em>not</em> redirect <code>stderr</code> to the pipe, so you still see the errors.)</p>
<p>Another problem in your <code>os.popen()</code> call is that you don't check to make sure <code>directory</code> doesn't contain any characters special to your shell. If the directory contained a quote, for example, or a *, weird things might happen. Using <code>os.popen()</code> like that is pretty bad.</p>
<p>You should use <code>subprocess.Popen()</code> instead, and explicitly tell it what you want to do with the process's output (both stdout and stderr.) You pass <code>subprocess.Popen()</code> a list of arguments (including the thing you want to start) instead of a single string, and it avoids the shell altogether -- no need to sanity-check your strings. If you really want to ignore the output, you would do it with something like:</p>
<pre><code>devnull = open(os.devnull, 'w')
for directory in directories:
subprocess.Popen(['runtool_exec', directory], stdout=devnull)
</code></pre>
<p>although I would strongly recommend at least doing some rudimentary checks on the result of subprocess.Popen to see if the process didn't execute prematurely or with an error code.</p>
|
python|linux|unix|scripting
| 9 |
1,902,817 | 6,264,025 |
How to adapt the Singleton pattern? (Deprecation warning)
|
<p>Few years ago I found an implementation of the Singleton pattern in Python by <a href="http://web.archive.org/web/20090619190842/http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html" rel="nofollow noreferrer">Duncan Booth</a>:</p>
<pre><code>class Singleton(object):
"""
Singleton class by Duncan Booth.
Multiple object variables refers to the same object.
http://web.archive.org/web/20090619190842/http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#singleton-and-the-borg
"""
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(
cls, *args, **kwargs)
return cls._instance
</code></pre>
<p>The same approach is also described in question "<a href="https://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python/1810391#1810391">Is there a simple, elegant way to define Singletons in Python?</a>"</p>
<p>I use the Singleton via sub-classing:<br>
<code>class Settings(Singleton)</code><br>
<code>class Debug(Singleton)</code> </p>
<p>Recently I made some changes to the program and got this warning:</p>
<pre><code>/media/KINGSTON/Sumid/src/miscutil.py:39: DeprecationWarning:
object.__new__() takes no parameters
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
</code></pre>
<p>I found <a href="http://mail.python.org/pipermail/python-dev/2008-February/076854.html" rel="nofollow noreferrer">explanation</a> (by Guido) about <code>__new__</code> deprecation which says that the parameters are not used at all. Passing an argument which is not needed can be symptom of a bug.</p>
<p>So I decided to clear the parameters:</p>
<pre><code>class Singleton(object):
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__()
return cls._instance
</code></pre>
<p>Which resulted in following exception:</p>
<pre><code>Traceback (most recent call last):
File "sumid.py", line 1168, in <module>
settings = Settings()
File "/media/KINGSTON/Sumid/src/miscutil.py", line 45, in __new__
cls._instance = super(Singleton, cls).__new__()
TypeError: object.__new__(): not enough arguments
</code></pre>
<p>When I modify the line to <code>cls._instance = super(Singleton, cls).__new__(cls)</code>, I'll get:</p>
<pre><code>Traceback (most recent call last):
File "sumid.py", line 1174, in <module>
debug = Debug(settings)
TypeError: __new__() takes exactly 1 argument (2 given)
</code></pre>
<p>Gimmel suggest another <a href="https://stackoverflow.com/questions/1590477/python-deprecation-warnings-with-monostate-new-can-someone-explain-why/1590586#1590586">solution</a>: <code>_instance = type.__new__(cls)</code>. For me it breaks the inheritance:</p>
<pre><code>Traceback (most recent call last):
File "sumid.py", line 1168, in <module>
settings = Settings()
File "/media/KINGSTON/Sumid/src/miscutil.py", line 40, in __new__
_instance = type.__new__(cls)
TypeError: type.__new__(Settings): Settings is not a subtype of type
</code></pre>
<p>The same <a href="http://freshfoo.com/blog/object__init__takes_no_parameters" rel="nofollow noreferrer">problem</a> has also Menno Smits. But I don't understand the <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=281127" rel="nofollow noreferrer">solution</a> suggested. Moreover I have no multiple inheritance in relevant code.</p>
<p>I didn't try the another <a href="https://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python/33201#33201">example</a> in "Is there a simple, elegant way to define Singletons in Python?", but at a glance it probably will have the same problem.</p>
<p>I use the Singleton pattern in a program and I don't want to rewrite it completely just because one warning. Thus following answers wont help me: </p>
<ul>
<li>Singleton is wrong. Don't use the Singleton at all. </li>
<li>Use Borg instead, it's more pythonic. </li>
<li>Use module instead of a class. </li>
</ul>
<p>To conclude I'll repeat the question:<br>
How to <strong>adapt the Singleton</strong> pattern with consideration of the <strong>deprecation warning</strong> with the <strong>minimal impact</strong> to existing code?</p>
<p><strong>Edit:</strong>
Line <code>cls._instance = object.__new__(cls)</code> raises the TypeError when the Child's init takes an argument:</p>
<pre><code>class Child(Singleton):
def __init__(self,param=None):
print(param)
print("Doing another stuff.")
ch = Child("Some stuff")
</code></pre>
|
<p>You need to drop any additional arguments you are passing when you construct the object. Change the offending line to:</p>
<pre><code> cls._instance = object.__new__(cls)
</code></pre>
<p>or</p>
<pre><code> cls._instance = super(Singleton, cls).__new__(cls)
</code></pre>
<p>though I think you'll be fine with the first (diamond inheritance and singletons sound as though they shouldn't be mixed).</p>
<p>P.S. I did try this suggestion and it works for me so I don't know why it didn't work for you.</p>
<p><strong>Edit in response to @dragonx's comment:</strong> As pointed out in the comments, <code>object.__new__</code> will throw an exception if you pass on <code>*args, **kwargs</code> so the super call to <code>__new__</code> should not include any arguments apart from <code>cls</code>. This wasn't the case when the original article was written. Also of course if you choose to base your singleton on some other type such as a <code>tuple</code> you would then need to pass the appropriate arguments.</p>
|
python|design-patterns|singleton|deprecated
| 10 |
1,902,818 | 5,995,812 |
Python - Decimal to Hex, Reverse byte order, Hex to Decimal
|
<p>I've been reading up a lot on stuct.pack and hex and the like.</p>
<p>I am trying to convert a decimal to hexidecimal with 2-bytes. Reverse the hex bit order, then convert it back into decimal.</p>
<p>I'm trying to follow these steps...in python</p>
<pre><code>Convert the decimal value **36895** to the equivalent 2-byte hexadecimal value:
**0x901F**
Reverse the order of the 2 hexadecimal bytes:
**0x1F90**
Convert the resulting 2-byte hexadecimal value to its decimal equivalent:
**8080**
</code></pre>
|
<p>Bit shifting to swap upper/lower eight bits:</p>
<pre><code>>>> x = 36895
>>> ((x << 8) | (x >> 8)) & 0xFFFF
8080
</code></pre>
<p>Packing and unpacking unsigned short(H) with opposite endianness(<>):</p>
<pre><code>>>> struct.unpack('<H',struct.pack('>H',x))[0]
8080
</code></pre>
<p>Convert 2-byte little-endian to big-endian...</p>
<pre><code>>>> int.from_bytes(x.to_bytes(2,'little'),'big')
8080
</code></pre>
|
python|decimal|hex|bit
| 10 |
1,902,819 | 67,811,345 |
Boolean filter geopandas dataframe following shapely within
|
<p>I have a geopandas dataframe I perform a convexhull operation on a multipoint dataset using shapely.</p>
<pre><code>top_sample_col.within(cvh_base)
</code></pre>
<p>This returns a boolean, how do I assign to a new gdf only those that are assigned true? (option A)</p>
<p>I can use <code>.set_index()</code> but then how do I filter by the index=True (option B)</p>
<p>Option A is the preferred method.</p>
<p>Edit</p>
<p>This does the job, but can it be more streamlined?</p>
<pre><code>df['within'] = top_sample_col.within(cvh_base)
df = df.loc[df['within'] == True]
</code></pre>
|
<p>You can pass the boolean array as a mask directly.</p>
<pre class="lang-py prettyprint-override"><code>df = df.loc[top_sample_col.within(cvh_base)]
</code></pre>
|
pandas|geopandas|shapely
| 1 |
1,902,820 | 67,065,866 |
How do I copy an instance that has non-pickleable objects stored within it?
|
<p>I have objects within my instance that are not pickleable.
However, I would like to be able to save the instance as the program runs in case something happens. This way I can easily restart the program.</p>
<p>My thought was:</p>
<ol>
<li>Create copy of instance as new_instance</li>
<li>Re-write all non-pickleable objects in new_instance to None</li>
<li>Pickle new_instance</li>
<li>Repeat at a specified time interval</li>
</ol>
<p>However, copy() and deepcopy() do not work.
copy() just assigns the reference to the original object for some reason &
Deepcopy() gives me the same error that the objects in my instance aren't pickleable.</p>
<p>Is there another option / better method that I should be using?
Is there a way to ignore certain object types when pickling so I don't need to create a copy, rewrite, and pickle?</p>
|
<p>I ended up writing the logic myself based on juanpa.arrivillaga's input.</p>
<p>I created an empty copy within the <strong>init</strong>(self) of the class.
Then, later updated using a function like below:</p>
<pre><code>def save_copy(self):
for i, j in self.__dict__.items():
# Ignore nonpickeable items
if(type(i) == 'nonpickeable'):
pass
else:
# Set copy dictionary to instance dictionary
# if pickeable
self._copy.__dict__[i] = j
</code></pre>
|
python|serialization|copy|instance|pickle
| 0 |
1,902,821 | 64,025,487 |
Cannot send message to Azure IoT Hub to units with ":" in their device id
|
<p>I am trying to send messages from my machine to a IoT-Hub. I am using the following code:</p>
<pre><code> message = Message('{{"temperature": 20,"humidity": 10}}')
client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
client.send_message(message)
</code></pre>
<p>This works when the deviceId in CONNECTION_STRING doesn't have colons in it.</p>
<pre><code>CONNECTION_STRING = "HostName=my-iot-hub.azure-devices.net;DeviceId=E0:DC:A0:73:C6:C3;SharedAccessKey=password"
CONNECTION_STRING = "HostName=my-iot-hub.azure-devices.net;DeviceId=my_device;SharedAccessKey=password"
</code></pre>
<p>The first connectionstring doesn't work. The process hangs when trying to send the message - but doesn't give me an error message. The second sends without any problems.</p>
<p>Is there some way to escape the colons?</p>
|
<p>We confirmed this is a bug with url encoding. In the next release of <a href="https://github.com/Azure/azure-iot-sdk-python" rel="nofollow noreferrer">azure-iot-device</a> (releases higher than 2.3.0), we will be adding a fix.</p>
<p>Thanks.</p>
|
python|azure|azure-iot-hub|azure-iot-sdk
| 1 |
1,902,822 | 42,584,866 |
Running an operation on one column based on content from another column in Pandas Dataframe
|
<p>I'm trying to convert the negative value of rows in column <code>'nominal'</code> where the corresponding value in column <code>'side'</code> is equal to 'B'. I don't want to lose any rows that are not converted. I've tried this below but getting raise <code>KeyError('%s not in index' % objarr[mask])</code></p>
<pre><code>df[-df['nominal']].where(df['side']=='B')
</code></pre>
|
<p>Just use both conditions in a boolean index with <code>&</code>. </p>
<pre><code>df[(df.side == 'B') & (df.nominal < 0)]
</code></pre>
<p>or if you intend on modifying, </p>
<pre><code>df.loc[(df.side == 'B') & (df.nominal < 0), 'nominal']
</code></pre>
<p><strong>Example</strong></p>
<pre><code>>>> df = pd.DataFrame(dict(side=['A']*3+['B']*3, nominal = [1, -2, -2, 2, 6, -5]))
>>> df
nominal side
0 1 A
1 -2 A
2 -2 A
3 2 B
4 6 B
5 -5 B
>>> df.loc[(df.side == 'B') & (df.nominal < 0), 'nominal'] = 1000
>>> df
nominal side
0 1 A
1 -2 A
2 -2 A
3 2 B
4 6 B
5 1000 B
</code></pre>
<p>This is a very standard way for filtering data in Pandas that you'll come across often. See <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="noreferrer">Boolean Indexing</a> in the Pandas docs. </p>
<hr>
<p><strong>Update</strong></p>
<p>For your updated problem description, we can just use the augmented assignment operator <code>*=</code> to multiply our desired values by -1. </p>
<pre><code>df.loc[(df.side == 'B'), 'nominal'] *= -1
</code></pre>
<p><strong>Example</strong></p>
<pre><code>>>> df = pd.DataFrame(dict(nominal = [1, 2, 5, 3, 5, 3], side=['A']*3 + ['B']*3))
>>> df
nominal side
0 1 A
1 2 A
2 5 A
3 3 B
4 5 B
5 3 B
>>> df.loc[(df.side == 'B'), 'nominal'] *= -1
df
nominal side
0 1 A
1 2 A
2 5 A
3 -3 B
4 -5 B
5 -3 B
</code></pre>
|
python|pandas|dataframe
| 6 |
1,902,823 | 43,025,652 |
how to extend to a lot of template along with its view function?
|
<p>What i am trying to do is that </p>
<p>my base.html to have a Cart.html that extends to it</p>
<p>while other child html can extend to base.html and have the Cart.html available in the base.html</p>
<p>something like this</p>
<p>Catalogue.html----> base.html with Cart.html</p>
<p>Catagories.html------^</p>
<p>i tried include in base.html, the form and button did appear</p>
<p>but it doesn't pass the class and function from the Cart.html</p>
<pre><code>class CartFormView(generic.ListView, ModelFormMixin):
template_name = 'Shop/Cart.html'
def get(self, request, *args, **kwargs):
#bla bla bla
def post(self, request, *args, **kwargs):
#bla bla bla
</code></pre>
<p>tried double extending but it is not allowed in Cart.html</p>
<pre><code>{% extends 'Shop/Catalogue.html', 'Shop/Catagories.html' %}
</code></pre>
<h1>or</h1>
<pre><code>{% extends 'Shop/Catalogue.html' %}
{% extends 'Shop/Catagories.html' %}
</code></pre>
<p>Thanks</p>
|
<ol>
<li>Create a separate HTML file called <code>cart.html</code></li>
<li>Inside the <code>base.html</code> create a <code>{% block cart_page %}</code> and enter inside it this: <code>{% include 'path/to/cart.html' %}</code>.</li>
<li>Now, each page will have the <code>cart.html</code> snippet.</li>
</ol>
<p>Something like this:</p>
<pre><code><!-- base.html -->
<!DOCTYPE html>
...
<body>
{% block cart_page %}
{% include 'templates/cart.html' %}
{% endblock %}
</body>
</code></pre>
<p>Now, if you want some of your HTML template not to include the <code>cart.html</code> then inside these template write this:</p>
<pre><code>{% block cart_page %}{% endblock %}
</code></pre>
<p>Of course, if you want to include <code>cart.html</code> to any (child) template you should do: <code>{% extends 'base.html' %}</code> at the top of each child template.</p>
<p>It is better for the <code>cart.html</code> <strong>not</strong> to include a full boilerplate HTML (starting with <code><!DOCTYPE html></code> etc), since it is considered a snippet. The only file that will have the <code><!DOCTYPE html></code> etc will be the <code>base.html</code> (the core one).</p>
|
python|django|django-models|django-forms
| 0 |
1,902,824 | 42,706,343 |
How to add the total value of a variable within a while a loop
|
<p>I have a variable that computes a new value each time the loop is ran. How would I add all the values that were computed together?</p>
|
<p>If I understand correctly what you want, use a variable outside the scope of your loop. This means (as a basic example)</p>
<pre><code># var outside loop
a = 0
for i in range(0,9):
# b just known inside the loop
b = i+i
a = a + b
print(a)
</code></pre>
|
python-3.x
| 0 |
1,902,825 | 66,500,055 |
Python is not able to compare a value to a list element
|
<p>So I am relatively new to python, not sure what is wrong here? I am sure it is a basic thing that I am missing but not sure what it could be, below is the code to find a matching target to any of the numbers in the list, which should work according to me but doesn't.</p>
<pre><code>def abc(target,list1):
for a in list1:
if a == target:
return a
else:
return 0
def main():
target = input("enter target")
list1 = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = input()
list1.append(ele)
g = abc(target,list1)
print(g)
if __name__== '__main__':
main()
</code></pre>
<p>Below is the output which obviously returns 0 as the code does not work:</p>
<pre><code>Enter target7
Enter number of elements : 4
5
6
7
8
0
</code></pre>
<p>should it not return 7 as the value in the list matches the target</p>
|
<p>As stated in the comments, your logic in <code>abc()</code> is off.</p>
<p>This should work as expected:</p>
<pre><code>def abc(target, list1):
return target if target in list1 else 0
def main():
target = int(input("enter target"))
list1 = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
list1.append(int(input()))
print(abc(target, list1))
if __name__ == '__main__':
main()
</code></pre>
<p>Output:</p>
<pre><code>Enter number of elements : 4
5
6
7
8
7
</code></pre>
|
python|python-3.x|list|function|range
| 0 |
1,902,826 | 66,683,925 |
dict is not ordering the content
|
<p>I installed the Anaconda 3 and I have a problem, I have read that dict is ordered automatically by the keys, but this is not happening in my installation</p>
<p>In the book that I am reading there is this example, wrote in a jupyter notebook:</p>
<p><a href="https://i.stack.imgur.com/FD2hG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FD2hG.jpg" alt="enter image description here" /></a></p>
<p><strong>this is what supposed to happen</strong>
<a href="https://i.stack.imgur.com/xVqWn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xVqWn.jpg" alt="enter image description here" /></a></p>
<p>I tested on <a href="https://colab.research.google.com" rel="nofollow noreferrer">https://colab.research.google.com</a> and I got the output ordered, so is my anaconda installation the problem? is this just a visual representation?</p>
<p>Sorry for my english, thanks in advance</p>
|
<p>If you want your dictionary to be sorted alphabetically, you can do the following:</p>
<pre><code>>>> print(dict(sorted(dic_estados.items())))
{'AM': 'Amazonas', 'BA': 'Bahia', 'MG': 'Minas Gerais', 'PR': 'Parana', 'RN': 'Rio Grande do Norte'}
</code></pre>
|
python|anaconda3
| 7 |
1,902,827 | 50,774,295 |
Speech recognizer doesn't work at the first vocal input
|
<p>I've just connected python to arduino in order to use vocal input. However the main problem is not in arduino but in python</p>
<pre><code>import speech_recognition as sr
import time
while True:
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
a = (r.recognize_google(audio))
print(a)
if a == 'light on':
print('ON')
if a == 'switch off':
print('OFF')
</code></pre>
<p>Sometimes it returns a NameError: <code>a</code> not defined, so <code>a</code> is not neither None. It happens only as first input. If it recognizes the first command (eg. switch off) it wouldn't happen in the whole runtime.
While sometimes it crashes while running and gives this error: </p>
<pre><code>File "C:\Program Files (x86)\Python36-32\lib\site-packages\speech_recognition\__init__.py", line 858, in recognize_google
if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
speech_recognition.UnknownValueError
</code></pre>
<p>I can see it, of course, only if I comment out try...except...</p>
|
<pre><code>try:
a = (r.recognize_google(audio))
print(a)
except:
pass
if a == 'light on':
arduino.write('H'.encode())
</code></pre>
<p>if an Exception occurs, <code>a</code> will not defined later and the program will crash.</p>
<p>Do e.g. </p>
<pre><code>try:
a = r.recognize_google(audio)
except NameError:
print('error') # use `traceback`
a = None
</code></pre>
|
python
| 0 |
1,902,828 | 50,483,962 |
AttributeError: 'Tensor' object has no attribute '_keras_history' when using backend random_uniform
|
<p>I'm implementing a WGAN-GP in Keras where I calculate the random weighted average of two tensors.</p>
<pre><code>def random_weighted_average(self, generated, real):
alpha = K.random_uniform(shape=K.shape(real))
diff = keras.layers.Subtract()([generated, real])
return keras.layers.Add()([real, keras.layers.Multiply()([alpha, diff])])
</code></pre>
<p>This is how it's used. It throws the error once I try to create the <code>discriminator_model</code>.</p>
<pre><code>averaged_samples = self.random_weighted_average(
generated_samples_for_discriminator,
real_samples)
averaged_samples_out = self.discriminator(averaged_samples)
discriminator_model = Model(
inputs=[real_samples, generator_input_for_discriminator],
outputs=[
discriminator_output_from_real_samples,
discriminator_output_from_generator,
averaged_samples_out
])
</code></pre>
<p>My backend is TensorFlow. When I use <code>alpha</code> in the last line I get the following error:</p>
<p><code>AttributeError: 'Tensor' object has no attribute '_keras_history'</code></p>
<p>I tried swapping <code>alpha</code> out for both <code>real</code> and <code>generated</code> to see if it had to do with the backend tensor and that was the case (the error disappeared). So what could be causing this issue? I need a random uniformly sampled tensor with the shape of <code>real</code> or <code>generated</code>.</p>
|
<p>Custom operations that use backend function need to be wrapped around a <code>Layer</code>. If you don't have any trainable weights, as in your case, the simplest approach is to use a <code>Lambda</code> layer:</p>
<pre><code>def random_weighted_average(inputs):
generated, real = inputs
alpha = K.random_uniform(shape=K.shape(real))
diff = generated - real
return real + alpha * diff
averaged_samples = Lambda(random_weighted_average)([generated_for_discriminator, real_samples])
</code></pre>
|
python|tensorflow|keras
| 1 |
1,902,829 | 50,573,741 |
Can't install cryptography on raspberry pi because of libffi
|
<p>I've been trying to install the package "flask-ask" on my Raspberry Pi Zero. However, there's a problem when trying to install the dependency "cryptography":</p>
<pre><code>Downloading/unpacking cryptography
Downloading cryptography-2.2.2.tar.gz (443kB): 443kB downloaded
Running setup.py (path:/tmp/pip-build-wg353po4/cryptography/setup.py) egg_info for package cryptography
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/tmp/pip-build-wg353po4/cryptography/setup.py", line 28, in <module>
"cryptography requires setuptools 18.5 or newer, please upgrade to a "
RuntimeError: cryptography requires setuptools 18.5 or newer, please upgrade to a newer version of setuptools
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/tmp/pip-build-wg353po4/cryptography/setup.py", line 28, in <module>
"cryptography requires setuptools 18.5 or newer, please upgrade to a "
RuntimeError: cryptography requires setuptools 18.5 or newer, please upgrade to a newer version of setuptools
----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /tmp/pip-build-wg353po4/cryptography
Storing debug log for failure in /home/pi/.pip/pip.log
</code></pre>
<p>(these logs gotten from trying to install cryptography on its own, but the same error is gotten when installing flask-ask)</p>
<p>I've tried <code>pip3 install -U setuptools</code> to upgrade it, but that doesn't work:</p>
<pre><code>pi@raspberrypi:~ $ pip3 install -U setuptools
Downloading/unpacking setuptools from https://files.pythonhosted.org/packages/7f/e1/820d941153923aac1d49d7fc37e17b6e73bfbd2904959fffbad77900cf92/setuptools-39.2.0-py2.py3-none-any.whl#sha256=8fca9275c89964f13da985c3656cb00ba029d7f3916b37990927ffdf264e7926
Downloading setuptools-39.2.0-py2.py3-none-any.whl (567kB): 567kB downloaded
Installing collected packages: setuptools
Found existing installation: setuptools 5.5.1
Not uninstalling setuptools at /usr/lib/python3/dist-packages, owned by OS
Can't roll back setuptools; was not uninstalled
Cleaning up...
Exception:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 295, in run
requirement_set.install(install_options, global_options, root=options.root_path)
File "/usr/lib/python3/dist-packages/pip/req.py", line 1436, in install
requirement.install(install_options, global_options, *args, **kwargs)
File "/usr/lib/python3/dist-packages/pip/req.py", line 672, in install
self.move_wheel_files(self.source_dir, root=root)
File "/usr/lib/python3/dist-packages/pip/req.py", line 902, in move_wheel_files
pycompile=self.pycompile,
File "/usr/lib/python3/dist-packages/pip/wheel.py", line 214, in move_wheel_files
clobber(source, lib_dir, True)
File "/usr/lib/python3/dist-packages/pip/wheel.py", line 208, in clobber
shutil.copy2(srcfile, destfile)
File "/usr/lib/python3.4/shutil.py", line 244, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/usr/lib/python3.4/shutil.py", line 108, in copyfile
with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.4/dist-packages/easy_install.py'
Storing debug log for failure in /home/pi/.pip/pip.log
</code></pre>
<p>So what should I do? I've done a lot of googling of various different things, and I've seen other people have problems with cryptography on the Pi, but not this specific problem.</p>
<p>EDIT: Ok, so I've done <code>pip install --user -U setuptools</code> now, and that works fine. Now I'm getting a totally different error:</p>
<pre><code> running install_egg_info
running egg_info
creating lib/PyYAML.egg-info
writing lib/PyYAML.egg-info/PKG-INFO
writing top-level names to lib/PyYAML.egg-info/top_level.txt
writing dependency_links to lib/PyYAML.egg-info/dependency_links.txt
writing manifest file 'lib/PyYAML.egg-info/SOURCES.txt'
reading manifest file 'lib/PyYAML.egg-info/SOURCES.txt'
writing manifest file 'lib/PyYAML.egg-info/SOURCES.txt'
Copying lib/PyYAML.egg-info to /home/pi/.local/lib/python2.7/site-packages/PyYAML-3.12$
running install_scripts
writing list of installed files to '/tmp/pip-XYXo6X-record/install-record.txt'
Could not find .egg-info directory in install record for PyYAML==3.12 (from flask-ask)
Running setup.py install for cryptography
Running command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-bui$
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
c/_cffi_backend.c:2:20: fatal error: Python.h: No such file or directory
#include <Python.h>
^
compilation terminated.
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-2gl72v/cryptography/setup.py", line 319, in <module>
**keywords_with_side_effects(sys.argv)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/__init__.py", line 128,$
_install_setup_requires(attrs)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/__init__.py", line 123,$
dist.fetch_build_eggs(dist.setup_requires)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/dist.py", line 514, in $
replace_conflicting=True,
File "/home/pi/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 7$
replace_conflicting=replace_conflicting
File "/home/pi/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1$
return self.obtain(req, installer)
File "/home/pi/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1$
return installer(requirement)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/dist.py", line 581, in $
return cmd.easy_install(req)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/command/easy_install.py$
return self.install_item(spec, dist.location, tmpdir, deps)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/command/easy_install.py$
dists = self.install_eggs(spec, download, tmpdir)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/command/easy_install.py$
return self.build_and_install(setup_script, setup_base)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/command/easy_install.py$
self.run_setup(setup_script, setup_base, args)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/command/easy_install.py$
raise DistutilsError("Setup script exited with %s" % (v.args[0],))
distutils.errors.DistutilsError: Setup script exited with error: command 'arm-linux-gn$
Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__=$
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
Package libffi was not found in the pkg-config search path.
Perhaps you should add the directory containing `libffi.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libffi' found
c/_cffi_backend.c:2:20: fatal error: Python.h: No such file or directory
#include <Python.h>
^
compilation terminated.
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-2gl72v/cryptography/setup.py", line 319, in <module>
**keywords_with_side_effects(sys.argv)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/__init__.py", line 128, in $
_install_setup_requires(attrs)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/__init__.py", line 123, in $
dist.fetch_build_eggs(dist.setup_requires)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/dist.py", line 514, in fetc$
replace_conflicting=True,
File "/home/pi/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 770, $
replace_conflicting=replace_conflicting
File "/home/pi/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1053,$
return self.obtain(req, installer)
File "/home/pi/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1065,$
return installer(requirement)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/dist.py", line 581, in fetc$
return cmd.easy_install(req)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/command/easy_install.py", l$
return self.install_item(spec, dist.location, tmpdir, deps)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/command/easy_install.py", l$
dists = self.install_eggs(spec, download, tmpdir)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/command/easy_install.py", l$
return self.build_and_install(setup_script, setup_base)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/command/easy_install.py", l$
self.run_setup(setup_script, setup_base, args)
File "/home/pi/.local/lib/python2.7/site-packages/setuptools/command/easy_install.py", l$
raise DistutilsError("Setup script exited with %s" % (v.args[0],))
distutils.errors.DistutilsError: Setup script exited with error: command 'arm-linux-gnueab$
----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-2gl72v/cr$
Exception information:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 295, in run
requirement_set.install(install_options, global_options, root=options.root_path)
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1436, in install
requirement.install(install_options, global_options, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 707, in install
cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)
File "/usr/lib/python2.7/dist-packages/pip/util.py", line 716, in call_subprocess
% (command_desc, proc.returncode, cwd))
InstallationError: Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/$
</code></pre>
<p>I have no clue why this is happening at this point.</p>
|
<p>I've had luck in a similar situation recently by first updating pip.</p>
<pre><code>sudo apt-get install -y python3-pip
sudo pip3 -H pip3 install --upgrade pip
</code></pre>
|
python|python-3.x|raspberry-pi|pip|python-cryptography
| 0 |
1,902,830 | 35,305,572 |
module has no attribute 'Twitter'
|
<p><a href="http://i.stack.imgur.com/fPo1W.jpg" rel="nofollow">ScreenShot with the error </a>Can someone help me with this? </p>
<pre><code>>>> import twitter
>>> twitter_api = twitter.Twitter(domain="api.twitter.com", api_version='1')
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'module' object has no attribute 'Twitter'
</code></pre>
|
<p>EDIT: I should clarify. Based on the package release version in your screenshot it appears you have installed this package:
<a href="https://pypi.python.org/pypi/python-twitter/3.0rc1" rel="nofollow">https://pypi.python.org/pypi/python-twitter/3.0rc1</a></p>
<p>Which is different from the package you intended to install:
<a href="https://pypi.python.org/pypi/twitter/1.17.1" rel="nofollow">https://pypi.python.org/pypi/twitter/1.17.1</a></p>
<p>You need to uninstall the package you had (e.g., <code>pip freeze</code>, <code>pip uninstall</code>) and install the correct one (<code>pip install twitter==1.17.1</code>). I highly recommend you discontinue using easy_install.</p>
|
python|twitter
| 0 |
1,902,831 | 64,962,367 |
python 2.7 shows up when running where pip3
|
<p>As the title states, I'm seeing an incorrect version of python showing when I check <code>pip3 --version</code></p>
<pre><code>pip 20.2.4 from /Library/Python/2.7/site-packages/pip-20.2.4-py2.7.egg/pip (python 2.7)
</code></pre>
<p>A few other checks:</p>
<ol>
<li>which pip3: /usr/local/bin/pip3</li>
<li>which python3: /usr/bin/python3</li>
</ol>
<p>I'm not sure how this happened so some insight here would be great. This is causing issues as I'm not installing any packages with python 3.</p>
|
<p>You have two ways to fix this that I know of. I ran into this as well:</p>
<ol>
<li>Use <code>python3 -m pip install ...</code> and forget about it</li>
<li>Actually understand what's going on - <code>pip</code> is actually a scipt that gets invoked by a python executable defined in its shebang:</li>
</ol>
<pre><code>❯ cat $(which pip)
#!/Users/me/anaconda/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
</code></pre>
<p>Let's do an experiment. This pip corresponds to my python3.8 installation. I'll create a python3.6 version for the sake of demonstration.</p>
<pre><code>❯ conda create -n p3.6 python=3.6 anaconda
</code></pre>
<p>Then we change the shebang to the new 3.6 installation:</p>
<pre><code>#!/Users/me/anaconda/envs/p3.6/bin/python
</code></pre>
<p>And run <code>pip --version</code> on the <code>pip</code> that belongs to my python 3.8 installation:</p>
<pre><code>❯ pip --version
pip 20.1.1 from /Users/rzhang/anaconda/envs/p3.6/lib/python3.6/site-packages/pip (python 3.6)
</code></pre>
<p>As you can see it shows that it points to this python3.6 python instead.</p>
<p>The reason this is the case is because if you look at the <code>sys.argv[0] = ...</code> line, it adopts the current python used to invoke the script. Modifying that before going into <code>main()</code> "picks" the python selected from shebang. Try changing that to the realpath of your python installation.</p>
<p>Now if you <strong>really</strong> want to fix the problem by understanding what's really going on, chances are your python interpreter links are all screwed up from a weird sequence of installations. It may be that the file in your shebang is actually a symlink that is not actually pointing at the correct installation, and you should fix that on a per-situation basis. There is no easy solution other than to untangle the installation paths of your multiple python interpreters.</p>
<p>Hope this helps!</p>
|
python|macos|pip
| 1 |
1,902,832 | 61,433,414 |
Which values to use when feeding placeholders in Tensorflow?
|
<p>In the code below, there are a number of tensor operations and calculations. I'd like to see the results of some of those calculations so I can better understand them. Specifically I'd like to see what h looks like during graph execution using <code>print(Session.Run(h))</code>. However, the calculations are dependent on the placeholder X. So in order to see them I need to use a feed dictionary.</p>
<p>I have read through this SO question: <a href="https://stackoverflow.com/questions/33810990/how-to-feed-a-placeholder">How to feed a placeholder?</a> and several others. I still don't know what I should be feeding into this placeholder.</p>
<p>To see the value of h, how, or rather what am I supposed to put in the feed dictionary when trying to print it?</p>
<pre><code>def expand_tile(value, size):
"""Add a new axis of given size."""
value = tf.convert_to_tensor(value, name='value')
ndims = value.shape.ndims
return tf.tile(tf.expand_dims(value, axis=0), [size] + [1]*ndims)
def positions_for(tokens, past_length):
batch_size = tf.shape(tokens)[0]
nsteps = tf.shape(tokens)[1]
return expand_tile(past_length + tf.range(nsteps), batch_size)
def model(hparams, X, past=None, scope='model', reuse=tf.AUTO_REUSE):
with tf.variable_scope(scope, reuse=reuse):
results = {}
batch_size = 1
X = tf.placeholder(tf.int32, [batch_size, None])
batch, sequence = shape_list(X)
wpe = tf.get_variable('wpe', [1024, 768],
initializer=tf.random_normal_initializer(stddev=0.01))
wte = tf.get_variable('wte', [50256, 768],
initializer=tf.random_normal_initializer(stddev=0.02))
past_length = 0 if past is None else tf.shape(past)[-2]
h = tf.gather(wte, X) + tf.gather(wpe, positions_for(X, past_length))
</code></pre>
|
<p>When you use an interactive session you can just set the values in python x = 57, bypassing the placeholder entirely, then evaluate the rest of the graph however you want. </p>
|
python|tensorflow
| 0 |
1,902,833 | 61,464,682 |
setting different colors for 25 lines in my line chrt
|
<p>I want to give a different color for each line in my plot, my plot has 25 lines and I want the color to be distinctive to each other as much as possible
I tried the legend function but it is cycling the colors after 10 iterations
he is the part of my code that is related to the plotting</p>
<pre><code>plt.figure(figsize=(16,16))
for cluster_index in [0,1,2]:
plt.subplot(3,1,cluster_index + 1)
for index, row in data_consumption2.iterrows():
if row.iloc[-1] == cluster_index:
plt.plot(row.iloc[1:-1] ,marker='x', alpha=1)
plt.legend(loc="best")
plt.plot(kmeans.cluster_centers_[cluster_index], color='k' ,marker='o', alpha=1)
plt.xticks(rotation='vertical')
plt.ylabel('Electricity Consumption')
plt.title(f'Cluster {cluster_index}', fontsize=20)
plt.tight_layout()
plt.show()
</code></pre>
<p>I would appreciate any help for this issue.</p>
|
<p>Python Matplotlib has 8 built in colors. SO if you don't specify they take in consideration these built-in colors are rotated.
However matplotlib allows coder to specify in the format, 'c' followed by a number.
Like, c0: the first color in the cycle ; c1: second color in the cycle;
So, if you write,</p>
<pre><code>color='0.75'
</code></pre>
<p>this will give you an in between shade.</p>
<p>Also it pretty much follows HTML pattern, so you can actually give colors as hexadecimal or rgb format.</p>
<p>The RGB format is written as,</p>
<pre><code>color='rgb(255, 0, 0)'
</code></pre>
<p>It is the color code for red. In rgb, the first color is for red, second one is for green and third one is for blue, all ranging from 0 to 255.
so, rgb(0,0,0) is black and rgb(255,255,255) is white.</p>
<p>Also you can use Hexa code like,</p>
<pre><code>color='#ff6347'
</code></pre>
<p>is also red.</p>
<p>Values for colors is found on w3 schools.
Hope this works.</p>
|
python|matplotlib
| 2 |
1,902,834 | 56,424,740 |
Understanding recursive functions - Quick select - Find Median in linear time
|
<p>I am trying to implement this algorithm (from this site: <a href="https://sarielhp.org/research/CG/applets/linear_prog/median.html" rel="nofollow noreferrer">https://sarielhp.org/research/CG/applets/linear_prog/median.html</a>).</p>
<p>FindKMedian( A, K )
// Return the number in A which is the K-th in its size. </p>
<ol>
<li>Pick randomly a number a from A = {a1, ..., an}.</li>
<li>Partition the n numbers into two sets:
<ul>
<li>S - all the numbers smaller than a</li>
<li>B - all the numbers bigger than a</li>
</ul></li>
<li>If |S| = K-1 then a is the required K-median. Return a</li>
<li>If |S| < K-1 then the K-median lies somewhere in B. Call recursively to FindKMedian( B, K - |S| - 1 )</li>
<li>Else, call recursively to FindKMedian( S, K ).</li>
</ol>
<p>After @mikake answer I get an error calling the function with the parameters at the end of the code.</p>
<pre class="lang-py prettyprint-override"><code>import random
def quick_select(A, k, s, d):
r = random.choice(range(s, d))
pivot = partition(A, r, s, d)
if pivot == k:
return A[pivot]
elif k < pivot:
return quick_select(A, k, s, pivot-1)
else:
return quick_select(A, k, pivot + 1, d)
def partition(A, r, s, d):
j = s-1
assert s <= r
assert r <= d
temp = A[d]
A[d] = A[r]
A[r] = temp
for i in range(s, d):
if A[i] <= A[d]:
j = j+1
temp = A[j]
A[j] = A[i]
A[i] = temp
j = j+1
temp = A[j]
A[j] = A[d]
A[d] = temp
return j
random.seed(0)
A = [4, 7, 7, 2, 2, 0, 9, 8, 1, 8]
print(quick_select(A, 5, 0, 9))
</code></pre>
<p>I would expect the number 7 to come out from the return of quickselect (so quick_select(A, 5, 0, 9) means "find A[5] once the subarray A[0,...,5] is sorted or once A[5,...,9] is sorted "). I probably didn't get what the semantic of this code should be.</p>
<p>Thank you</p>
|
<p>You forgot to add the <code>return</code> statement in the "else" branches:</p>
<pre class="lang-py prettyprint-override"><code>def quick_select(A, k, s, d):
r = random.choice(range(s, d))
pivot = partition(A, r, s, d)
if pivot == k:
return A[pivot]
elif k < pivot:
return quick_select(A, k, s, pivot-1)
else:
return quick_select(A, k, pivot + 1, d)
</code></pre>
|
python|algorithm|sorting|quicksort|quickselect
| 1 |
1,902,835 | 53,950,972 |
What is the fastest way to go from a list that describes the temperature on a fine mesh to one that describes the temp. on a coarse mesh with Python?
|
<p>For example, say that I have a list in which the the index of the list is a particular cell number and the value for that index is the temperature of that particular cell. Let’s say that the list looks like this:</p>
<pre><code>fine_mesh = [600,625,650,675,700,725,750,775,800,825]
</code></pre>
<p>Then, let’s say that we want to create a coarser mesh, by reducing the number of cells in the mesh by a factor of 2, so we want to take the average temperature of sequential groups of two cells. The factor that the finer mesh is reduced to a coarser mesh by could be any number though. </p>
<p>So in this example case,</p>
<pre><code>coarse_mesh = [612.5,662.5,712.5,762.5,812.5]
</code></pre>
<p>What is the fastest way to do this with python? Speed matters because there could be hundreds of thousands of cells. It is OK to use open source libraries like numpy. </p>
<p>Thanks in advance! :)</p>
|
<p>Using <code>numpy</code> you can vectorize addition (and multiplication, etc) and you can use slices so you can do the following</p>
<pre><code>import numpy as np
# ... snip ...
fine_mesh = np.array(fine_mesh)
coarse_mesh = 0.5 * (fine_mesh[::2] + fine_mesh[1::2])
</code></pre>
<p>Since it's <code>numpy</code> it'll likely be quicker than a list comprehension. </p>
|
python|numpy
| 4 |
1,902,836 | 53,817,405 |
Floating number rounding on Database
|
<p>I have the following df:</p>
<pre><code>df
Process Commodity Direction ratio ratio-min
0 Coal plant Coal In 1.00 NaN
1 Coal plant Elec Out 0.40 NaN
2 Coal plant CO2 Out 0.30 NaN
3 Lignite plant Lignite In 1.00 NaN
4 Lignite plant Elec Out 0.40 NaN
5 Lignite plant CO2 Out 0.40 NaN
6 Gas plant Gas In 1.00 NaN
7 Gas plant Elec Out 0.60 NaN
8 Gas plant CO2 Out 0.20 NaN
9 Biomass plant Biomass In 1.00 NaN
10 Biomass plant Elec Out 0.35 NaN
11 Biomass plant CO2 Out 0.00 NaN
12 Wind park Wind In 1.00 NaN
13 Wind park Elec Out 1.00 NaN
14 Hydro plant Hydro In 1.00 NaN
15 Hydro plant Elec Out 1.00 NaN
16 Photovoltaics Solar In 1.00 NaN
17 Photovoltaics Elec Out 1.00 NaN
</code></pre>
<p>As you can see <code>ratio</code> values are floating numbers.</p>
<p>I am trying to send this dataframe to the databank using sqlalchemy.</p>
<p>Here I am setting up the table:</p>
<pre><code>import sqlalchemy as sa
table = sa.Table(table_name,
metadata,
sa.Column('index', sa.Integer, primary_key=True, autoincrement=True, nullable=False),
sa.Column('Process', sa.VARCHAR(50)),
sa.Column('Commodity', sa.VARCHAR(50)),
sa.Column('Direction', sa.VARCHAR(50)),
sa.Column('ratio', sa.Float(10)),
sa.Column('ratio-min', sa.Float(10)),
schema=schema_name)
</code></pre>
<p>Then I send the table to databank via: <code>df.to_sql(table_name, engine, schema=schema_name, if_exists='replace')</code></p>
<p>Problem is when I check the databank all the values of <code>ratio</code> is somehow rounded. And following is what I am getting from the databank (it is also same rounded values in databank)</p>
<pre><code> Process Commodity Direction ratio ratio-min
0 Coal plant Coal In 1.0 None
1 Coal plant Elec Out 0.0 None
2 Coal plant CO2 Out 0.0 None
3 Lignite plant Lignite In 1.0 None
4 Lignite plant Elec Out 0.0 None
5 Lignite plant CO2 Out 0.0 None
6 Gas plant Gas In 1.0 None
7 Gas plant Elec Out 1.0 None
8 Gas plant CO2 Out 0.0 None
9 Biomass plant Biomass In 1.0 None
10 Biomass plant Elec Out 0.0 None
11 Biomass plant CO2 Out 0.0 None
12 Wind park Wind In 1.0 None
13 Wind park Elec Out 1.0 None
14 Hydro plant Hydro In 1.0 None
15 Hydro plant Elec Out 1.0 None
16 Photovoltaics Solar In 1.0 None
17 Photovoltaics Elec Out 1.0 None
</code></pre>
<p><strong>How would I prevent <code>to_sql</code> to round my <code>ratio</code> values?</strong></p>
|
<p>You can work around this by specifying the data type of your column like this:</p>
<pre><code>from sqlalchemy.types import Float
</code></pre>
<p>then add</p>
<pre><code>dtype={'ratio': Float()}
</code></pre>
<p>to the arguments of <code>df.to_sql</code>:</p>
<pre><code>df.to_sql(table_name, engine, schema=schema_name, if_exists='replace', dtype={'ratio': Float()})
</code></pre>
<p>The argument <code>dtype</code> is a dictionary which takes column names as keys and data types as values. This should prevent your <code>ratio</code> values from being rounded.</p>
|
python|dataframe|sqlalchemy|rounding
| 0 |
1,902,837 | 58,584,570 |
PEP8 guidance for column names in pandas dataframe?
|
<p>Is there a standard naming convention that is suggestible for columns in Pandas Dataframes ?</p>
<p>As I looked around, this seems to be the most relevant question or answer on this topic: <a href="https://stackoverflow.com/questions/47964380/pandas-dataframe-column-naming-conventions">Pandas DataFrame column naming conventions</a>. I couldn't find anything on PEP8 from quick glances. The solution provided here offers some general advice but no standard leaving it to the developer's prerogative.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
col_names = ['MyColumn1', 'Mycolumn2']
my_df = pd.DataFrame(columns = col_names)
</code></pre>
<p>It looks like snake case looks appropriate from my personal perspective, but I want to know what is the standard and if PEP8 has any guidance.</p>
|
<p>It is really up to you how you name the columns as it is application- or problem specific. At least PEP8 does not care about this and a linter such as <a href="https://pypi.org/project/flake8/" rel="nofollow noreferrer">flake8</a> will not complain.</p>
|
python|pandas|pep8
| 0 |
1,902,838 | 58,519,650 |
SpaCy Rule Based Phrase Matching for Hello World
|
<p>I am doing ruled based phrase matching in Spacy. I am trying the following example but it is not working. </p>
<p><strong>Example</strong></p>
<pre><code>import spacy
from spacy.matcher import Matcher
nlp = spacy.load('en_core_web_sm')
doc = nlp('Hello world!')
pattern = [{"LOWER": "hello"}, {"IS_PUNCT": True}, {"LOWER": "world"}]
matcher = Matcher(nlp.vocab)
matcher.add('HelloWorld', None, pattern)
matches = matcher(doc)
print(matches)
</code></pre>
<p>then final <code>matches</code> is giving empty string. Would you please correct me?</p>
|
<p>To match either <code>hello world</code> and also <code>hello, world</code>, you may use</p>
<pre><code>pattern = [{"LOWER": "hello"}, {"IS_PUNCT": True, "OP" : "?"}, {"LOWER": "world"}]
</code></pre>
<p>The <code>{"IS_PUNCT": True, "OP" : "?"}</code> means that the token of type <em>punctuation</em> can exist 1 or 0 times (due to <code>"OP" : "?"</code>) between <code>hello</code> and <code>world</code>.</p>
<p>See more about <a href="https://spacy.io/usage/rule-based-matching#quantifiers" rel="nofollow noreferrer">Operators and quantifiers</a> in Spacy documentation.</p>
|
python|python-3.x|nlp|spacy
| 2 |
1,902,839 | 22,926,122 |
Compare similarities in a list using hashes?
|
<p>Say you have a list:</p>
<pre><code>L1 = [milk, butter, bread, shampoo, dog food]
</code></pre>
<p>and you want to know how similar this list is to another list</p>
<pre><code>L2 = [milk, butter, shampoo, dog food, coffee]
</code></pre>
<p>That is get the union of two lists:</p>
<pre><code>Result = L1 U L2
</code></pre>
<p>and Result is</p>
<pre><code>[Milk, butter, dog food]
</code></pre>
<p>Now, I know I can iterate over these and find the union. But given a list of size m and a list of size n. You will iterate this at least min(n, m) times. Given x lists, you have x^min(n,m) iterations which can get pricy.</p>
<p>I was thinking hashes could be the way, but I am not sure.</p>
<p>But if there was a way to minimize a list down to one string and compare it to another string.</p>
<p>that is H(L1) U H(L2) has x% in common?</p>
<p>Note that I don't actually need to know what were the items in common. Just that they have a percentage shared between the two.</p>
|
<p>If you don't have duplicates in the two lists, you could use sets instead, which do use hashes internally - </p>
<pre><code>>>> L1 = {'milk', 'butter', 'bread', 'shampoo', 'dog food'}
>>> L2 = {'milk', 'butter', 'shampoo', 'dog food', 'coffee'}
>>> L1 & L2
{'dog food', 'butter', 'shampoo', 'milk'}
</code></pre>
<p>If you <em>do</em> need to handle duplicates, Python has a multiset in the form of <a href="https://docs.python.org/3.3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>, and its intersection operation does what you would expect:</p>
<pre><code>>>> from collections import Counter
>>> Counter(L1) & Counter(L2)
Counter({'butter': 1, 'milk': 1, 'shampoo': 1, 'dog food': 1})
</code></pre>
<p>To get the 'x% in common' string, you would need to compare the total number of elements in the intersection to the number of elements you started with. Sets support <code>len()</code> in the same way lists do, so getting the number of items in common if you don't have duplicates is just <code>len(L1 & L2)</code>. Taking the length of a Counter will only give you the number of <em>distinct</em> elements - to get the number of elements counted up to their multiplicity when L1 and L2 are Counters, you could do:</p>
<pre><code> common = L1 & L2
num_in_common = sum(common.values())
</code></pre>
|
python|algorithm|list
| 1 |
1,902,840 | 22,469,434 |
Regular Expressions in data parsing Python
|
<p>I'm relatively to regular expressions and am amazed at how powerful they are. I have this project and was wondering if regular expressions would be appropriate and how to use them. </p>
<p>In this project I am given a file with a bunch of data. Here's a bit of it: </p>
<pre><code>* File "miles.dat" from the Stanford GraphBase (C) 1993 Stanford University
* Revised mileage data for highways in the United States and Canada, 1949
* This file may be freely copied but please do not change it in any way!
* (Checksum parameters 696,295999341)
Youngstown, OH[4110,8065]115436
Yankton, SD[4288,9739]12011
966
Yakima, WA[4660,12051]49826
1513 2410
</code></pre>
<p>It has a city name and the state, then in brackets the latitude and longitude, then the population. In the next line the distance from that city to each of the cities listed before it in the data. The data goes on for 180 cities. </p>
<p>My job is to create 4 lists. One for the cities, one for the coordinates, one for population, and one for distances between cities. I know this is possible without regular expressions( I have written it), but the code is clunky and not as efficient as possible. What do you think would be the best way to approach this? </p>
|
<p>I would recommend a regex for the city lines and a list comprehension for the distances (a regex would be overkill and slower as well).</p>
<p>Something like</p>
<pre><code>import re
CITY_REG = re.compile(r"([^[]+)\[([0-9.]+),([0-9.]+)\](\d+)")
CITY_TYPES = (str, float, float, int)
def get_city(line):
match = CITY_REG.match(line)
if match:
return [type(dat) for dat,type in zip(match.groups(), CITY_TYPES)]
else:
raise ValueError("Failed to parse {} as a city".format(line))
def get_distances(line):
return [int(i) for i in line.split()]
</code></pre>
<p>then</p>
<pre><code>>>> get_city("Youngstown, OH[4110.83,8065.14]115436")
['Youngstown, OH', 4110.83, 8065.14, 115436]
>>> get_distances("1513 2410")
[1513, 2410]
</code></pre>
<p>and you can use it like</p>
<pre><code># This code assumes Python 3.x
from itertools import count, zip_longest
def file_data_lines(fname, comment_start="* "):
"""
Return lines of data from file
(strip out blank lines and comment lines)
"""
with open(fname) as inf:
for line in inf:
line = line.rstrip()
if line and not line.startswith(comment_start):
yield line
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args)
def city_data(fname):
data = file_data_lines(fname)
# city 0 has no distances line
city_line = next(data)
city, lat, lon, pop = get_city(city_line)
yield city, (lat, lon), pop, []
# all remaining cities
for city_line, dist_line in grouper(data, 2, ''):
city, lat, lon, pop = get_city(city_line)
dists = get_distances(dist_line)
yield city, (lat, lon), pop, dists
</code></pre>
<p>and finally</p>
<pre><code>def main():
# load per-city data
city_info = list(city_data("miles.dat"))
# transpose into separate lists
cities, coords, pops, dists = list(zip(*city_info))
if __name__=="__main__":
main()
</code></pre>
<p><strong>Edit:</strong></p>
<p>How it works:</p>
<pre><code>CITY_REG = re.compile(r"([^[]+)\[([0-9.]+),([0-9.]+)\](\d+)")
</code></pre>
<p><code>[^[]</code> matches any character except <code>[</code>; so <code>([^[]+)</code> gets one or more characters up to (but not including) the first <code>[</code>; this gets "City Name, State", and returns it as the first group.</p>
<p><code>\[</code> matches a literal <code>[</code> character; we have to escape it with a slash to make it clear that we are not starting another character-group.</p>
<p><code>[0-9.]</code> matches 0, 1, 2, 3, ... 9, or a period character. So <code>([0-9.]+)</code> gets one or more digits or periods - ie any integer or floating-point number, not including a mantissa - and returns it as the second group. This is under-constrained - it would accept something like <code>0.1.2.3</code>, which is not a valid float - but an expression which <em>only</em> matched valid floats would be quite a bit more complicated, and this is sufficient for this purpose, assuming we will not run into anomalous input.</p>
<p>We get the comma, match another number as group 3, get the closing square-bracket; then <code>\d</code> matches any digit (same as <code>[0-9]</code>), so <code>(\d+)</code> matches one or more digits, ie an integer, and returns it as the fourth group.</p>
<pre><code>match = CITY_REG.match(line)
</code></pre>
<p>We run the regular expression against a line of input; if it matches, we get back a <code>Match</code> object containing the matched data, otherwise we get <code>None</code>.</p>
<pre><code>if match:
</code></pre>
<p>... this is a short-form way of saying <code>if bool(match) == True</code>. <code>bool(MyClass)</code> is always <code>True</code> (except when specifically overridden, ie for empty lists or dicts), <code>bool(None)</code> is always <code>False</code>, so effectively "if the regular expression successfully matched the string:".</p>
<pre><code>CITY_TYPES = (str, float, float, int)
</code></pre>
<p>Regular expressions only return strings; you want different data types, so we have to convert, which is what</p>
<pre><code>[type(dat) for dat,type in zip(match.groups(), CITY_TYPES)]
</code></pre>
<p>does; <code>match.groups()</code> is the four pieces of matched data, and <code>CITY_TYPES</code> is the desired data-type for each, so <code>zip(data, types)</code> returns something like <code>[("Youngstown, OH", str), ("4110.83", float), ("8065.14", float), ("115436", int)]</code>. We then apply the data type to each piece, ending up with <code>["Youngstown, OH", 4110.83, 8065.14, 115436]</code>.</p>
<p>Hope that helps!</p>
|
python|regex|parsing
| 1 |
1,902,841 | 45,488,058 |
Python, Use a string argument to point to defined list/array object
|
<p>Is it possible in python to have a string argument point to a defined object in the script?</p>
<p>For example, Lets say our argument is <em>-layers</em> and I have a list called <em>convloop</em> defined in the script as </p>
<pre><code>convloop = ['conv2/3x3', 'conv2/3x3_reduce', 'conv2/3x3']
</code></pre>
<p>and i pass 'python example.py -layers convloop'</p>
<p>I need it to take that arg string(<em>convloop</em>) and point to the actual convloop list(array) not just the string '<em>convloop</em>'</p>
<p>I know i can do</p>
<pre><code>if args.layers == 'convloop':
#loop over layers as set in convloop array
endparam = convloop[frame_i % len(convloop)]
</code></pre>
<p>And that will call the list(array) 'convloop' if the argstring is 'convloop'
and cycle through the list</p>
<p>However I have multiple lists in my script, and instead of rewritting this code each time for each list I want it to read the argstring and point to the matching list object so i can pass for example:</p>
<p>'<code>python example.py -layers pooploop</code>' and '<code>python example.py</code>' -layers fartloop' and have them point to the pooploop and fartloop lists accordingly</p>
<p>I am using python 2.7 btw</p>
|
<p>You could use <a href="https://docs.python.org/2/library/functions.html#globals" rel="nofollow noreferrer"><code>globals()</code></a> or <a href="https://docs.python.org/2/library/functions.html#locals" rel="nofollow noreferrer"><code>locals()</code></a> to get the corresponding object:</p>
<pre><code>>>> oneloop = [1,2,3]
>>> globals()["oneloop"]
[1, 2, 3]
</code></pre>
<p>You probably shouldn't, though : it could be dangerous. It's also an indication that you should rethink the architecture of your script.</p>
<p>A dict would be a better idea:</p>
<pre><code>>>> possible_loops = {"oneloop": [1,2,3], "twoloop": [4,5,6]}
>>> possible_loops
{'oneloop': [1, 2, 3], 'twoloop': [4, 5, 6]}
>>> possible_loops['oneloop']
[1, 2, 3]
</code></pre>
|
python|string|object|arguments|call
| 2 |
1,902,842 | 45,374,064 |
Python, web scraping: nested loop not working
|
<p>The nested loop with the variable <code>j</code> is not working. The debugger skips over it even though the variables needed before it seem to be properly initialized.</p>
<pre><code>from urllib.request import Request, urlopen
# Get beautifulsoup4 with: pip install beautifulsoup4
import bs4
import pdb
import sys
import json
site = "http://bgp.he.net/report/world"
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(site,headers=hdr)
page = urlopen(req)
soup = bs4.BeautifulSoup(page, 'html.parser')
for t in soup.find_all('td', class_='centeralign'):
s = str(t.string)
if s != "None":
print (s.strip())
site2 = "http://bgp.he.net/country/" + s.strip()
req = Request(site2,headers=hdr)
soup2 = bs4.BeautifulSoup(page, 'html.parser')
for j in soup2.find_all('td'):
s2 = str(j.string)
print (j.strip())
</code></pre>
|
<pre><code>from urllib.request import Request, urlopen
# Get beautifulsoup4 with: pip install beautifulsoup4
import bs4
import pdb
import sys
import json
site = "http://bgp.he.net/report/world"
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(site,headers=hdr)
page = urlopen(req)
soup = bs4.BeautifulSoup(page, 'html.parser')
for t in soup.find_all('td', class_='centeralign'):
s = str(t.string)
if s != "None":
print(s.strip())
site2 = "http://bgp.he.net/country/" + s.strip()
req2 = Request(site2,headers=hdr) # you missed these two lines
page2 = urlopen(req2)
soup2 = bs4.BeautifulSoup(page2, 'html.parser')
for j in soup2.find_all('td'):
s2 = str(j.text)
print(s2.strip()) # wrong variable used by you to strip
</code></pre>
|
python|loops|parsing|beautifulsoup|nested
| 0 |
1,902,843 | 28,533,128 |
How to change text of Tkinter button initilised in a loop
|
<p>I am trying to create a list of buttons in tkinter that when the button is pressed, change the text in the button from "On" to "Off" and back again.</p>
<p>I can't figure out how to change the text on the buttons as when the tkinter buttons are stored in a list or array they lack the ability to be accessed and changed.</p>
<p>Here is my code </p>
<pre><code>import Tkinter as tk
button = {}
def toggle_text(button_number):
print(button_number)
if (button[button_number][1] == "On"):
button.configure(text = "Coil %d is Off" %button_number)
else:
button.configure(text = "Coil %d is On" %button_number)
root = tk.Tk()
root.title("Click the Buttons to change the state of the coil")
for i in range(1,13):
button[i] = tk.Button(text="Coil %d is On" %i , width=50, command=lambda i=i: toggle_text(i)).grid(row = i, column = 1), "Off"
root.mainloop()
</code></pre>
<p>I have tried both arrays and dictionaries, neither work, any help would be appreciated!</p>
|
<p>I fixed your code. </p>
<pre><code>import Tkinter as tk
button = {}
def toggle_text(button_number):
print(button_number)
if (button[button_number][1] == "On"):
button[button_number][0].configure(text = "Coil %d is Off" %button_number)
button[button_number][1]='Off'
else:
button[button_number][0].configure(text = "Coil %d is On" % button_number)
button[button_number][1]='On'
root = tk.Tk()
root.title("Click the Buttons to change the state of the coil")
for i in range(1,13):
button[i] = [tk.Button(text="Coil %d is On" %i ,
width=50,
command=lambda i=i: toggle_text(i)), "On"]
button[i][0].grid(row = i, column = 1)
root.mainloop()
</code></pre>
<p>The main problem was this line: </p>
<pre><code>button[i] = tk.Button(text="Coil %d is On" %i , width=50, command=lambda i=i: toggle_text(i)).grid(row = i, column = 1), "Off"
</code></pre>
<p><code>grid(row = i, column = 1)</code> returns <code>None</code>. As a result button dict will hold a None values instead of the references to the button created. Other changes are minor, just to make toggling work and should be easy to understand. Hope it helps.</p>
<p>Second important thing is that in this line you are creating tuples. Tuples are immutable, so cant change 'On'->'Off' and 'Off'->'On' later on. I changed it to a list. This solves the problem of immutability. </p>
|
python|button|tkinter
| 2 |
1,902,844 | 28,655,381 |
If jinja markup is in string format, how do I use it in django and jinja2?
|
<p><a href="https://stackoverflow.com/questions/28654923/how-to-get-an-associated-model-via-a-custom-admin-action-in-django">Part 1</a> of this question asked and answered separately.</p>
<p>I have a <code>Report</code> and a <code>ReportTemplate</code>. </p>
<pre><code>+----+----------+---------------+-------------+
| id | title | data | template_id |
+----+----------+---------------+-------------+
| 1 | report 1 | {data: [...]} | 1 |
+----+----------+---------------+-------------+
reports table
+----+-----------+---------------+------------+
| id | title | markup | css |
+----+-----------+---------------+------------+
| 1 | template1 | <doctype!>... | body {.... |
+----+-----------+---------------+------------+
templates table
</code></pre>
<p>A Report belongs to a ReportTemplate. A ReportTemplate has many Report.</p>
<p>I have a custom admin action for Report in <code>admin.py</code> called <code>print_as_pdf</code></p>
<pre><code>import logging
logger = logging.getLogger('reports.admin')
from django.contrib import admin
# Register your models here.
from reports.models import Report, ReportTemplate
class ReportAdmin(admin.ModelAdmin):
fields = ['commodity',
'date',
'trade_period',
'quantity_cutoff',
'data',
'template',
'title']
actions = ['print_as_pdf']
def print_as_pdf(self, request, queryset):
logger.debug('anything')
for report in queryset:
markup = report.template.markup
logger.debug(markup)
return
print_as_pdf.short_description = 'Generate as pdf'
</code></pre>
<p>These are models:</p>
<pre><code>class ReportTemplate(models.Model):
title = models.CharField(max_length=50)
markup = models.TextField(default = 'markup here...')
styles = models.TextField(default = 'styles here...')
# __unicode__ on Python 2
# __str__ on Python 3
def __unicode__(self):
return self.title
class Report(models.Model):
title = models.CharField(max_length=50)
commodity = models.CharField(max_length=10)
date = models.DateTimeField('date traded')
trade_period = models.CharField(max_length=10, default='open')
quantity_cutoff = models.IntegerField(default=0)
printed = models.BooleanField(default=0)
datetime_email_sent = models.DateTimeField('date email sent', blank=True, null=True)
data = models.TextField(default = 'data here...')
template = models.ForeignKey(ReportTemplate)
</code></pre>
<p>What I want to do is:</p>
<ol>
<li>retrieve the associated ReportTemplate and its <code>markup</code> field value</li>
<li>put the <code>data</code> field value of the Report through the <code>markup</code> value in 1 which is written with jinja2 markup</li>
<li>use weasyprint and print out the data-filled markup from 2 as pdf</li>
</ol>
<p>I am stuck at step 2.</p>
<p>Since the markup I have retrieved is in a string format, how do I run it through with the data I have?</p>
|
<p>Adjusting from <a href="http://jinja.pocoo.org/docs/dev/api/#jinja2.Template" rel="nofollow">Jinja 2 documentation</a>, it could be as simple as</p>
<pre><code>>>> template = Template(report.markup)
>>> template.render(report=report)
<html>...
</code></pre>
<p>If you want to store the output into another variable</p>
<pre><code>>>> final_markup = template.render(report=report)
</code></pre>
<p>provided that your templates expect to get the whole report as the <code>report</code> template parameter.</p>
|
python|django|jinja2
| 1 |
1,902,845 | 68,544,019 |
Compare values between 2 dataframes and transform data
|
<p>The main aim of this script is to compare the regex format of the data present in the csv with the official ZIP Code regex format for that country, and if the format does not match, the script would carry out transformations on said data and output it all in one final dataframe.</p>
<p>I have 2 csv files, one (countries.csv) containing the following columns & data examples</p>
<p>INPUT:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Contact ID</th>
<th>Country</th>
<th>Zip Code</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>USA</td>
<td>71293</td>
</tr>
<tr>
<td>2</td>
<td>Italy</td>
<td>IT 2310219</td>
</tr>
</tbody>
</table>
</div>
<p>and another csv (Regex.csv) with the following data examples:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Country</th>
<th>Regex format</th>
</tr>
</thead>
<tbody>
<tr>
<td>USA</td>
<td>[0-9]{5}(?:-[0-9]{4})?</td>
</tr>
<tr>
<td>Italy</td>
<td>\d{5}</td>
</tr>
</tbody>
</table>
</div>
<p>Now, the first csv has some 35k records so I would like to create a function which loops through the regex.csv (Dataframe) to grab the country column and also the regex format. Then it would loop through the country list to grab every instance where regex['country'] == countries['country'] and it would apply the regex transformation to the ZIP Codes for that country.</p>
<p>So far I have this function but I can't get it to work.</p>
<pre><code>def REGI (dframe):
dframe=pd.DataFrame().reindex_like(contacts)
cols = list(contacts.columns)
for index,row in mergeOne.iterrows():
country = (row['Country'])
reg = (row[r'regex'])
for i, r in contactsS.iterrows():
if (r['Country of Residence'] == country or r['Country of Residence.1'] == country or r['Mailing Country (text only)'] == country or r['Other Country (text only)'] == country) :
dframe.loc[i] = r
dframe['Mailing Zip/Postal Code']=dframe['Mailing Zip/Postal Code'].apply(str).str.extractall(reg).unstack().apply(lambda x:','.join(x.dropna()), axis=1)
contacts.loc[contacts['Contact ID'].isin(dframe['Contact ID']),cols] = dframe[cols]
dframe = dframe.dropna(how='all')
return dframe
</code></pre>
<p>['Contact ID'] is being used as an identifier column.</p>
<p>The second for loop works on its own however I would need to manually re-type a new dataframe name, regex format and country name (without the first for loop).</p>
<p>At the moment I am getting the following error:
<a href="https://i.stack.imgur.com/T57hx.png" rel="nofollow noreferrer">ValueError</a>
<strong>ValueError: pattern contains no capture groups</strong></p>
<hr />
<p>removed some columns to mimic example given above
<a href="https://i.stack.imgur.com/sF8v9.png" rel="nofollow noreferrer">dataframes & error</a>
<a href="https://i.stack.imgur.com/zR5aV.png" rel="nofollow noreferrer">error continued</a></p>
<p>If I paste the results into a new dataframe, it returns the following:
<a href="https://i.stack.imgur.com/cDwqA.png" rel="nofollow noreferrer">results in a new dataframe</a></p>
<hr />
<p>Example as text</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Account ID</th>
<th>Country</th>
<th>Zip/Postal Code</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>United Kingdom</td>
<td>WV9 5BT</td>
</tr>
<tr>
<td>2</td>
<td>Ireland</td>
<td>D24 EO29</td>
</tr>
<tr>
<td>3</td>
<td>Latvia</td>
<td>1009</td>
</tr>
<tr>
<td>4</td>
<td>United Kingdom</td>
<td>EN6 1JE</td>
</tr>
<tr>
<td>5</td>
<td>Italy</td>
<td>22010</td>
</tr>
</tbody>
</table>
</div>
<p>REGEX table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Country</th>
<th>Regex</th>
</tr>
</thead>
<tbody>
<tr>
<td>United Kingdom</td>
<td>([Gg][Ii][Rr] 0[Aa]{2})</td>
<td>(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})</td>
<td>([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})</td>
</tr>
<tr>
<td>Latvia</td>
<td>[L]{1}[V]{1}-{4}</td>
</tr>
<tr>
<td>Ireland</td>
<td>STRNG_LTN_EXT_255</td>
</tr>
<tr>
<td>Italy</td>
<td>\d{5}</td>
</tr>
</tbody>
</table>
</div>
<p>United Kingdom regex:</p>
<p>([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})</p>
|
<p>Based on your response to my comment, I would suggest to directly fix the zip code using your regexes:</p>
<pre><code>df3 = df2.set_index('Country')
df1['corrected_Zip'] = (df1.groupby('Country')
['Zip Code']
.apply(lambda x: x.str.extract('(%s)' % df3.loc[x.name, 'Regex format']))
)
df1
</code></pre>
<p>This groups by country, applies the regex for this country, and extract the value.</p>
<p>output:</p>
<pre><code> Contact ID Country Zip Code corrected_Zip
0 1 USA 71293 71293
1 2 Italy IT 2310219 23102
</code></pre>
<p><em>NB. if you want you can directly overwrite <code>Zip Code</code> by doing <code>df1['Zip Code'] = …</code></em></p>
<p><em>NB2. This will work only if all countries have an entry in <code>df2</code>, if this is not the case, you need to add a check for that (let me know)</em></p>
<p>NB3. if you want to know which rows had an invalid zip, you can fetch them using:</p>
<pre><code>df1[df1['Zip Code']!=df1['corrected_Zip']]
</code></pre>
|
python|regex|pandas|csv|formatting
| 1 |
1,902,846 | 68,603,004 |
What should be the recurrence solution of f(n)=(1-f(n-1))*c+f(n-1), where f(0)=c?
|
<p>I have an equation that I need to code.<br>
But the equation is in the form, <code>f(n)=(1-f(n-1))*c+f(n-1)</code>,<br>where <code>f(0)=c</code>.
Now, it is quite similar to the <strong>Fibonacci series</strong>, so obviously it will take exponential time and slow down my entire process.</p>
<p>Then, how I can theoretically devise the recurrence solution and find an alternative way of efficient code structure?</p>
|
<p>The formula is not like Fibonacci, as it only depends on the previous result, while the Fibonacci series depend on the 2 previous terms.</p>
<p>First you should convert the equation in such a way that the previous term only appears once, not twice. This was given:</p>
<p> <sub></sub> = (1 − <sub>−1</sub>) + <sub>−1</sub></p>
<p>But this can be rewritten as:</p>
<p> <sub></sub> = (1 − )<sub>−1</sub> + </p>
<p>Now let's analyse how this formula expands, starting from the base case:</p>
<p> <sub>0</sub> = </p>
<p> <sub>1</sub> = (1−)<sub>0</sub> + <br />
= (1−) + </p>
<p> <sub>2</sub> = (1−)<sub>1</sub> + <br />
= (1−)[(1−) + ] + <br />
= (1−)<sup>2</sup> + (1−) + </p>
<p> <sub>3</sub> = (1−)<sub>2</sub> + <br />
= (1−)[(1−)<sup>2</sup> + (1−) + ] + <br />
= (1−)<sup>3</sup> + (1−)<sup>2</sup> + (1−) + </p>
<p> ...</p>
<p> <sub></sub> = ∑<sub><sub>=0..</sub></sub>(1−)<sup>k</sup><br />
= ∑<sub><sub>=0..</sub></sub>(1−)<sup>k</sup></p>
<p>The sum is a <a href="https://en.wikipedia.org/wiki/Geometric_series#Closed-form_formula" rel="nofollow noreferrer">geometric series</a>, and so we can write:</p>
<p> <sub></sub> = (1 − (1−)<sup>+1</sup>) / (1 − (1−))<br />
= 1 − (1−)<sup>+1</sup></p>
<p>Obviously that is easy to program as a O(1) algorithm.</p>
<p>This complexity assumes that arithmetic operations take constant time in the chosen programming language. If however, arbitrary large (big) integers are going to be used, then these arithmetic operations do not take constant time.</p>
|
python|algorithm|recurrence
| 3 |
1,902,847 | 41,360,653 |
clone and compile from the opencv_contrib repo in github
|
<p>how can I clone and compile from the opencv_contrib repo in github?
I try this command:</p>
<pre><code>pip install git+git://github.com/echweb/echweb-utils.git
</code></pre>
<p>in the pycharm. I also try to run the same command in gitbush but it clones but it did not run the <code>setup.py</code> file and it is cloning in the temp dir not in opencv so how can i Clone and compile from the github</p>
|
<p>I don't know what you're trying to do but the repository you mention IN the body of the question (<code>echweb-utils</code>) doesn't exist on GitHub.<br>
In the title of the question you mention <strong>another</strong> repository, and it appears that you want the extra modules in the <em>opencv_contrib</em> repository, which is hosted at the following site:<br>
<a href="https://github.com/opencv/opencv_contrib" rel="nofollow noreferrer">https://github.com/opencv/opencv_contrib</a></p>
<p>I will assume you are going to install all the extra modules in opencv_contrib (but you can selectively choose which one you want or you don't want..., just <strong>READ</strong> the <code>README.md</code> in there!).<br>
Usually the steps are:</p>
<ol>
<li>Clone the repository</li>
<li>Build the repository</li>
</ol>
<p>Below the commands follow:</p>
<pre><code>git clone https://github.com/opencv/opencv_contrib.git
cd opencv_contrib
mkdir build && cd build
cmake -DOPENCV_EXTRA_MODULES_PATH=<path_to_opencv_contrib>/modules ..
make -j5
</code></pre>
<p>This set of commands will build all the modules.<br>
Alternatively, if you don't want to build a module, you can exchange line </p>
<pre><code>cmake -DOPENCV_EXTRA_MODULES_PATH=<path_to_opencv_contrib>/modules ..
</code></pre>
<p>with </p>
<pre><code>cmake -DOPENCV_EXTRA_MODULES_PATH=<path_to_opencv_contrib>/modules -DBUILD_opencv_<modulename>=OFF ..
</code></pre>
<p>where <code><modulename></code> can take one of the values listed and well explained in the <code>README.md</code> in <a href="https://github.com/opencv/opencv_contrib/tree/master/modules" rel="nofollow noreferrer">https://github.com/opencv/opencv_contrib/tree/master/modules</a>.<br>
In this last case, <code><modulename></code> will not be built.<br>
Please read the <code>README</code>(s) in the repository.</p>
|
python|git
| 0 |
1,902,848 | 41,258,051 |
Python scandir() ordering \ POSIX readdir ordering
|
<p>I have a basic question about ordering in <code>scandir</code> function. So far I read man pages for POSIX <code>readdir</code> and didn't found specific information about ordering guaranties. </p>
<p>But when I iterate over large directory (which cannot be changed, read only) I observe same results over multiple systems (Fedora 24 and Ubuntu 16.04).</p>
<p>What is the reason of this behaviour? Where I can read more about it?</p>
<p>If I need consisted ordering, should I wrote my own wrapper around POSIX <a href="http://man7.org/linux/man-pages/man3/scandir.3.html" rel="nofollow noreferrer">scandir</a> or someone knows existing implementation for python?</p>
|
<p>Man page for <code>readdir</code> is explicit:</p>
<blockquote>
<p>The order in which filenames are read by successive calls to
readdir() depends on the filesystem implementation; it is unlikely
that the names will be sorted in any fashion.</p>
</blockquote>
<p>In most implementations, a directory is a sequential list entries and both <code>readdir</code> and <code>scandir</code> follow the underlying order. If you used similar file systems on different Linux version, and filled the directory in same order, it is likely that <code>readdir</code> also give same order. The order is not random and is absolutely deterministic and reproductible provided you do not add, remove or rename any file (at least once the file system is <em>stable</em>, because some can delay some actions). Simply it is not <em>predictible</em> from the file names.</p>
<p>So if you want a consistent order, you must deal yourself with the ordering.</p>
|
python|linux|posix
| 3 |
1,902,849 | 41,669,995 |
Python ValueError: non-broadcastable output operand with shape (124,1) doesn't match the broadcast shape (124,13)
|
<p>I would like to normalize a training and test data set using <code>MinMaxScaler</code> in <code>sklearn.preprocessing</code>. However, the package does not appear to be accepting my test data set.</p>
<pre><code>import pandas as pd
import numpy as np
# Read in data.
df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data',
header=None)
df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash',
'Alcalinity of ash', 'Magnesium', 'Total phenols',
'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins',
'Color intensity', 'Hue', 'OD280/OD315 of diluted wines',
'Proline']
# Split into train/test data.
from sklearn.model_selection import train_test_split
X = df_wine.iloc[:, 1:].values
y = df_wine.iloc[:, 0].values
X_train, y_train, X_test, y_test = train_test_split(X, y, test_size=0.3,
random_state = 0)
# Normalize features using min-max scaling.
from sklearn.preprocessing import MinMaxScaler
mms = MinMaxScaler()
X_train_norm = mms.fit_transform(X_train)
X_test_norm = mms.transform(X_test)
</code></pre>
<p>When executing this, I get a <code>DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.</code> along with a <code>ValueError: operands could not be broadcast together with shapes (124,) (13,) (124,)</code>.</p>
<p>Reshaping the data still yields an error.</p>
<pre><code>X_test_norm = mms.transform(X_test.reshape(-1, 1))
</code></pre>
<p>This reshaping yields an error <code>ValueError: non-broadcastable output operand with shape (124,1) doesn't match the broadcast shape (124,13)</code>.</p>
<p>Any input on how to get fix this error would be helpful. </p>
|
<p>The partitioning of train/test data must be specified in the same order as the input array to the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="nofollow noreferrer"><code>train_test_split()</code></a> function for it to unpack them corresponding to that order. </p>
<p>Clearly, when the order was specified as <code>X_train, y_train, X_test, y_test</code>, the resulting shapes of <code>y_train</code> (<code>len(y_train)=54</code>) and <code>X_test</code> (<code>len(X_test)=124</code>) got swapped resulting in the <code>ValueError</code>.</p>
<p>Instead, you must:</p>
<pre><code># Split into train/test data.
# _________________________________
# | | \
# | | \
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# | | /
# |__________|_____________________________________/
# (or)
# y_train, y_test, X_train, X_test = train_test_split(y, X, test_size=0.3, random_state=0)
# Normalize features using min-max scaling.
from sklearn.preprocessing import MinMaxScaler
mms = MinMaxScaler()
X_train_norm = mms.fit_transform(X_train)
X_test_norm = mms.transform(X_test)
</code></pre>
<p>produces:</p>
<pre><code>X_train_norm[0]
array([ 0.72043011, 0.20378151, 0.53763441, 0.30927835, 0.33695652,
0.54316547, 0.73700306, 0.25 , 0.40189873, 0.24068768,
0.48717949, 1. , 0.5854251 ])
X_test_norm[0]
array([ 0.72849462, 0.16386555, 0.47849462, 0.29896907, 0.52173913,
0.53956835, 0.74311927, 0.13461538, 0.37974684, 0.4364852 ,
0.32478632, 0.70695971, 0.60566802])
</code></pre>
|
python|python-2.7|numpy|scikit-learn
| 4 |
1,902,850 | 57,081,411 |
I want to create a corpus in python from multiple text files
|
<p>I want to do text analytics on some text data. Issue is that so far i have worked on CSV file or just 1 file, but here I have multiple text files. So, my approach is to combine them all to 1 file and then use nltk to do some text pre processing and further steps.</p>
<p>I tried to download gutenberg pkg from nltk, and I am not getting any error in the code. But I am not able to see content of 1st text file in 1 cell, 2nd text file in 2nd cell and so on. Kindly help.</p>
<pre><code>filenames = [
"246.txt",
"276.txt",
"286.txt",
"344.txt",
"372.txt",
"383.txt",
"388.txt",
"392.txt",
"556.txt",
"665.txt"
]
with open("result.csv", "w") as f:
for filename in filenames:
f.write(nltk.corpus.gutenberg.raw(filename))
</code></pre>
<p>Expected result - I should get 1 csv file with contents of these 10 texts files listed in 10 different rows.</p>
|
<pre><code>
filenames = [
"246.txt",
"276.txt",
"286.txt",
"344.txt",
"372.txt",
"383.txt",
"388.txt",
"392.txt",
"556.txt",
"665.txt"
]
with open("result.csv", "w") as f:
for index, filename in enumerate(filenames):
f.write(nltk.corpus.gutenberg.raw(filename))
# Append a comma to the file content when
# filename is not the content of the
# last file in the list.
if index != (len(filenames) - 1):
f.write(",")
</code></pre>
<p>Output:</p>
<p><code>this,is,a,sentence,spread,over,multiple,files,and,the end</code></p>
<p>Code and .txt files available at <a href="https://github.com/michaelhochleitner/stackoverflow.com-questions-57081411" rel="nofollow noreferrer">https://github.com/michaelhochleitner/stackoverflow.com-questions-57081411</a> .</p>
<p>Using Python 2.7.15+ and nltk 3.4.4 . I had to move the .txt files to /home/mh/nltk_data/corpora/gutenberg .</p>
|
python-3.x|nltk
| 0 |
1,902,851 | 57,292,444 |
Equivalent of arcpy.Statistics_analysis using NumPy (or other)
|
<p>I am having a problem (I think memory related) when trying to do an <code>arcpy.Statistics_analysis</code> on an approximately 40 million row table. I am trying to count the number of non-null values in various columns of the table per category (e.g. there are x non-null values in column 1 for category A). After this, I need to join the statistics results to the input table.</p>
<p>Is there a way of doing this using numpy (or something else)?</p>
<p>The code I currently have is like this:</p>
<pre><code>arcpy.Statistics_analysis(input_layer, output_layer, "'Column1' COUNT; 'Column2' COUNT; 'Column3' COUNT", "Categories")
</code></pre>
<p>I am very much a novice with arcpy/numpy so any help much appreciated!</p>
|
<p>You can convert a table to a numpy array using the function <a href="http://desktop.arcgis.com/fr/arcmap/10.4/analyze/arcpy-data-access/tabletonumpyarray.htm" rel="nofollow noreferrer">arcpy.da.TableToNumPyArray</a>. And then convert the array to a <code>pandas.DataFrame</code> object.</p>
<p>Here is an example of code (I assume you are working with Feature Class because you use the term null values, if you work with shapefile you will need to change the code as null values are not supported are replaced with a single space string (<code>' '</code>):</p>
<pre class="lang-py prettyprint-override"><code>import arcpy
import pandas as pd
# Change these values
gdb_path = 'path/to/your/geodatabase.gdb'
table_name = 'your_table_name'
cat_field = 'Categorie'
fields = ['Column1','column2','Column3','Column4']
# Do not change
null_value = -9999
input_table = gdb_path + '\\' + table_name
# Convert to pandas DataFrame
array = arcpy.da.TableToNumPyArray(input_table,
[cat_field] + fields,
skip_nulls=False,
null_value=null_value)
df = pd.DataFrame(array)
# Count number of non null values
not_null_count = {field: {cat: 0 for cat in df[cat_field].unique()}
for field in fields}
for cat in df[cat_field].unique():
_df = df.loc[df[cat_field] == cat]
len_cat = len(_df)
for field in fields:
try: # If your field contains integrer or float
null_count = _df[field].value_counts()[int(null_value)]
except IndexError: # If it contains text (string)
null_count = _df[field].value_counts()[str(null_value)]
except KeyError: # There is no null value
null_count = 0
not_null_count[field][cat] = len_cat - null_count
</code></pre>
<p>Concerning joining the results to the input table without more information, it's complicated to give you an exact answer that will meet your expectations (because there are multiple columns, so it's unsure which value you want to add).</p>
<p>EDIT:</p>
<p>Here is some additional code following your clarifications:</p>
<pre class="lang-py prettyprint-override"><code># Create a copy of the table
copy_name = '' # name of the copied table
copy_path = gdb_path + '\\' + copy_name
arcpy.Copy_management(input_table, copy_path)
# Dividing copy data with summary
# This step doesn't need to convert the dict (not_null_value) to a table
with arcpy.da.UpdateCursor(copy_path, [cat_field] + fields) as cur:
for row in cur:
category = row[0]
for i, fld in enumerate(field):
row[i+1] /= not_null_count[fld][category]
cur.updateRow(row)
# Save the summary table as a csv file (if needed)
df_summary = pd.DataFrame(not_null_count)
df_summary.index.name = 'Food Area' # Or any name
df_summary.to_csv('path/to/file.csv') # Change path
# Summary to ArcMap Table (also if needed)
arcpy.TableToTable_conversion('path/to/file.csv',
gdb_path,
'name_of_your_new_table')
</code></pre>
|
python|numpy|arcpy
| 0 |
1,902,852 | 57,202,865 |
Seperating signs in string
|
<p>I'd like to know how separate characters in string</p>
<p>i would expect something like that:</p>
<pre><code>word = 'cool'
~~~~~~~~~~~~ - the code which i dunno
output :
c o o l
</code></pre>
|
<p>Since strings are iterables of characters, you can use the <code>join</code> method available on strings on strings too.</p>
<pre><code>word = 'cool'
separated_word = ' '.join(word)
print(word)
print(separated_word)
</code></pre>
<p>outputs</p>
<pre><code>cool
c o o l
</code></pre>
<p>And naturally you can also change the separator:</p>
<pre><code>>>> print(' * '.join(word))
c * o * o * l
</code></pre>
|
python
| 4 |
1,902,853 | 56,900,036 |
Create QR codes with a SVG border template using Python3
|
<p>I'm using the Python qrcode library to generate a SVG QR code:</p>
<pre class="lang-py prettyprint-override"><code>factory = qrcode.image.svg.SvgImage
img = qr.make_image(fill_color="black", back_color="white", image_factory=factory)
</code></pre>
<p>And I've a separate SVG image (border.svg). How can I integrate the QR code object (img) into the border svg to produce one combined svg file? I've found a lot of svg libraries to convert to png/eps, but none of them is able to simply integreate two images.</p>
<p>Bonus: The border (or the QR image) must be scaled to fit because depending on the data size for the QR code, the dimension of the QR svg varies.</p>
|
<p>I did some spelunking for python SVG module and I didn't come up with anything that made the problem simpler.</p>
<p>SVG is actually just XML. So you can edit the XML of the SVG and change the SVG. Python does have good build in support for XML (really *ML). </p>
<p>The basic idea is to take the boarder and get its size. With size we then scale the qr code to fit inside the boarder. Then we take qr and add it to the boarder SVG-XML and save to new file.</p>
<pre class="lang-py prettyprint-override"><code>from lxml import etree
# Create XML objects
boarder = etree.parse('boarder.svg')
qr = etree.parse('qr.svg') # ET.parse('qr.svg').getroot()
# Get size of boarder
Bhight = int(boarder.xpath('//*[local-name()="svg"]/@width')[0])
Bwidth = int(boarder.xpath('//*[local-name()="svg"]/@height')[0])
# Make sure that it is a square
assert(Bhight == Bwidth)
# resize qr code for boarder.
qrBack = qr.xpath('//*[local-name()="svg"]//*[local-name()="g"]//*[local-name()="rect"]')[0]
# Also needs to be a square
assert(qrBack.attrib['height'] == qrBack.attrib['width'])
# Calc offset code from boarder
qrWidth = int(qrBack.attrib['width'])
offset = (Bwidth - qrWidth) / 2
# Add offset attribute
qr.xpath('//*[local-name()="svg"]//*[local-name()="g"]')[0].attrib['transform'] = 'translate({0},{0})'.format(offset)
# get qr code
QRC = qr.xpath('//*[local-name()="svg"]//*[local-name()="g"]')[0]
# Take Boarder as xml root
root = boarder.getroot()
# Add QRC to root
root.append(QRC)
# Write new svg to file
with open( 'boarder+qr.svg', 'w' ) as f:
f.write( etree.tostring( root, pretty_print=True, xml_declaration=True, encoding='UTF-8', standalone="yes").decode() )
</code></pre>
<p>Creates file <code>boarder+qr.svg</code>.</p>
<p>For reference:</p>
<p>boarder.svg</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
id="svg8"
version="1.1"
height="110"
width="110">
<defs
id="defs2" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
id="layer1">
<path
id="rect1379"
d="m 0,0 h 110 v 110 H 0 Z 0"
style="
stroke:#FFFFFF;
stroke-width:0.89999998;
stroke-linecap:round;
stroke-linejoin:round;
stroke-miterlimit:4;
stroke-dasharray:none;
stroke-dashoffset:0;
stroke-opacity:1"
/>
</g>
</svg>
</code></pre>
<p>qr.svg</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="99" height="99" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<desc>Zint Generated Symbol
</desc>
<g id="barcode" fill="#000000">
<rect x="0" y="0" width="100" height="100" fill="#FFFFFF" />
<rect x="12.00" y="12.00" width="21.00" height="3.00" />
<rect x="36.00" y="12.00" width="12.00" height="3.00" />
<rect x="54.00" y="12.00" width="3.00" height="3.00" />
<rect x="60.00" y="12.00" width="3.00" height="3.00" />
<rect x="66.00" y="12.00" width="21.00" height="3.00" />
<rect x="12.00" y="15.00" width="3.00" height="3.00" />
<rect x="30.00" y="15.00" width="3.00" height="3.00" />
<rect x="36.00" y="15.00" width="3.00" height="3.00" />
<rect x="45.00" y="15.00" width="3.00" height="3.00" />
<rect x="51.00" y="15.00" width="6.00" height="3.00" />
<rect x="60.00" y="15.00" width="3.00" height="3.00" />
<rect x="66.00" y="15.00" width="3.00" height="3.00" />
<rect x="84.00" y="15.00" width="3.00" height="3.00" />
<rect x="12.00" y="18.00" width="3.00" height="3.00" />
<rect x="18.00" y="18.00" width="9.00" height="3.00" />
<rect x="30.00" y="18.00" width="3.00" height="3.00" />
<rect x="39.00" y="18.00" width="3.00" height="3.00" />
<rect x="51.00" y="18.00" width="3.00" height="3.00" />
<rect x="57.00" y="18.00" width="3.00" height="3.00" />
<rect x="66.00" y="18.00" width="3.00" height="3.00" />
<rect x="72.00" y="18.00" width="9.00" height="3.00" />
<rect x="84.00" y="18.00" width="3.00" height="3.00" />
<rect x="12.00" y="21.00" width="3.00" height="3.00" />
<rect x="18.00" y="21.00" width="9.00" height="3.00" />
<rect x="30.00" y="21.00" width="3.00" height="3.00" />
<rect x="45.00" y="21.00" width="9.00" height="3.00" />
<rect x="57.00" y="21.00" width="3.00" height="3.00" />
<rect x="66.00" y="21.00" width="3.00" height="3.00" />
<rect x="72.00" y="21.00" width="9.00" height="3.00" />
<rect x="84.00" y="21.00" width="3.00" height="3.00" />
<rect x="12.00" y="24.00" width="3.00" height="3.00" />
<rect x="18.00" y="24.00" width="9.00" height="3.00" />
<rect x="30.00" y="24.00" width="3.00" height="3.00" />
<rect x="36.00" y="24.00" width="3.00" height="3.00" />
<rect x="45.00" y="24.00" width="9.00" height="3.00" />
<rect x="66.00" y="24.00" width="3.00" height="3.00" />
<rect x="72.00" y="24.00" width="9.00" height="3.00" />
<rect x="84.00" y="24.00" width="3.00" height="3.00" />
<rect x="12.00" y="27.00" width="3.00" height="3.00" />
<rect x="30.00" y="27.00" width="3.00" height="3.00" />
<rect x="36.00" y="27.00" width="9.00" height="3.00" />
<rect x="48.00" y="27.00" width="6.00" height="3.00" />
<rect x="60.00" y="27.00" width="3.00" height="3.00" />
<rect x="66.00" y="27.00" width="3.00" height="3.00" />
<rect x="84.00" y="27.00" width="3.00" height="3.00" />
<rect x="12.00" y="30.00" width="21.00" height="3.00" />
<rect x="36.00" y="30.00" width="3.00" height="3.00" />
<rect x="42.00" y="30.00" width="3.00" height="3.00" />
<rect x="48.00" y="30.00" width="3.00" height="3.00" />
<rect x="54.00" y="30.00" width="3.00" height="3.00" />
<rect x="60.00" y="30.00" width="3.00" height="3.00" />
<rect x="66.00" y="30.00" width="21.00" height="3.00" />
<rect x="36.00" y="33.00" width="6.00" height="3.00" />
<rect x="57.00" y="33.00" width="6.00" height="3.00" />
<rect x="12.00" y="36.00" width="9.00" height="3.00" />
<rect x="27.00" y="36.00" width="6.00" height="3.00" />
<rect x="36.00" y="36.00" width="6.00" height="3.00" />
<rect x="45.00" y="36.00" width="6.00" height="3.00" />
<rect x="60.00" y="36.00" width="15.00" height="3.00" />
<rect x="81.00" y="36.00" width="6.00" height="3.00" />
<rect x="12.00" y="39.00" width="3.00" height="3.00" />
<rect x="18.00" y="39.00" width="3.00" height="3.00" />
<rect x="24.00" y="39.00" width="3.00" height="3.00" />
<rect x="33.00" y="39.00" width="6.00" height="3.00" />
<rect x="48.00" y="39.00" width="3.00" height="3.00" />
<rect x="54.00" y="39.00" width="9.00" height="3.00" />
<rect x="66.00" y="39.00" width="6.00" height="3.00" />
<rect x="75.00" y="39.00" width="3.00" height="3.00" />
<rect x="81.00" y="39.00" width="6.00" height="3.00" />
<rect x="15.00" y="42.00" width="3.00" height="3.00" />
<rect x="21.00" y="42.00" width="3.00" height="3.00" />
<rect x="30.00" y="42.00" width="3.00" height="3.00" />
<rect x="36.00" y="42.00" width="9.00" height="3.00" />
<rect x="48.00" y="42.00" width="3.00" height="3.00" />
<rect x="57.00" y="42.00" width="3.00" height="3.00" />
<rect x="72.00" y="42.00" width="9.00" height="3.00" />
<rect x="84.00" y="42.00" width="3.00" height="3.00" />
<rect x="18.00" y="45.00" width="6.00" height="3.00" />
<rect x="33.00" y="45.00" width="6.00" height="3.00" />
<rect x="42.00" y="45.00" width="9.00" height="3.00" />
<rect x="57.00" y="45.00" width="3.00" height="3.00" />
<rect x="69.00" y="45.00" width="3.00" height="3.00" />
<rect x="75.00" y="45.00" width="3.00" height="3.00" />
<rect x="15.00" y="48.00" width="3.00" height="3.00" />
<rect x="24.00" y="48.00" width="9.00" height="3.00" />
<rect x="39.00" y="48.00" width="6.00" height="3.00" />
<rect x="48.00" y="48.00" width="3.00" height="3.00" />
<rect x="57.00" y="48.00" width="6.00" height="3.00" />
<rect x="66.00" y="48.00" width="6.00" height="3.00" />
<rect x="84.00" y="48.00" width="3.00" height="3.00" />
<rect x="21.00" y="51.00" width="9.00" height="3.00" />
<rect x="39.00" y="51.00" width="6.00" height="3.00" />
<rect x="57.00" y="51.00" width="6.00" height="3.00" />
<rect x="66.00" y="51.00" width="6.00" height="3.00" />
<rect x="81.00" y="51.00" width="6.00" height="3.00" />
<rect x="12.00" y="54.00" width="12.00" height="3.00" />
<rect x="30.00" y="54.00" width="3.00" height="3.00" />
<rect x="39.00" y="54.00" width="27.00" height="3.00" />
<rect x="69.00" y="54.00" width="12.00" height="3.00" />
<rect x="84.00" y="54.00" width="3.00" height="3.00" />
<rect x="18.00" y="57.00" width="3.00" height="3.00" />
<rect x="24.00" y="57.00" width="3.00" height="3.00" />
<rect x="33.00" y="57.00" width="3.00" height="3.00" />
<rect x="39.00" y="57.00" width="3.00" height="3.00" />
<rect x="45.00" y="57.00" width="3.00" height="3.00" />
<rect x="54.00" y="57.00" width="12.00" height="3.00" />
<rect x="69.00" y="57.00" width="3.00" height="3.00" />
<rect x="12.00" y="60.00" width="6.00" height="3.00" />
<rect x="21.00" y="60.00" width="3.00" height="3.00" />
<rect x="30.00" y="60.00" width="3.00" height="3.00" />
<rect x="39.00" y="60.00" width="9.00" height="3.00" />
<rect x="60.00" y="60.00" width="15.00" height="3.00" />
<rect x="81.00" y="60.00" width="3.00" height="3.00" />
<rect x="36.00" y="63.00" width="15.00" height="3.00" />
<rect x="60.00" y="63.00" width="3.00" height="3.00" />
<rect x="72.00" y="63.00" width="3.00" height="3.00" />
<rect x="78.00" y="63.00" width="3.00" height="3.00" />
<rect x="84.00" y="63.00" width="3.00" height="3.00" />
<rect x="12.00" y="66.00" width="21.00" height="3.00" />
<rect x="45.00" y="66.00" width="3.00" height="3.00" />
<rect x="54.00" y="66.00" width="3.00" height="3.00" />
<rect x="60.00" y="66.00" width="3.00" height="3.00" />
<rect x="66.00" y="66.00" width="3.00" height="3.00" />
<rect x="72.00" y="66.00" width="6.00" height="3.00" />
<rect x="84.00" y="66.00" width="3.00" height="3.00" />
<rect x="12.00" y="69.00" width="3.00" height="3.00" />
<rect x="30.00" y="69.00" width="3.00" height="3.00" />
<rect x="36.00" y="69.00" width="6.00" height="3.00" />
<rect x="54.00" y="69.00" width="3.00" height="3.00" />
<rect x="60.00" y="69.00" width="3.00" height="3.00" />
<rect x="72.00" y="69.00" width="3.00" height="3.00" />
<rect x="84.00" y="69.00" width="3.00" height="3.00" />
<rect x="12.00" y="72.00" width="3.00" height="3.00" />
<rect x="18.00" y="72.00" width="9.00" height="3.00" />
<rect x="30.00" y="72.00" width="3.00" height="3.00" />
<rect x="45.00" y="72.00" width="3.00" height="3.00" />
<rect x="54.00" y="72.00" width="24.00" height="3.00" />
<rect x="81.00" y="72.00" width="3.00" height="3.00" />
<rect x="12.00" y="75.00" width="3.00" height="3.00" />
<rect x="18.00" y="75.00" width="9.00" height="3.00" />
<rect x="30.00" y="75.00" width="3.00" height="3.00" />
<rect x="42.00" y="75.00" width="9.00" height="3.00" />
<rect x="54.00" y="75.00" width="3.00" height="3.00" />
<rect x="60.00" y="75.00" width="6.00" height="3.00" />
<rect x="72.00" y="75.00" width="12.00" height="3.00" />
<rect x="12.00" y="78.00" width="3.00" height="3.00" />
<rect x="18.00" y="78.00" width="9.00" height="3.00" />
<rect x="30.00" y="78.00" width="3.00" height="3.00" />
<rect x="36.00" y="78.00" width="12.00" height="3.00" />
<rect x="51.00" y="78.00" width="3.00" height="3.00" />
<rect x="57.00" y="78.00" width="6.00" height="3.00" />
<rect x="72.00" y="78.00" width="3.00" height="3.00" />
<rect x="81.00" y="78.00" width="6.00" height="3.00" />
<rect x="12.00" y="81.00" width="3.00" height="3.00" />
<rect x="30.00" y="81.00" width="3.00" height="3.00" />
<rect x="36.00" y="81.00" width="15.00" height="3.00" />
<rect x="54.00" y="81.00" width="12.00" height="3.00" />
<rect x="69.00" y="81.00" width="6.00" height="3.00" />
<rect x="12.00" y="84.00" width="21.00" height="3.00" />
<rect x="36.00" y="84.00" width="9.00" height="3.00" />
<rect x="51.00" y="84.00" width="3.00" height="3.00" />
<rect x="60.00" y="84.00" width="6.00" height="3.00" />
<rect x="75.00" y="84.00" width="3.00" height="3.00" />
<rect x="84.00" y="84.00" width="3.00" height="3.00" />
</g>
</svg>
</code></pre>
<p>You may need to change a few things so that you can target your source SVGs correctly, but this should give you a good jumping off point.</p>
<p>boarder+qr.svg</p>
<pre class="lang-xml prettyprint-override"><code><?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" id="svg8" version="1.1" height="110" width="110">
<defs id="defs2"/>
<metadata id="metadata5">
<rdf:RDF>
<cc:Work rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
<dc:title/>
</cc:Work>
</rdf:RDF>
</metadata>
<g id="layer1">
<path id="rect1379" d="m 0,0 h 110 v 110 H 0 Z 0" style=" stroke:#FFFFFF; stroke-width:0.89999998; stroke-linecap:round; stroke-linejoin:round; stroke-miterlimit:4; stroke-dasharray:none; stroke-dashoffset:0; stroke-opacity:1"/>
</g>
<svg:g id="barcode" fill="#000000" transform="translate(5.0,5.0)">
<svg:rect x="0" y="0" width="100" height="100" fill="#FFFFFF"/>
<svg:rect x="12.00" y="12.00" width="21.00" height="3.00"/>
<svg:rect x="36.00" y="12.00" width="12.00" height="3.00"/>
<svg:rect x="54.00" y="12.00" width="3.00" height="3.00"/>
<svg:rect x="60.00" y="12.00" width="3.00" height="3.00"/>
<svg:rect x="66.00" y="12.00" width="21.00" height="3.00"/>
<svg:rect x="12.00" y="15.00" width="3.00" height="3.00"/>
<svg:rect x="30.00" y="15.00" width="3.00" height="3.00"/>
<svg:rect x="36.00" y="15.00" width="3.00" height="3.00"/>
<svg:rect x="45.00" y="15.00" width="3.00" height="3.00"/>
<svg:rect x="51.00" y="15.00" width="6.00" height="3.00"/>
<svg:rect x="60.00" y="15.00" width="3.00" height="3.00"/>
<svg:rect x="66.00" y="15.00" width="3.00" height="3.00"/>
<svg:rect x="84.00" y="15.00" width="3.00" height="3.00"/>
<svg:rect x="12.00" y="18.00" width="3.00" height="3.00"/>
<svg:rect x="18.00" y="18.00" width="9.00" height="3.00"/>
<svg:rect x="30.00" y="18.00" width="3.00" height="3.00"/>
<svg:rect x="39.00" y="18.00" width="3.00" height="3.00"/>
<svg:rect x="51.00" y="18.00" width="3.00" height="3.00"/>
<svg:rect x="57.00" y="18.00" width="3.00" height="3.00"/>
<svg:rect x="66.00" y="18.00" width="3.00" height="3.00"/>
<svg:rect x="72.00" y="18.00" width="9.00" height="3.00"/>
<svg:rect x="84.00" y="18.00" width="3.00" height="3.00"/>
<svg:rect x="12.00" y="21.00" width="3.00" height="3.00"/>
<svg:rect x="18.00" y="21.00" width="9.00" height="3.00"/>
<svg:rect x="30.00" y="21.00" width="3.00" height="3.00"/>
<svg:rect x="45.00" y="21.00" width="9.00" height="3.00"/>
<svg:rect x="57.00" y="21.00" width="3.00" height="3.00"/>
<svg:rect x="66.00" y="21.00" width="3.00" height="3.00"/>
<svg:rect x="72.00" y="21.00" width="9.00" height="3.00"/>
<svg:rect x="84.00" y="21.00" width="3.00" height="3.00"/>
<svg:rect x="12.00" y="24.00" width="3.00" height="3.00"/>
<svg:rect x="18.00" y="24.00" width="9.00" height="3.00"/>
<svg:rect x="30.00" y="24.00" width="3.00" height="3.00"/>
<svg:rect x="36.00" y="24.00" width="3.00" height="3.00"/>
<svg:rect x="45.00" y="24.00" width="9.00" height="3.00"/>
<svg:rect x="66.00" y="24.00" width="3.00" height="3.00"/>
<svg:rect x="72.00" y="24.00" width="9.00" height="3.00"/>
<svg:rect x="84.00" y="24.00" width="3.00" height="3.00"/>
<svg:rect x="12.00" y="27.00" width="3.00" height="3.00"/>
<svg:rect x="30.00" y="27.00" width="3.00" height="3.00"/>
<svg:rect x="36.00" y="27.00" width="9.00" height="3.00"/>
<svg:rect x="48.00" y="27.00" width="6.00" height="3.00"/>
<svg:rect x="60.00" y="27.00" width="3.00" height="3.00"/>
<svg:rect x="66.00" y="27.00" width="3.00" height="3.00"/>
<svg:rect x="84.00" y="27.00" width="3.00" height="3.00"/>
<svg:rect x="12.00" y="30.00" width="21.00" height="3.00"/>
<svg:rect x="36.00" y="30.00" width="3.00" height="3.00"/>
<svg:rect x="42.00" y="30.00" width="3.00" height="3.00"/>
<svg:rect x="48.00" y="30.00" width="3.00" height="3.00"/>
<svg:rect x="54.00" y="30.00" width="3.00" height="3.00"/>
<svg:rect x="60.00" y="30.00" width="3.00" height="3.00"/>
<svg:rect x="66.00" y="30.00" width="21.00" height="3.00"/>
<svg:rect x="36.00" y="33.00" width="6.00" height="3.00"/>
<svg:rect x="57.00" y="33.00" width="6.00" height="3.00"/>
<svg:rect x="12.00" y="36.00" width="9.00" height="3.00"/>
<svg:rect x="27.00" y="36.00" width="6.00" height="3.00"/>
<svg:rect x="36.00" y="36.00" width="6.00" height="3.00"/>
<svg:rect x="45.00" y="36.00" width="6.00" height="3.00"/>
<svg:rect x="60.00" y="36.00" width="15.00" height="3.00"/>
<svg:rect x="81.00" y="36.00" width="6.00" height="3.00"/>
<svg:rect x="12.00" y="39.00" width="3.00" height="3.00"/>
<svg:rect x="18.00" y="39.00" width="3.00" height="3.00"/>
<svg:rect x="24.00" y="39.00" width="3.00" height="3.00"/>
<svg:rect x="33.00" y="39.00" width="6.00" height="3.00"/>
<svg:rect x="48.00" y="39.00" width="3.00" height="3.00"/>
<svg:rect x="54.00" y="39.00" width="9.00" height="3.00"/>
<svg:rect x="66.00" y="39.00" width="6.00" height="3.00"/>
<svg:rect x="75.00" y="39.00" width="3.00" height="3.00"/>
<svg:rect x="81.00" y="39.00" width="6.00" height="3.00"/>
<svg:rect x="15.00" y="42.00" width="3.00" height="3.00"/>
<svg:rect x="21.00" y="42.00" width="3.00" height="3.00"/>
<svg:rect x="30.00" y="42.00" width="3.00" height="3.00"/>
<svg:rect x="36.00" y="42.00" width="9.00" height="3.00"/>
<svg:rect x="48.00" y="42.00" width="3.00" height="3.00"/>
<svg:rect x="57.00" y="42.00" width="3.00" height="3.00"/>
<svg:rect x="72.00" y="42.00" width="9.00" height="3.00"/>
<svg:rect x="84.00" y="42.00" width="3.00" height="3.00"/>
<svg:rect x="18.00" y="45.00" width="6.00" height="3.00"/>
<svg:rect x="33.00" y="45.00" width="6.00" height="3.00"/>
<svg:rect x="42.00" y="45.00" width="9.00" height="3.00"/>
<svg:rect x="57.00" y="45.00" width="3.00" height="3.00"/>
<svg:rect x="69.00" y="45.00" width="3.00" height="3.00"/>
<svg:rect x="75.00" y="45.00" width="3.00" height="3.00"/>
<svg:rect x="15.00" y="48.00" width="3.00" height="3.00"/>
<svg:rect x="24.00" y="48.00" width="9.00" height="3.00"/>
<svg:rect x="39.00" y="48.00" width="6.00" height="3.00"/>
<svg:rect x="48.00" y="48.00" width="3.00" height="3.00"/>
<svg:rect x="57.00" y="48.00" width="6.00" height="3.00"/>
<svg:rect x="66.00" y="48.00" width="6.00" height="3.00"/>
<svg:rect x="84.00" y="48.00" width="3.00" height="3.00"/>
<svg:rect x="21.00" y="51.00" width="9.00" height="3.00"/>
<svg:rect x="39.00" y="51.00" width="6.00" height="3.00"/>
<svg:rect x="57.00" y="51.00" width="6.00" height="3.00"/>
<svg:rect x="66.00" y="51.00" width="6.00" height="3.00"/>
<svg:rect x="81.00" y="51.00" width="6.00" height="3.00"/>
<svg:rect x="12.00" y="54.00" width="12.00" height="3.00"/>
<svg:rect x="30.00" y="54.00" width="3.00" height="3.00"/>
<svg:rect x="39.00" y="54.00" width="27.00" height="3.00"/>
<svg:rect x="69.00" y="54.00" width="12.00" height="3.00"/>
<svg:rect x="84.00" y="54.00" width="3.00" height="3.00"/>
<svg:rect x="18.00" y="57.00" width="3.00" height="3.00"/>
<svg:rect x="24.00" y="57.00" width="3.00" height="3.00"/>
<svg:rect x="33.00" y="57.00" width="3.00" height="3.00"/>
<svg:rect x="39.00" y="57.00" width="3.00" height="3.00"/>
<svg:rect x="45.00" y="57.00" width="3.00" height="3.00"/>
<svg:rect x="54.00" y="57.00" width="12.00" height="3.00"/>
<svg:rect x="69.00" y="57.00" width="3.00" height="3.00"/>
<svg:rect x="12.00" y="60.00" width="6.00" height="3.00"/>
<svg:rect x="21.00" y="60.00" width="3.00" height="3.00"/>
<svg:rect x="30.00" y="60.00" width="3.00" height="3.00"/>
<svg:rect x="39.00" y="60.00" width="9.00" height="3.00"/>
<svg:rect x="60.00" y="60.00" width="15.00" height="3.00"/>
<svg:rect x="81.00" y="60.00" width="3.00" height="3.00"/>
<svg:rect x="36.00" y="63.00" width="15.00" height="3.00"/>
<svg:rect x="60.00" y="63.00" width="3.00" height="3.00"/>
<svg:rect x="72.00" y="63.00" width="3.00" height="3.00"/>
<svg:rect x="78.00" y="63.00" width="3.00" height="3.00"/>
<svg:rect x="84.00" y="63.00" width="3.00" height="3.00"/>
<svg:rect x="12.00" y="66.00" width="21.00" height="3.00"/>
<svg:rect x="45.00" y="66.00" width="3.00" height="3.00"/>
<svg:rect x="54.00" y="66.00" width="3.00" height="3.00"/>
<svg:rect x="60.00" y="66.00" width="3.00" height="3.00"/>
<svg:rect x="66.00" y="66.00" width="3.00" height="3.00"/>
<svg:rect x="72.00" y="66.00" width="6.00" height="3.00"/>
<svg:rect x="84.00" y="66.00" width="3.00" height="3.00"/>
<svg:rect x="12.00" y="69.00" width="3.00" height="3.00"/>
<svg:rect x="30.00" y="69.00" width="3.00" height="3.00"/>
<svg:rect x="36.00" y="69.00" width="6.00" height="3.00"/>
<svg:rect x="54.00" y="69.00" width="3.00" height="3.00"/>
<svg:rect x="60.00" y="69.00" width="3.00" height="3.00"/>
<svg:rect x="72.00" y="69.00" width="3.00" height="3.00"/>
<svg:rect x="84.00" y="69.00" width="3.00" height="3.00"/>
<svg:rect x="12.00" y="72.00" width="3.00" height="3.00"/>
<svg:rect x="18.00" y="72.00" width="9.00" height="3.00"/>
<svg:rect x="30.00" y="72.00" width="3.00" height="3.00"/>
<svg:rect x="45.00" y="72.00" width="3.00" height="3.00"/>
<svg:rect x="54.00" y="72.00" width="24.00" height="3.00"/>
<svg:rect x="81.00" y="72.00" width="3.00" height="3.00"/>
<svg:rect x="12.00" y="75.00" width="3.00" height="3.00"/>
<svg:rect x="18.00" y="75.00" width="9.00" height="3.00"/>
<svg:rect x="30.00" y="75.00" width="3.00" height="3.00"/>
<svg:rect x="42.00" y="75.00" width="9.00" height="3.00"/>
<svg:rect x="54.00" y="75.00" width="3.00" height="3.00"/>
<svg:rect x="60.00" y="75.00" width="6.00" height="3.00"/>
<svg:rect x="72.00" y="75.00" width="12.00" height="3.00"/>
<svg:rect x="12.00" y="78.00" width="3.00" height="3.00"/>
<svg:rect x="18.00" y="78.00" width="9.00" height="3.00"/>
<svg:rect x="30.00" y="78.00" width="3.00" height="3.00"/>
<svg:rect x="36.00" y="78.00" width="12.00" height="3.00"/>
<svg:rect x="51.00" y="78.00" width="3.00" height="3.00"/>
<svg:rect x="57.00" y="78.00" width="6.00" height="3.00"/>
<svg:rect x="72.00" y="78.00" width="3.00" height="3.00"/>
<svg:rect x="81.00" y="78.00" width="6.00" height="3.00"/>
<svg:rect x="12.00" y="81.00" width="3.00" height="3.00"/>
<svg:rect x="30.00" y="81.00" width="3.00" height="3.00"/>
<svg:rect x="36.00" y="81.00" width="15.00" height="3.00"/>
<svg:rect x="54.00" y="81.00" width="12.00" height="3.00"/>
<svg:rect x="69.00" y="81.00" width="6.00" height="3.00"/>
<svg:rect x="12.00" y="84.00" width="21.00" height="3.00"/>
<svg:rect x="36.00" y="84.00" width="9.00" height="3.00"/>
<svg:rect x="51.00" y="84.00" width="3.00" height="3.00"/>
<svg:rect x="60.00" y="84.00" width="6.00" height="3.00"/>
<svg:rect x="75.00" y="84.00" width="3.00" height="3.00"/>
<svg:rect x="84.00" y="84.00" width="3.00" height="3.00"/>
</svg:g>
</svg>
</code></pre>
|
python|python-3.x|svg|image-processing|qr-code
| 0 |
1,902,854 | 25,748,857 |
Scrape all Text on a Webpage that is buried within Tags in Python 3
|
<p>I need to scrape a webpage (<a href="https://www304.americanexpress.com/credit-card/compare" rel="nofollow">https://www304.americanexpress.com/credit-card/compare</a>) but I am running into an issue -- the text that I need on the front page is absolutely buried within many different formatting tags.</p>
<p>I know how to scrape a regular page using Beautiful Soup but this is not giving me what I want (i.e. text is missing, some tags make it through...)</p>
<pre><code>import requests
from bs4 import BeautifulSoup
from collections import Counter
urls = ['https://www304.americanexpress.com/credit-card/compare']
with open('thisisanew.txt', 'w', encoding='utf-8') as outfile:
for url in urls:
website = requests.get(url)
soup = BeautifulSoup(website.content)
text = [''.join(s.findAll(text=True))for s in soup.findAll('p')]
for item in text:
print (''.join([element.text for element in soup.body.find_all(lambda tag: tag != 'script', recursive=False)]))
</code></pre>
<p>Is there a special way to scrape this particular webpage?</p>
|
<p>This is just a regular webpage. For instance <code><span class="card-offer-des"></code> contains the text <code>after you use your new Card to make $1,000 in purchases within the first 3 months.</code>. I also tried turning off Javascript in the browser. The text is still there as it should be. </p>
<p>So I don't really see what the problem is. Also, I would suggest that try to learn lxml and xpath. Once you know how that works, it's actually easier to get the text you want. </p>
|
python-3.x|beautifulsoup|scrapy
| 1 |
1,902,855 | 44,603,490 |
python write unicode to file and retrieve it as a symbol
|
<p>I am working on a Python program which contains an Arabic-English database and allows to update this database and also to study the vocabluary. I am almost done with implementing all the functions I need but the most important part is missing: The encoding of the Arabic strings. To append new vocabulary to the data base txt file, a dictionary is created and then its content is appended to the file. To study vocabulary, the content of the txt file is converted into a dictionary again, a random word is printed to the console and the user is asked for its translation. Now the idea is that the user has the possibility to write the Englisch word as well as the Arabic word in latin letters and the program will internally convert the pseudo-arabic string to Arabic letters. For example, if the user writes 'b' when asked for the Arabic word, I want to append 'ب'.
1. There are about 80 signs I have to consider in the implementation. Is there a way of creating some mapping between the latin-letter input string and the respective Arabic signs? For me, the most intuitive idea would be to write one if statement after the other but that's probably super slow.
2. I have trouble printing the Arabic string to the console. This input </p>
<pre><code>print('bla{}!'.format(chr(0xfe9e)))
print('bla{}!'.format(chr(int('0x'+'0627',16))))
</code></pre>
<p>will result in printing the Arabic sign whereas this won't:</p>
<pre><code>print('{}'.format(chr(0xfe9e)))
</code></pre>
<p>What can I do in order to avoid this problem, since I want a sequence which consists of unicode symbols only?</p>
|
<p>This is not the final answer but can give you a start.</p>
<p>First of all check your encoding:</p>
<pre><code>import sys
sys.getdefaultencoding()
</code></pre>
<p><strong>Edit:</strong> </p>
<p><code>sys.setdefaultencoding('UTF8')</code> was removed from <code>sys</code> module. But still, you can comment what <code>sys.getdefaultencoding()</code> returns in your box.</p>
<p>However, for Arabic characters, you can range them all at once:</p>
<p>According to this <a href="http://jrgraphix.net/r/Unicode/0600-06FF" rel="nofollow noreferrer">website</a>, Arabic characters are from <code>0x620 to 0x64B</code> and Basic Latin characters are from <code>0x0061 to 0x007B</code> (for lower cases).</p>
<p>So: </p>
<pre><code>arabic_chr = [chr(k) for k in range(0x620, 0x064B, 1)]
latin_chr = [chr(k) for k in range(0x0061, 0x007B, 1)]
</code></pre>
<p>Now, all what you have to do, is finding a relation between the two lists, orr maybe extend more the ranges (I speak arabic and i know that there is many forms of one char and a character can change from a word to another).</p>
|
python|string|unicode
| 0 |
1,902,856 | 61,979,661 |
Extract PDF OLE Object in MS Word using win32com python
|
<p>This is my very first question here....</p>
<p>I have a lot of MSWord files with 1 or more PDF inserted as objects, i need to process all de word files and extract the pdfs to save them as pdf files, leaving de MS word file just like i found it.
Until now i have this code to test it in one file:</p>
<pre><code>import win32com.client as win32
word = win32.Dispatch('Word.Application')
word.Application.Visible = False
doc1 = word.Documents.Open('C:\\word_merge\\docx_con_pdfs.docx')
for s in doc1.InlineShapes:
if s.OLEFormat.ClassType == 'AcroExch.Document.DC':
s.OLEFormat.DoVerb()
_ = input("Hit Enter to Quit")
doc1.Close()
word.Application.Quit()
</code></pre>
<p>I know this work because the <strong>s.OLEFormat.DoVerb()</strong> effectivly opens the files in <em>Adobe Reader</em> and kept them open until "Hit Enter" moment, when are closed with the word file.</p>
<p>Is in this point when i need to replace <strong>DoVerb()</strong> with some code that save the OLE Object into a PDF file.</p>
<p>In this point <strong>s</strong> contains the file i need, but i cant find the way to save it as file instead of only open it.</p>
<p>please help me, i have read articles many hours by now and didn't find the answer.</p>
|
<p>i found a workaround in the python-win32 mailing list...... thanks to Chris Else, is like some says in one comment, the .bin file cant be Transformed into a pdf, the code that Chris send me was:</p>
<pre><code>import olefile
from zipfile import ZipFile
from glob import glob
# How many PDF documents have we saved
pdf_count = 0
# Loop through all the .docx files in the current folder
for filename in glob("*.docx"):
try:
# Try to open the document as ZIP file
with ZipFile(filename, "r") as zip:
# Find files in the word/embeddings folder of the ZIP file
for entry in zip.infolist():
if not entry.filename.startswith("word/embeddings/"):
continue
# Try to open the embedded OLE file
with zip.open(entry.filename) as f:
if not olefile.isOleFile(f):
continue
ole = olefile.OleFileIO(f)
# CLSID for Adobe Acrobat Document
if ole.root.clsid != "B801CA65-A1FC-11D0-85AD-444553540000":
continue
if not ole.exists("CONTENTS"):
continue
# Extract the PDF from the OLE file
pdf_data = ole.openstream('CONTENTS').read()
# Does the embedded file have a %PDF- header?
if pdf_data[0:5] == b'%PDF-':
pdf_count += 1
pdf_filename = "Document %d.pdf" % pdf_count
# Save the PDF
with open(pdf_filename, "wb") as output_file:
output_file.write(pdf_data)
except:
print("Unable to open '%s'" % filename)
print("Extracted %d PDF documents" % pdf_count)
</code></pre>
|
python|pdf|ms-word|win32com|ole
| 1 |
1,902,857 | 24,074,684 |
How to play a sound onto a input stream
|
<p>I was wondering if it was possible to play a sound directly into a input from python. I am using linux, and with that I am using OSS, ALSA, and Pulseaudio </p>
|
<p>You can definitely play (and generate) sound with python</p>
<p>Here is a example code that generates sinewave, opens default Alsa playback device and plays sinewave through that</p>
<pre><code>#!/usr/bin/env python3
import math
import struct
import alsaaudio
from itertools import *
def sine_wave(frequency=440.0, framerate=44100, amplitude=0.5):
"""Stolen from here: http://zacharydenton.com/generate-audio-with-python/"""
period = int(framerate / frequency)
if amplitude > 1.0: amplitude = 1.0
if amplitude < 0.0: amplitude = 0.0
lookup_table = [float(amplitude) * math.sin(2.0*math.pi*float(frequency)*(float(i%period)/float(framerate))) for i in range(period)]
return (lookup_table[i%period] for i in count(0))
sound_out = alsaaudio.PCM() # open default sound output
sound_out.setchannels(1) # use only one channel of audio (aka mono)
sound_out.setrate(44100) # how many samples per second
sound_out.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE) # sample format
for sample in sine_wave():
# alsa only eats binnary data
b = struct.pack("<f", sample) # convert python float to binary float
sound_out.write(b)
</code></pre>
<p>or you can loopback microphone to your speakers</p>
<pre><code>#!/usr/bin/env python3
import struct
import alsaaudio
sound_out = alsaaudio.PCM() # open default sound output
sound_out.setchannels(1) # use only one channel of audio (aka mono)
sound_out.setperiodsize(5) # buffer size, default is 32
sound_in = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE) # default recording device
sound_in.setchannels(1) # use only one channel of audio (aka mono)
sound_in.setperiodsize(5) # buffer size, default is 32
while True:
sample_lenght, sample = sound_in.read()
sound_out.write(sample)
</code></pre>
<p>much more examples can be found in python alsaaudio library <a href="http://pyalsaaudio.sourceforge.net/libalsaaudio.html" rel="nofollow">http://pyalsaaudio.sourceforge.net/libalsaaudio.html</a></p>
|
python|linux|audio|alsa|pulseaudio
| 3 |
1,902,858 | 20,553,228 |
Error reducing astronomy picture flatfield PIL
|
<p>I am trying to reduce my cannon astro images by taking off the flatframe, which works. But it leaves all the values very low (so almost black picture), which is why I also want to multiply it with the average. However this gives me an error. (while without multiplication it works.)</p>
<p>Does anybody know why?</p>
<blockquote>
<p>Traceback (most recent call last): File
"D:\astro\10-12\moon\fits\red.py", line 16, in
img = Image.fromarray(imarray) File "C:\Python27\lib\site-packages\PIL\Image.py", line 1886, in fromarray
raise TypeError("Cannot handle this data type") TypeError: Cannot handle this data type</p>
</blockquote>
<p>Here is my code</p>
<pre><code>import Image
import numpy as np
im = Image.open('8bit/DPP_0001.TIF')
flat = Image.open('8bit/flat2.TIF')
#im.show()
imarray = np.array(im)
flatarray = np.array(flat)
avg = np.average(imarray)
imarray = (imarray/flatarray)*avg
img = Image.fromarray(imarray)
img.save("done/aap.png","png")
</code></pre>
|
<p>PIL's <code>Image.fromarray()</code> supports a limited range of input type/channel combinations (see <code>PIL/Image.py</code>, member <code>_fromarray_typemap</code>). </p>
<p>The original <code>imarray</code> loaded from the TIF file had 3 channels of 8-bit integer values (bytes).</p>
<p>In your case, the average value of the image yielded a float value, and when that was multiplied with the image data, it produced float values for all of the pixels. </p>
<p>For <code>fromarray</code> to work, you need to coerce the pixel values back to byte values with <code>np.uint8( ... )</code>. </p>
|
python|python-imaging-library
| 1 |
1,902,859 | 72,120,846 |
How to not add duplicate list values but instead add a counter to count each item?
|
<pre><code>elif int(groceriesInput) in range(len(groceries)+1):
optionSelect = input("\nAdd " + (groceries[int(groceriesInput)- 1][0]) + " to the cart? (y or n): ")
if optionSelect == "y" or optionSelect == "Y":
if groceries[int(groceriesInput)-1] in cart:
os.system('cls')
else:
os.system('cls')
cart.append(groceries[int(groceriesInput)- 1])
</code></pre>
<p>How would I add a counter before each item without adding a duplicate item to the list?</p>
<p>My function builds the list from reading a file.</p>
<p>For example this is the output I want:</p>
<pre><code>2 milk
</code></pre>
<p>instead of:</p>
<pre><code>milk milk
</code></pre>
<p>[['eggs', 1.99], ['milk', 3.59], ['salmon', 9.99], ['bread', 3.25], ['bean dip', 2.99], ['Fat Tire Ale', 8.99], ['Greek yogurt', 4.99], ['brocoli', 2.29], ['tomatos', 3.19], ['apples', 5.99], ['chicken', 10.99], ['chips', 3.69], ['muesli', 4.99], ['Nine Lives catfood', 6.39], ['goat cheese', 5.19], ['parmesan cheese', 5.99], ['Pinot Noir', 18.5]] this is the list</p>
|
<p>So, for each entry in your list, you split it into two words: name and price. Since, we are only concerned with the item name, we store the value inside <code>entry[0]</code> into <code>item</code>, which is basically the name of some item. Now, we assume that this is the first time we are encountering this item, so we set <code>isFirst</code> equal to <code>True</code>.</p>
<p>Now, we go through each item stored in your output list: <code>out</code>. Since, each item inside <code>out</code> looks like: <code>COUNT NAME</code>, we split it, and check if current item's name is found inside this splitted string. If it does, we retrieve the value of its count and add one to it.</p>
<p>We now get the index of this item, set the incremented value of count to it, set the <code>isFirst</code> flag to <code>False</code>, since we are not encountering this item for the first time, and break out of the loop.</p>
<p>If <code>isFirst</code> was set to <code>True</code>, i.e., it was out first time encountering such item, we simply append <code>1 ITEM_NAME</code> to the output list.</p>
<pre><code>out = []
for entry in originalList:
item = entry[0]
isFirst = True
for s in out:
if item in s.split():
count = int(s.split()[0]) + 1
index = out.index(s)
out[index] = f"{count} {item}"
isFirst = False
break
if isFirst:
out.append(f"1 {item}")
</code></pre>
<p><strong>Some other improvements to your code</strong>:</p>
<p>Try to use <a href="https://realpython.com/python-f-strings/" rel="nofollow noreferrer">f-strings</a> to represent formatted strings (those where you need a variable's value inside). So, the line where you are asking for user's input, you can replace it with:</p>
<pre><code>optionSelect = input(f"\nAdd {groceries[int(groceriesInput)- 1][0]} to the cart? (y or n):")
</code></pre>
|
python
| 0 |
1,902,860 | 46,515,698 |
Rounding to nearest min in a pandas dataframe
|
<p>I want to round the hh:mm:ss values in my TimeStamp col of the dataframe so that the seconds are always 00</p>
<p>Dataset:</p>
<pre><code> TimeStamp A B C
10:27:30 1.953036 2.110234 1.981548
10:28:30 1.973408 2.046361 1.806923
10:29:30 0.000000 0.000000 0.014881
10:30:30 2.567976 3.169928 3.479591
</code></pre>
<p>I tried:</p>
<pre><code> df_sr4500.TimeStamp = np.asarray(np.round(df_sr4500.TimeStamp.values / np.timedelta64(1, 'm')), dtype='timedelta64[m]')
</code></pre>
<p>I get:</p>
<pre><code> TimeStamp A B C
10:28:00 1.953036 2.110234 1.981548
10:28:00 1.973408 2.046361 1.806923
10:30:00 0.000000 0.000000 0.014881
10:30:00 2.567976 3.169928 3.479591
</code></pre>
<p>I would have it rather rounding one way for the middle value.
The next step for me is to resample every two min with mean</p>
<p>Please suggest if you have any better/easier way to do this. I am very new to pandas/numpy. </p>
|
<p>Add one nanosecond to each time and then round.</p>
<pre><code>df['TimeStamp'] = (df['TimeStamp'] + pd.Timedelta(1)).dt.round('min')
0 10:28:00
1 10:29:00
2 10:30:00
3 10:31:00
Name: TimeStamp, dtype: timedelta64[ns]
</code></pre>
|
python|pandas|numpy
| 1 |
1,902,861 | 62,506,088 |
How can I change color of button when it pushed with tkinter?
|
<p>I made 100 buttons and I want to change color of button which pushed.
How can I do that?
Here is my code.</p>
<pre><code>import tkinter as tk
def settingships():
column = -1
row = 0
root = tk.Tk()
root.title('set ships')
root.geometry('470x310')
for i in range(101):
if i > 0:
if i%10 == 1:
row += 1
column = -1
column += 1
text=f'{i}'
btn = tk.Button(root,text=text,command=collback(i)).grid(column=column,row=row)
root.mainloop()
def collback(i):
def nothing():
btn.config(bg='#008000')
return nothing
</code></pre>
|
<p>First, <code>i</code> is not used in <code>collback()</code>. Second <code>btn</code> is undefined in <code>nothing()</code>. You should pass <code>btn</code> to <code>collback()</code> instead.</p>
<p>In order to do that you need to replace the following line:</p>
<pre><code>btn = tk.Button(root,text=text,command=collback(i)).grid(column=column,row=row)
</code></pre>
<p>to:</p>
<pre><code>btn = tk.Button(root, text=text)
btn.grid(column=column, row=row)
btn.config(command=collback(btn))
</code></pre>
<p>And modify <code>collback()</code> as below:</p>
<pre><code>def collback(btn):
def nothing():
btn.config(bg='#008000')
return nothing
</code></pre>
<p>Or simply use lambda to replace <code>collback()</code>:</p>
<pre><code>btn.config(command=lambda b=btn: b.config(bg='#008000'))
</code></pre>
|
python|python-3.x|user-interface|tkinter
| 2 |
1,902,862 | 70,127,250 |
Table formatting with pandas Dataframe.to_latex()
|
<p>Is there any way to instruct pandas <code>Dataframe.to_latex()</code> to append <code>\footnotesize</code> (or other global options) for the output table in LateX? (Of course, other than manually append it, which is not efficient, as I'm generating lots of tables.)</p>
<p>So, right now my code produces the following LaTeX table:</p>
<pre><code>\begin{table}[H]
\centering
\caption{Caption of the table.}
\label{tab:06_01.example}
\begin{tabular}{lrrr}
\toprule
& & F-1 & F-2 \\
Dataset & Model & & \\
\midrule
\multirow{2}{*}{\textit{H}} & Baseline & 0.904 & 0.887 \\
& Version2 & 0.939 & 0.927 \\
\cline{1-4}
\multirow{2}{*}{\textit{S}} & Baseline & 0.548 & 0.506 \\
& Version2 & 0.582 & 0.541 \\
\cline{1-4}
\midrule
\multirow{2}{*}{\textit{G}} & Baseline & 0.879 & 0.855 \\
& Version2 & 0.910 & 0.895 \\
\cline{1-4}
\multirow{2}{*}{\textit{T}} & Baseline & 0.911 & 0.877 \\
& Version2 & 0.940 & 0.913 \\
\bottomrule
\end{tabular}
\end{table}
</code></pre>
<p>from the following pandas dataframe:</p>
<pre><code> F-1 F-2
dataset Model
H Baseline 0.904 0.887
Version2 0.939 0.927
S Baseline 0.548 0.506
Version2 0.582 0.541
G Baseline 0.879 0.855
Version2 0.910 0.895
T Baseline 0.911 0.877
Version2 0.940 0.913
</code></pre>
<p>and the corresponding dict for reproducibility purposes:</p>
<pre><code>{'F-1': {('H', 'Baseline'): 0.9044961552465764, ('H', 'Fine-Tuned'): 0.9387767951280728, ('S', 'Baseline'): 0.547968262581014, ('S', 'Fine-Tuned'): 0.5815634664656218, ('G', 'Baseline'): 0.8793941208568047, ('G', 'Fine-Tuned'): 0.9102870296052078, ('T', 'Baseline'): 0.9110316123313993, ('T', 'Fine-Tuned'): 0.9404444309041384}, 'F-2': {('H', 'Baseline'): 0.8865304318012182, ('H', 'Fine-Tuned'): 0.9273671656403047, ('S', 'Baseline'): 0.5063582247873787, ('S', 'Fine-Tuned'): 0.5408162758046822, ('G', 'Baseline'): 0.8551648617281388, ('G', 'Fine-Tuned'): 0.8947135188980437, ('T', 'Baseline'): 0.8774834363467384, ('T', 'Fine-Tuned'): 0.9134634736945935}}
</code></pre>
<p>through an almost direct <code>dataframe.to_latex()</code>.
What I would like is to change some global table options, e.g. add \footnotesize, change \centering, like this:</p>
<pre><code>\begin{table}[H]
\footnotesize %include or not
\centering %include or not
\caption{Caption of the table.}
\label{tab:06_01.example}
\begin{tabular}{lrrr}
\toprule
& & F-1 & F-2 \\
Dataset & Model & & \\
\midrule
\multirow{2}{*}{\textit{H}} & Baseline & 0.904 & 0.887 \\
& Version2 & 0.939 & 0.927 \\
\cline{1-4}
\multirow{2}{*}{\textit{S}} & Baseline & 0.548 & 0.506 \\
& Version2 & 0.582 & 0.541 \\
\cline{1-4}
\multirow{2}{*}{\textit{G}} & Baseline & 0.879 & 0.855 \\
& Version2 & 0.910 & 0.895 \\
\cline{1-4}
\multirow{2}{*}{\textit{T}} & Baseline & 0.911 & 0.877 \\
& Version2 & 0.940 & 0.913 \\
\bottomrule
\end{tabular}
\end{table}
</code></pre>
<p>At 1st sight, it seems that there isn't such an option within <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_latex.html" rel="nofollow noreferrer">Dataframe.to_latex()</a>, but I'm not sure about what <em>formatters</em> field can do. Furthermore, I don't know if Styler.to_latex() could help here.</p>
<p><strong>PS</strong>: An additional nice-to-have would be to define after which datasets (e.g. S) to include a \midrule (as I would like to separate different types of datasets).</p>
<pre><code>\begin{table}[H]
\footnotesize %include or not
\centering %include or not
\caption{Caption of the table.}
\label{tab:06_01.example}
\begin{tabular}{lrrr}
\toprule
& & F-1 & F-2 \\
Dataset & Model & & \\
\midrule
\multirow{2}{*}{\textit{H}} & Baseline & 0.904 & 0.887 \\
& Version2 & 0.939 & 0.927 \\
\cline{1-4}
\multirow{2}{*}{\textit{S}} & Baseline & 0.548 & 0.506 \\
& Version2 & 0.582 & 0.541 \\
\cline{1-4}
\midrule
\multirow{2}{*}{\textit{G}} & Baseline & 0.879 & 0.855 \\
& Version2 & 0.910 & 0.895 \\
\cline{1-4}
\multirow{2}{*}{\textit{T}} & Baseline & 0.911 & 0.877 \\
& Version2 & 0.940 & 0.913 \\
\bottomrule
\end{tabular}
\end{table}
</code></pre>
|
<p>You can tell latex to make these changes for all your tables:</p>
<pre><code>\documentclass{article}
\usepackage{float}
\usepackage{booktabs}
\usepackage{multirow}
% change fontsize
\AtBeginEnvironment{tabular}{\footnotesize}
% switch off centering in tables
\AtBeginEnvironment{table}{\let\centering\relax}
\begin{document}
\begin{table}[H]
\centering
\caption{Caption of the table.}
\label{tab:06_01.example}
\begin{tabular}{lrrr}
\toprule
& & F-1 & F-2 \\
Dataset & Model & & \\
\midrule
\multirow{2}{*}{\textit{H}} & Baseline & 0.904 & 0.887 \\
& Version2 & 0.939 & 0.927 \\
\cline{1-4}
\multirow{2}{*}{\textit{S}} & Baseline & 0.548 & 0.506 \\
& Version2 & 0.582 & 0.541 \\
\cline{1-4}
\midrule
\multirow{2}{*}{\textit{G}} & Baseline & 0.879 & 0.855 \\
& Version2 & 0.910 & 0.895 \\
\cline{1-4}
\multirow{2}{*}{\textit{T}} & Baseline & 0.911 & 0.877 \\
& Version2 & 0.940 & 0.913 \\
\bottomrule
\end{tabular}
\end{table}
test
\centering
test
\end{document}
</code></pre>
|
python|pandas|latex
| 1 |
1,902,863 | 55,062,375 |
tensorflow api 2.0 tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn
|
<p>I am trying to use tensorflow estimator using tensorflow api 2.</p>
<pre><code>import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'A': np.array([100, 105.4, 108.3, 111.1, 113, 114.7]),
'B': np.array([11, 11.8, 12.3, 12.8, 13.1,13.6]),
'C': np.array([55, 56.3, 57, 58, 59.5, 60.4]),
'Target': np.array([4000, 4200.34, 4700, 5300, 5800, 6400])})
featcols = [
tf.feature_column.numeric_column("A"),
tf.feature_column.numeric_column("B"),
tf.feature_column.numeric_column("C")
]
model = tf.estimator.LinearRegressor(featcols)
features = tf.convert_to_tensor(["A", "B", "C"])
def train_input_fn():
training_dataset = (
tf.data.Dataset.from_tensor_slices(
(
tf.cast(df[[features]].values, tf.float32),
tf.cast(df['Target'].values, tf.float32)
)
)
)
return training_dataset
model.train(train_input_fn)
</code></pre>
<p>The last line throwes me:</p>
<p><code>TypeError: Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn</code></p>
<p>Also, it gives me a warning:</p>
<pre><code>Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.
</code></pre>
|
<p>This completes without error. But I haven't tested. Just installed tensorflow 2.0 alpha.</p>
<p>Please check the <a href="https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/estimators/linear.ipynb" rel="nofollow noreferrer">docs</a> for further help.</p>
<pre><code>import tensorflow as tf
import pandas as pd
import numpy as np
df = pd.DataFrame(data={'A': np.array([100, 105.4, 108.3, 111.1, 113, 114.7]),
'B': np.array([11, 11.8, 12.3, 12.8, 13.1,13.6]),
'C': np.array([55, 56.3, 57, 58, 59.5, 60.4]),
'Target': np.array([4000, 4200.34, 4700, 5300, 5800, 6400])})
print (df.describe())
featcols = [
tf.feature_column.numeric_column("A"),
tf.feature_column.numeric_column("B"),
tf.feature_column.numeric_column("C")
]
model = tf.estimator.LinearRegressor(featcols)
def make_input_fn():
def train_input_fn():
label = df.pop('Target')
print( label )
print ( df )
ds = tf.data.Dataset.from_tensor_slices((dict(df), label))
ds = ds.batch(1).repeat(1)
return ds
return train_input_fn
model.train(make_input_fn())
</code></pre>
<p>I've also shown here what is printed for me.</p>
<pre><code>Limited tf.compat.v2.summary API due to missing TensorBoard installation
Limited tf.summary API due to missing TensorBoard installation
A B C Target
count 6.000000 6.000000 6.00000 6.000000
mean 108.750000 12.433333 57.70000 5066.723333
std 5.421716 0.939503 2.01792 937.309351
min 100.000000 11.000000 55.00000 4000.000000
25% 106.125000 11.925000 56.47500 4325.255000
50% 109.700000 12.550000 57.50000 5000.000000
75% 112.525000 13.025000 59.12500 5675.000000
max 114.700000 13.600000 60.40000 6400.000000
WARNING: Logging before flag parsing goes to stderr.
W0313 19:30:06.720984 10576 estimator.py:1799] Using temporary folder as model directory: C:\Users\476458\AppData\Local\Temp\tmpkk4q3ute
W0313 19:30:06.767783 10576 deprecation.py:323] From C:\tensorflow2\lib\site-packages\tensorflow\python\training\training_util.py:238: Variable.
initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.
0 4000.00
1 4200.34
2 4700.00
3 5300.00
4 5800.00
5 6400.00
Name: Target, dtype: float64
A B C
0 100.0 11.0 55.0
1 105.4 11.8 56.3
2 108.3 12.3 57.0
3 111.1 12.8 58.0
4 113.0 13.1 59.5
5 114.7 13.6 60.4
W0313 19:30:06.861381 10576 deprecation.py:323] From C:\tensorflow2\lib\site-packages\tensorflow\python\feature_column\feature_column_v2.py:2758
: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.cast` instead.
W0313 19:30:07.220174 10576 deprecation.py:506] From C:\tensorflow2\lib\site-packages\tensorflow\python\training\slot_creator.py:187: calling Ze
ros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
2019-03-13 19:30:07.672566: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was
not compiled to use: AVX2
</code></pre>
|
python-3.x|tensorflow|tensorflow-estimator|tensorflow2.0
| 1 |
1,902,864 | 54,787,800 |
Looping over nested dictionary and delete if condition is not met (python)
|
<p>I have a list of nested dictionaries:</p>
<pre><code>[{'a': 1,
'b': 'string',
'c': [{'key1': 80,
'key2': 'string',
'key3': 4033},
{'key1': 324,
'key2': 'string',
'key3': 4034,
'key4': 1}]},
{'a': 1,
'b': 'string',
'c': [{'key1': 80,
'key2': 'string',
'key3': 4033},
{'key1': 324,
'key2': 'string',
'key3': 4034,
'key4': 1,
'key5': 2}]}]
</code></pre>
<p>Please not that the values of key <code>c</code> is a list of dictionaries again.
Now I want to filter out from this list all dictionaries with key <code>c</code>, that do not contain <code>key1</code>, <code>key2</code>, <code>key3</code> & <code>key4</code>.</p>
<p>I thought of looping first over the first, second, and so on <code>dict</code> in the list, and then looping over the nested <code>dict</code>s that have <code>c</code> as a key. Then, if the <code>dict</code> inside <code>c</code> does not meet my requirement, I delete it.</p>
<p>Therefore my code would be:</p>
<pre><code>for j in range(len(mydict)):
for i in range(len(mydict[j]["c"])):
if not all (k in mydict[j]["c"][i] for k in ("key1", "key2", "key3", "key4")):
del(mydict[j]["c"][i])
</code></pre>
<p>But I am getting a <code>IndexError: list index out of range</code> error. Where is my mistake?</p>
<p>My desired output would be:</p>
<pre><code>[{'a': 1,
'b': 'string',
'c': [{'key1': 324,
'key2': 'string',
'key3': 4034,
'key4': 1}]},
{'a': 1,
'b': 'string',
'c': [{'key1': 324,
'key2': 'string',
'key3': 4034,
'key4': 1,
'key5': 2}]}]
</code></pre>
|
<p>The problem is that with <code>for i in range(len(mydict[j]["c"])):</code> you are iterating the lists in the dict while at the same time removing from those lists. Instead, you can replace the inner loop with a list comprehension:</p>
<pre><code>for d in mydict:
d['c'] = [d2 for d2 in d['c']
if all(k in d2 for k in ("key1", "key2", "key3", "key4"))]
</code></pre>
|
python|list|dictionary|for-loop
| 2 |
1,902,865 | 55,064,016 |
How to pass an entire object in a multitraded program
|
<p>I'm started a concurrent program using Python. I have a simple question:
I'm using the class Thread to create several concurrent processes.
I would like these threads to pass objects to each other (so I would like that a thread not only notice a certain event, but takes an object from this event (when it happens)!).
How can I do this? Thanks a lot!</p>
<p>Example of code:</p>
<pre><code>class Process(Thread):
def __init__(self):
super(Processo, self).__init__()
def run(self):
myObject = SomeObject(param1, param2, param3)
# Code to pass myObject to all the threads
# Code waiting for the object to use it
def main():
process1 = Process()
process2 = Process()
process3 = Process()
process1.start()
process2.start()
process3.start()
</code></pre>
|
<p>You can use <code>queue.Queue</code> to communicate between threads. There is simple example of two threads. One thread puts items on the one side of the <code>queue</code> and the other take them. The <code>queue</code> can be also used for multi-producer multi-consumer application (but before implementing plan how it should work).</p>
<pre><code>from queue import Queue
from random import randint
import threading
import time
class Producer(threading.Thread):
def __init__(self, queue):
super(Producer, self).__init__()
self.queue = queue
def run(self):
while True:
thread_name = self.name
if not self.queue.full():
print('Will send "{}"'.format(thread_name))
self.queue.put(thread_name)
time.sleep(randint(1, 3))
class Consumer(threading.Thread):
def __init__(self, queue):
super(Consumer, self).__init__()
self.queue = queue
def run(self):
while True:
if not self.queue.empty():
received = self.queue.get()
print('Received "{}"'.format(received))
time.sleep(randint(1, 3))
if __name__ == '__main__':
q = Queue()
a = Producer(queue=q)
b = Consumer(queue=q)
a.start()
b.start()
a.join()
b.join()
</code></pre>
<p>The <code>sleeps</code> are only to slow it down for demonstration. There is documentation for <a href="https://docs.python.org/3/library/queue.html" rel="nofollow noreferrer">Queue</a></p>
<p><em>Note: Thread is not the same as a Process. Be careful with terminology you can be miss-understood.</em></p>
|
python|multithreading|events|python-multithreading
| 0 |
1,902,866 | 33,346,591 |
What is the difference between size and count in pandas?
|
<p>That is the difference between <code>groupby("x").count</code> and <code>groupby("x").size</code> in pandas ?</p>
<p>Does size just exclude nil ?</p>
|
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html#pandas.core.groupby.GroupBy.size"><code>size</code></a> includes <code>NaN</code> values, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.count.html#pandas.core.groupby.GroupBy.count"><code>count</code></a> does not:</p>
<pre><code>In [46]:
df = pd.DataFrame({'a':[0,0,1,2,2,2], 'b':[1,2,3,4,np.NaN,4], 'c':np.random.randn(6)})
df
Out[46]:
a b c
0 0 1 1.067627
1 0 2 0.554691
2 1 3 0.458084
3 2 4 0.426635
4 2 NaN -2.238091
5 2 4 1.256943
In [48]:
print(df.groupby(['a'])['b'].count())
print(df.groupby(['a'])['b'].size())
a
0 2
1 1
2 2
Name: b, dtype: int64
a
0 2
1 1
2 3
dtype: int64
</code></pre>
|
python|pandas|numpy|nan|difference
| 150 |
1,902,867 | 33,425,139 |
Django aggregate average of an annotation sum (1.6.5)
|
<hr>
<p>Currently trying to grab an average of a sum of a group by, but when I try to execute the correct queryset it complains of incorrect syntax</p>
<pre><code>objs = MyModel.objects.filter(...).values('user', 'value')
objs = objs.annotate(sum=Sum('value'))
# i've also tried adding `.values('sum')` to the above
objs = objs.aggregate(Avg('sum')) # whines here
</code></pre>
<p>Is there any way to do this without dropping in SQL? The desired SQL is along the lines of</p>
<pre><code>SELECT AVG(`sum`) as `avg` FROM (
SELECT SUM(`appname_mymodel`.`value`) AS `sum`
FROM `appname_mymodel`
GROUP BY
`appname_mymodel`.`user_id`, `appname_mymodel`.`value`
) as subquery ORDER BY NULL;
</code></pre>
<p>Not sure if django plays well with subqueries.</p>
<p>Here is the error message:</p>
<pre><code>ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM (SELECT SUM(`appname_mymodel`.`value`) AS `sum` FROM `appname_' at line 1")
</code></pre>
<p><strong>Django version</strong> - 1.6.5</p>
<p><strong>MySQL version</strong> - 5.5</p>
<p>Notes:</p>
<ul>
<li>If I leave off the <code>values</code> (the group by), it works fine (i.e. <code>objs.filter(...).annotate(...).aggregate(...)</code></li>
<li>The example below is sufficient as a fully reproducible example.</li>
</ul>
<p>Model:</p>
<pre><code># Create your models here.
class UserProfile(models.Model):
name = models.CharField(max_length=200)
class OtherFK(models.Model):
name = models.CharField(max_length=200)
class MyModel(models.Model):
# Happens if value is CharField or IntegerField
value = models.CharField(max_length=200, blank=True, null=True)
date = models.DateField()
user = models.ForeignKey(UserProfile)
other_fk = models.ForeignKey(OtherFK)
</code></pre>
<p>Example:</p>
<pre><code>>>> from app_name.models import UserProfile, OtherFK, MyModel
>>> up = UserProfile.objects.create(name="test")
>>> fk = OtherFK.objects.create(name="test")
>>> v1 = MyModel.objects.create(user=up, other_fk=fk, value="12", date="2015-10-01")
>>> v2 = MyModel.objects.create(user=up, other_fk=fk, value="13", date="2015-10-02")
>>> from django.db.models import Sum,Avg
>>> MyModel.objects.all().values("user").distinct().annotate(sum=Sum("value")).aggregate(Avg('sum'))
ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM (SELECT DISTINCT `app_name_mymodel`.`user_id` AS `user_id`, SUM(`app_name_m' at line 1")
>>> MyModel.objects.all().values("user").distinct().annotate(sum=Sum("value"))
[{'sum': 25.0, 'user': 1L}]
>>> print MyModel.objects.all().values("user").distinct().annotate(sum=Sum("value")).query
SELECT DISTINCT `app_name_mymodel`.`user_id`, SUM(`app_name_mymodel`.`value`) AS `sum` FROM `app_name_mymodel` GROUP BY `app_name_mymodel`.`user_id` ORDER BY NULL
</code></pre>
|
<p>Looks like this is a <a href="https://code.djangoproject.com/ticket/23669#comment:5" rel="nofollow">known bug</a> in Django 1.6, and need to upgrade to 1.7+ to fix</p>
<p>For now, I will just do the math in python.</p>
|
python|mysql|django|django-queryset|django-1.6
| 0 |
1,902,868 | 24,720,194 |
entry.delete(-1) Deletes second to last character in a entry field but I need the last. Python Tkinter
|
<p>I have a entry widget that when a user clicks a button it executes this code:</p>
<pre><code>entry.delete(-1)
</code></pre>
<p>But it removes the second to last character from the entry widget. I need to remove the last character why is this not working?</p>
|
<p>You may want to try</p>
<pre><code>entry.delete(len(entry.get())-1)
</code></pre>
<p>and see if that does the trick. This dynamically computes the index of the last character of any string in the Entry widget, and at least on Win7 deletes appropriately, from the right side.</p>
|
python|tkinter|widget|tkinter-entry
| 2 |
1,902,869 | 24,804,377 |
Need to add both image and text in one article in django
|
<p>I have 2 different classes for the post and the image,but I need both in one class so I can add the image related to the post from the admin site while adding post.And, I need to display the image next to the title</p>
<pre><code>class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
date = models.DateTimeField()
def __unicode__(self):
return self.title
class Image(models.Model):
image = models.ImageField(upload_to='%Y/%m/%d')
</code></pre>
|
<p>Did you update the database? you should have a <code>post_image_id</code> in your <code>blog_post</code> table. (related to you no such column error). Please be aware if you are running Django 1.6 or lower <code>./manage.py syncdb</code> will not update your database table. You should use South ore update your database manually.</p>
<p>If you fixed the no column error you can add an image to a post. (See Lafada's example)</p>
<p>If you want to have a m2m relation and add multiple images to your Post.</p>
<pre><code>image_a = Image()
image_b = Image()
blog = Blog().save() # You must save a blog before adding images in a m2m relation.
blog.images.add(image_a)
blog.images.add(image_b)
</code></pre>
<p>or</p>
<pre><code>blog = Blog().save()
for image in images:
blog.images.add(image)
blog.save()
</code></pre>
|
python|django
| 0 |
1,902,870 | 38,231,478 |
Why is relative path not working in python tests?
|
<p>My directory layout is as follows</p>
<pre><code>project\
project\setup.py
project\scripts\foo.py
project\scripts\bar.py
project\scripts\__init__.py
project\tests\test_foo.py
project\tests\__init__.py
</code></pre>
<p>My test file looks as follows</p>
<pre><code>project\tests\test_fo.py
from ..scripts import foo
def test_one():
assert 0
</code></pre>
<p>I get the following error, when I do </p>
<pre><code>cd C:\project
C:\virtualenvs\test_env\Scripts\activate
python setup.py install
python setup.py test
</code></pre>
<p><strong>E ValueError: Attempted relative import beyond toplevel package</strong></p>
<p>What am I doing wrong?
This is my setup.py</p>
<pre><code>setup(
name = 'project',
setup_requires=['pytest-runner'],
tests_require=['pytest'],
packages = ["scripts","tests"],
package_data={
'scripts': ['*.py'],
'tests': ['*.py'],
},
)
</code></pre>
|
<p>Relative imports only work <em>within</em> a package. <code>scripts</code> may be a package, and so is <code>tests</code>, but the <code>project</code> directory <em>is not</em> (and neither should it be). This makes <code>scripts</code> and <code>tests</code> <em>top-level packages</em>. You can't refer to other top-level names using relative syntax.</p>
<p>Moreover, tests are not run with the <code>tests</code> package; the test runner imports the <code>test_foo</code> module, not the <code>tests.test_foo</code> module, so <em>as far as Python is concerned</em> <code>test_foo</code> is a top-level module.</p>
<p><code>scripts</code> is a top-level name, just use that directly. You will have to add the <code>project</code> directory to <code>sys.path</code> however. You can do so at the top of your <code>test_foo.py</code> file with:</p>
<pre><code>import os
import sys
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.abspath(os.path.join(TEST_DIR, os.pardir))
sys.path.insert(0, PROJECT_DIR)
</code></pre>
<p>then import from <code>scripts</code> with absolute paths:</p>
<pre><code>from scripts import foo
</code></pre>
<p>Note however that when you run <code>python setup.py</code> then your current working directory is added to <code>sys.path</code> anyway, so <code>scripts</code> is available directly without having to fiddle with <code>sys.path</code>.</p>
<p>Moreover, pytest will <em>already</em> do the work for you; for any given test file it'll make sure the first parent directory with <em>no</em> <code>__init__.py</code> file in it is on <code>sys.path</code>. In your case that's the <code>project/</code> directory, so again <code>scripts</code> is directly available to import from. See <a href="http://pytest.org/latest/goodpractices.html#choosing-a-test-layout-import-rules" rel="noreferrer"><em>Good Practices</em></a>:</p>
<blockquote>
<p>If <code>pytest</code> finds a “a/b/test_module.py” test file while recursing into the filesystem it determines the import name as follows:</p>
<ul>
<li>determine <code>basedir</code>: this is the first “upward” (towards the root) directory not containing an <code>__init__.py</code>. If e.g. both a and b contain an <code>__init__.py</code> file then the parent directory of a will become the basedir.</li>
<li>perform <code>sys.path.insert(0, basedir)</code> to make the test module importable under the fully qualified import name.</li>
<li><code>import a.b.test_module</code> where the path is determined by converting path separators / into ”.” characters. This means you must follow the convention of having directory and file names map directly to the import names.</li>
</ul>
</blockquote>
<p>Note that in order to actually use <code>pytest</code> to run your tests when you use <code>setup.py test</code>, you need to register an alias in your <code>setup.cfg</code> file (create it in <code>project/</code> if you do not have one):</p>
<pre><code>[aliases]
test = pytest
</code></pre>
|
python|relative-path|setuptools|pytest|setup.py
| 10 |
1,902,871 | 38,385,558 |
Error Message When Converting to Grayscale in Python Using PIL?
|
<p>So, I've got PIL installed (at least I think properly) to convert color images to grayscale, and when I use this code </p>
<pre><code>from PIL import Image
image_file = Image.open("James.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('Gray.png')
</code></pre>
<p>IDLE shows me this...</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Kane/Desktop/huh.py", line 2, in <module>
image_file = Image.open("James.png")
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1952, in open
fp = __builtin__.open(fp, "rb")
IOError: [Errno 2] No such file or directory: 'James.png'
</code></pre>
<p>What do I need to do to fix this? I have Python 2.7, does this make a difference?</p>
|
<p>Your problem could be that the image file "James.png" is not in the same directory as your script, in your example on your Desktop. Is that the case?</p>
<p>Cheers</p>
|
python|image|python-imaging-library
| 1 |
1,902,872 | 38,144,640 |
Add up the value of data[x] to data[x+1]
|
<p>I have a long list of data which I am working with now,containing a list of 'timestamp' versus 'quantity'. However, the timestamp in the list is not all in order (for example,timestamp[x] can be 140056 while timestamp[x+1] can be 560). I am not going to arrange them, but to add up the value of timestamp[x] to timestamp[x+1] when this happens. </p>
<p>ps:The arrangement of quantity needs to be in the same order as in the list when plotting.</p>
<p>I have been working with this using the following code, which timestamp is the name of the list which contain all the timestamp values:</p>
<pre><code>for t in timestamp:
previous = timestamp[t-1]
increment = 0
if previous > timestamp[t]:
increment = previous
t += increment
delta = datetime.timedelta(0, (t - startTimeStamp) / 1000);
timeAtT = fileStartDate + (delta + startTime)
print("time at t=" + str(t) + " is: " + str(timeAtT));
previous = t
</code></pre>
<p>However it comes out with TypeError: list indices must be integers, not tuples. May I know how to solve this, or any other ways of doing this task? Thanks!</p>
|
<p>The problem is that you're treating <code>t</code> as if it is an <em>index</em> of the list. In your case, <code>t</code> holds the actual values of the list, so constructions like <code>timestamp[t]</code> are not valid. You either want:</p>
<pre><code>for t in range(len(timestamp)):
</code></pre>
<p>Or if you want both an index and the value:</p>
<pre><code>for (t, value) in enumerate(timestamp):
</code></pre>
|
python|python-3.x
| 0 |
1,902,873 | 31,141,362 |
Maya - check if an attributes is enabled / disabled
|
<p>Since hours I try to solve a problem I have with Maya / MEL / Python.
I have a script to set values of a fluid container. </p>
<p>E.g. setAttr "fluidShape1.densityDissipation" 0.2</p>
<p>Works great...</p>
<p>My problem: Actually it is not possible to change the value using the interface (see image). Is there a way to find out if the "text box" is enabled?</p>
<p>Thanks!!</p>
<p>P.S. I cant upload the image :(. But I hope you guys know what i mean</p>
|
<p>To find out if the attribute is settable, use</p>
<pre><code>getAttr -settable your_object.your_attribute
</code></pre>
<p>it will return 1 if you can set the attribute using <code>setAttr</code> and 0 if you can't.</p>
<p>If the value is grayed out in the UI the attribute is <em>locked</em>, you can unlock it with </p>
<pre><code>setAttr -lock 0 your_object.your_attribute
</code></pre>
<p>If the value is purple in the UI it's driven by a connection of some kind, you'll need to use the hypergraph or the <code>listConnections</code> command to find out what's driving it and decide if you want to override the connection.</p>
|
python|maya|mel
| 1 |
1,902,874 | 29,080,348 |
Using numpy arrays with lpsolve?
|
<p>In the docs, it says you can use numpy arrays:</p>
<blockquote>
<p>numpy package</p>
<p>In the above section Maximum usage of matrices with lpsolve the
package numpy was already mentioned. See <a href="http://numpy.scipy.org/" rel="nofollow">http://numpy.scipy.org/</a> for a
brief overview. This package is the successor of the older and
obsolete package Numeric. Since lp_solve is all about arrays and
matrices, it is logical that the lpsolve Python driver accepts numpy
arrays. This is possible from driver version 5.5.0.9. Before it was
needed that numpy arrays were converted to lists. For example:</p>
</blockquote>
<pre><code>>>> from numpy import *
>>> from lpsolve55 import *
>>> lp=lpsolve('make_lp', 0, 4);
>>> c = array([1, 3, 6.24, 0.1])
>>> ret = lpsolve('set_obj_fn', lp, c)
</code></pre>
<blockquote>
<p>Note that the numpy array variable c is passed directly to lpsolve.
Before driver version 5.5.0.9 this gave an error since lpsolve did not
know numpy arrays. They had to be converted to lists:</p>
</blockquote>
<pre><code>>>> ret = lpsolve('set_obj_fn', lp, list(c))
</code></pre>
<blockquote>
<p>That is ok for small models, but for larger arrays this gives an extra
memory overhead since c is now two times in memory. Once as the numpy
array and once as list.</p>
<p>Note that all returned arrays from lpsolve are always lists.</p>
<p>Also note that the older package Numeric is not supported by lpsolve.
So it is not possible to provide a Numeric array to lpsolve. That will
give an error.</p>
</blockquote>
<p><a href="http://lpsolve.sourceforge.net/5.5/Python.htm" rel="nofollow">http://lpsolve.sourceforge.net/5.5/Python.htm</a></p>
<p>When I attempt to do that I get an error.</p>
<pre><code>lp = lpsolve('make_lp', 0, 7)
coef = np.array([0, 0, 0, 1, 1, 1, 1])
lpsolve('set_obj_fn', lp, coef)
</code></pre>
<p>Results in:</p>
<pre><code>lpsolve('set_obj_fn', lp, coef)
lpsolve.error: invalid vector.
</code></pre>
<p>If I would do:</p>
<pre><code>lpsolve('set_obj_fn', lp, coef.tolist())
</code></pre>
<p>It works but costs much more memory (in the general case).</p>
<p>When I run <code>lpsolve()</code></p>
<p>It results in:</p>
<pre><code>lpsolve Python Interface version 5.5.0.9
using lpsolve version 5.5.2.0
</code></pre>
|
<p>You can use PyLPSolve if you are having trouble with lpsolve. It is a wrapper for lpsolve that allowed me to use numpy arrays.</p>
<p><a href="http://www.stat.washington.edu/~hoytak/code/pylpsolve/" rel="nofollow">http://www.stat.washington.edu/~hoytak/code/pylpsolve/</a></p>
|
python|numpy|lpsolve
| 0 |
1,902,875 | 8,794,506 |
Adding wxPython GUI elements in a pygame physics simulation
|
<p>I have made a pygame physics simulation--'a projectile motion' but it lacks interactivity like accepting angle of launch,speed etc. I am wanting to add input boxes with increase decrease arrows but don't know how to go about it. Thanks for the help. </p>
|
<p>Maybe you can try <a href="http://www.pygame.org/project/108/" rel="nofollow noreferrer">PGU</a> (Phil's pyGame Utilities).</p>
<p>In addition to other tools, it has a library for creating GUIs.<br>
This PGU demo shows probably something similar to that you are looking for:</p>
<p><img src="https://i.stack.imgur.com/aDX6I.png" alt="enter image description here"></p>
|
python|wxpython|physics|simulation|pygame
| 2 |
1,902,876 | 52,032,024 |
Can bs4 to parse tag with <style='display:none;'>?
|
<p>If you browse this page <code>https://weathernews.jp/s/topics/201808/220015/?fm=tp_index</code>, you will two images, when I parse it as code:</p>
<pre><code>from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options
from urllib.parse import urljoin
import re
options = Options()
options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=options)
driver.get('https://weathernews.jp/s/topics/201808/220015/?fm=tp_index')
soup_level2 = BeautifulSoup(driver.page_source, 'lxml')
sections = soup_level2.find_all("img")
for section in sections:
image = re.findall(r"(https://smtgvs.weathernews.jp/s/topics/img/[0-9]+/.+)\?[0-9]+", urljoin('https://weathernews.jp/', section['src']))
if image:
print(image[0])
else:
image = re.findall(r"(https://smtgvs.weathernews.jp/s/topics/img/[0-9]+/.+)\?[0-9]+", urljoin('https://weathernews.jp/', section.get("data-original")))
if image:
print(image[0])
</code></pre>
<p>I got images as below</p>
<pre><code>https://smtgvs.weathernews.jp/s/topics/img/201808/201808220015_top_img_A.jpg
https://smtgvs.weathernews.jp/s/topics/img/201808/201808220015_box_img0_A.jpg
https://smtgvs.weathernews.jp/s/topics/img/201808/201808220015_box_img1_A.jpg
https://smtgvs.weathernews.jp/s/topics/img/201808/201808220015_box_img2_A.jpg
https://smtgvs.weathernews.jp/s/topics/img/201808/201808220015_box_img5_A.png
</code></pre>
<p>In fact, there are two other images with <code>style="display: none;"</code> on page, can you help me to parse them?</p>
<pre><code><section id="box3" class="nodisp_zero" style="display: none;">
<h1 id="box_ttl3" style="display: none;"></h1>
<img style="width: 100%; display: none;" id="box_img3" alt="box3" src="https://smtgvs.weathernews.jp/s/topics/img/dummy.png" class="lazy" data-original="https://smtgvs.weathernews.jp/s/topics/img/201808/201808220015_box_img3_A.jpg?1533975785">
<figcaption id="box_caption3" style="display: none;"></figcaption>
<div class="textarea clearfix">
<h2 id="box_subttl3" style="display: none;"></h2>
<div class="fontL" id="box_com3" style="display: none;"></div>
</div>
</section>
</code></pre>
|
<p>You can query the html using the attributes.</p>
<p><strong>Ex:</strong></p>
<pre><code>html = """<section id="box3" class="nodisp_zero" style="display: none;">
<h1 id="box_ttl3" style="display: none;"></h1>
<img style="width: 100%; display: none;" id="box_img3" alt="box3" src="https://smtgvs.weathernews.jp/s/topics/img/dummy.png" class="lazy" data-original="https://smtgvs.weathernews.jp/s/topics/img/201808/201808220015_box_img3_A.jpg?1533975785">
<figcaption id="box_caption3" style="display: none;"></figcaption>
<div class="textarea clearfix">
<h2 id="box_subttl3" style="display: none;"></h2>
<div class="fontL" id="box_com3" style="display: none;"></div>
</div>
</section>"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
print( soup.find("section", {"style": "display: none;"}).img["data-original"] )
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>https://smtgvs.weathernews.jp/s/topics/img/201808/201808220015_box_img3_A.jpg?1533975785
</code></pre>
|
css|python-3.x|beautifulsoup|styles|display
| 0 |
1,902,877 | 62,467,330 |
Why use if in to check string value is no working?
|
<p>Sorry for very basic question. I am not familiar with Python.</p>
<p>I check my mac terminal <code>python --version</code> is 3.7.6</p>
<p>and I use the code</p>
<pre><code>if '/watch?v=YtJ9dkFgjeQ' in '=':
print('Include =')
else:
print('fail')
pass
</code></pre>
<p>I want to check include <code>=</code> or not, but no idea why it prints fail.</p>
|
<p>You can try</p>
<pre><code>print('Include =' if '/watch?v=YtJ9dkFgjeQ'.count("=") > 0 else 'fail')
</code></pre>
<p>or </p>
<pre><code>print('Include =' if '/watch?v=YtJ9dkFgjeQ'.find("=") > 0 else 'fail')
</code></pre>
<p>This will check if <code>"="</code> in string <code>'/watch?v=YtJ9dkFgjeQ'</code> and print the relevant output.</p>
|
python|python-3.x
| 1 |
1,902,878 | 62,375,432 |
Is there a __dunder__ method corresponding to |= (pipe equal/update) for dicts in python 3.9?
|
<p>In python 3.9, dictionaries gained combine <code>|</code> and update <code>|=</code> operators. Is there a dunder/magic method which will enable this to be used for other classes? I've tried looking in the python source but found it a bit bewildering.</p>
|
<p>Yes, <code>|</code> and <code>|=</code> correspond to <a href="https://docs.python.org/3/reference/datamodel.html#object.__or__" rel="nofollow noreferrer"><code>__or__</code></a> and <a href="https://docs.python.org/3/reference/datamodel.html#object.__ior__" rel="nofollow noreferrer"><code>__ior__</code></a>.</p>
<p>Don't look at the <em>python source code</em>, look at the documentation. In particular, the data model. </p>
<p>See <a href="https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types" rel="nofollow noreferrer">here</a></p>
<p>And note, this isn't specific to python 3.9.</p>
|
python|python-3.x|python-3.9
| 10 |
1,902,879 | 56,432,848 |
How to create a histogram in Python one data point at a time?
|
<p>I need to create a histogram of a very large data set in python 3. However, I cannot use a list to create a histogram because the list would be too large given my data. I need a way to update a histogram as each data point is created. That way my computer is only ever dealing with a single point and updating the plot.</p>
<p>I've been using matplotlib. Tried plt.draw() but couldn't get it to work. (See code below) </p>
<pre><code>#Proof of concept code
l = [1, 2, 3, 2, 3, 2]
n = 0
p = False
for x in range(0,6):
n = l[x]
if p == False:
fig = plt.hist(n)
p = True
else:
plt.draw()
</code></pre>
<p>I need a plot that looks like plt.hist(l). But have only been getting the first point plotted.</p>
|
<p>Are you familiar with Numpy? Numpy handles large arrays pretty well. </p>
<p>Here's an example using a random integer set from 1 to 3 (inclusive).</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
arr_random = np.random.randint(1,4,10000)
plt.hist(arr_random)
plt.show()
</code></pre>
<p>It's very efficient to compute plt.hist() with Numpy arrays.</p>
|
python
| 0 |
1,902,880 | 67,492,184 |
Use Multi processing for NetfilterQueue delay function
|
<p>I am unable to use Multiprocessing with Netfilter queue. Code and errors are as below:</p>
<p>ERROR:
TypeError: print_and_accept() missing 1 required argument: 'pkt'</p>
<pre><code>
nfqueue = NetfilterQueue()
nfqueue.bind(1, print_and_accept)
try:
nfqueue.run()
except KeyboardInterrupt:
print('')
global a
time.sleep(ransecs)#ADD DELAY calculated by delay_calc()
print(pkt)
pkt.accept()
#delay_calc()
nfqueue.unbind()
p2 = multiprocessing.Process(target=print_and_accept())
if __name__ == '__main__':
p2.start()```
</code></pre>
|
<p>The multiprocessing library gives this example:</p>
<pre><code>p = Process(target=f, args=('bob',))
</code></pre>
<p>Because of the way the Process class is formatted, you must change your multiprocessing line to:</p>
<pre><code>p2 = multiprocessing.Process(target=print_and_accept, args=('args',))
</code></pre>
<p>The problem arises from putting the brackets after the function reference, which calls the function and causes the error. Removing these and adding arguments as required (in the form of a tuple) should fix your problem.</p>
<p>Comment any questions down below.</p>
|
python|python-3.x|python-multiprocessing|netfilter
| 0 |
1,902,881 | 36,296,786 |
AttributeError: 'module' object has no attribute 'update_settings' scrapy 1.0.5
|
<p>The crawler works fine by command line by gives this error:</p>
<pre><code>2016-03-30 03:47:59 [scrapy] INFO: Scrapy 1.0.5 started (bot: scrapybot)
2016-03-30 03:47:59 [scrapy] INFO: Optional features available: ssl, http11
2016-03-30 03:47:59 [scrapy] INFO: Overridden settings: {'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'}
Traceback (most recent call last):
File "/home/ahmeds/scrapProject/crawler/startcrawls.py", line 11, in <module>
process.crawl(onioncrawl)
File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 150, in crawl
crawler = self._create_crawler(crawler_or_spidercls)
File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 166, in _create_crawler
return Crawler(spidercls, self.settings)
File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 32, in __init__
self.spidercls.update_settings(self.settings)
AttributeError: 'module' object has no attribute 'update_settings'
</code></pre>
<p>This is my code for running my crawler by script as per <a href="http://doc.scrapy.org/en/latest/topics/practices.html" rel="noreferrer">latest documentation</a>. My scrapy version is 1.0.5.</p>
<pre><code>from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from crawler.spiders import onioncrawl
setting = get_project_settings()
process = CrawlerProcess(setting)
process.crawl(onioncrawl)
process.start()
</code></pre>
|
<p>I was using Spider filename instead of Spider class name. </p>
|
python-2.7|scrapy|scrapy-spider|attributeerror
| 16 |
1,902,882 | 19,393,273 |
Opening terminal using python
|
<p>Currently I've been creating just a small program. And one of the options is to start a counter.</p>
<p>Code for counter</p>
<pre><code>from time import sleep
number = 0
while 1 == 1:
sleep(1)
print number
number += 1
</code></pre>
<p>I want to be able to open this program in a new terminal window (Ubuntu) so I can keep the existing terminal open. Anyway to do this in python?</p>
<p>Thanks</p>
<p>Paul</p>
<p><strong>EDIT</strong>
I think I figured out one way to run it in the same terminal so it works!</p>
<pre><code>os.system('python counter.py')
</code></pre>
<p>I simply used that, I thought if I were to do that before, when I used CTRL + C it would close down both programs but this seems to of worked. Thanks for the answers!</p>
|
<p>You could create a wrapper that launches your terminal and tells it to run your script. If you know which terminal you're using, this isn't too hard. For example, if you use <a href="http://multignometerm.sourceforge.net/web/doc/options.html" rel="nofollow"><code>multi-gnome-terminal</code></a>:</p>
<pre><code>#!/bin/sh
multi-gnome-terminal --use-factory --command /usr/bin/python /path/to/my/script.py
</code></pre>
<p>Now, every time you run that wrapper (with <code>sh ./wrapper</code>, or <code>/usr/local/bin/wrapper</code> if you <code>install -m755</code> it, or by double-clicking it, or whatever), it will open a new window (launching a new terminal process only if necessary) and run your script there.</p>
|
python|terminal
| 0 |
1,902,883 | 22,421,669 |
External python application is not running
|
<p>Hi i just create a java application to run my python code externally. But it want giving me the out put.
this is my java code:-</p>
<pre><code> package com.epatient;
import java.io.*;
public class InterpreterExample {
//static String workingDir = System.getProperty("user.dir");
//static String appDir = workingDir + "\\epatient\\epatient_prediction.py";
public static void main(String a[]){
try{
String appDir = "C:\\Users\\Thushara Kasun\\Documents\\juno\\serial.port\\epatient\\epatient_prediction.py";
System.out.println(appDir);
ProcessBuilder pb = new ProcessBuilder("python",appDir);
Process p = pb.start();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);
}catch(NumberFormatException e){e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
}
</code></pre>
<p>this is my python code :-</p>
<pre><code> import sys
from sklearn.externals import joblib
import pandas as pd
import numpy as np
import csv
from sklearn.decomposition import PCA
import re
import psycopg2
import datetime
import time
con = None
bio_data = None
heart_rate = None
so2_data = None
temp_data = None
bp_data = None
try:
con = psycopg2.connect(database='Epatient_user_1', user='postgres', password='root')
cur = con.cursor()
...#database access codes omited
model_name = 'trained_model'
est = joblib.load(model_name)
predictions = est.predict(data)
#predictions
# <codecell>
#sys.stdout.write(str(int(predictions[0])))
#sys.stdout.flush()
#print int(predictions[0])
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
#print st
cur.execute('INSERT INTO patient_status (STATUS,TIME,PROCESSED) VALUES (' + str(int(predictions[0])) + ',\''+ st + '\',0);')
con.commit()
except psycopg2.DatabaseError, e:
print 'Error %s' % e
sys.exit(1)
finally:
if con:
con.close()
sys.stdout.write(str(int(predictions[0])))
sys.stdout.flush()
#print int(predictions[0])
</code></pre>
<p>Java out put is just <strong>value is : null</strong>
there is no problem with the python code it is working perfectly. i just want to print a Boolean which is in a string format. simultaneously i need to update that value in my local postgresql database(via python code, which is working individually). simply the python code is not executing by my java application. Kindly help me on this or give me a alternative way to resolve this issue. </p>
|
<p>I think that your Java code is Ok, then try to change your Python script.</p>
<p>Please, would you be so kind to change the line <code>print int(predictions[0])</code> with:</p>
<pre><code>sys.stdout.write(str(predictions[0]))
sys.stdout.flush()
</code></pre>
<p><code>sys.stdout</code> will print data to console outputstream</p>
<p>and just for testing, put the absolute path of your script in the ProcessBuilder constructor:</p>
<pre><code>String appDir = "C:\\my\\full\\path\\to\\script.py";
ProcessBuilder pb =
new ProcessBuilder("python", appDir);
Process p = pb.start();
....
</code></pre>
|
java|postgresql|python-2.7|bufferedreader|processbuilder
| 1 |
1,902,884 | 16,683,964 |
How to do a background check on entry into the m2m communication in the query?
|
<p>There are models:</p>
<pre><code>class MyObject (models.Model):
name = models.CharField ()
class Day (models.Model):
day = models.IntegerField ()
class Month (models.Model):
month = models.IntegerField ()
myobj = models.ForeignKey (MyObject)
days = models.ManyToManyField (Day)
</code></pre>
<p>User with a form on the website introduces a month.
I make a request:</p>
<pre><code>MyObject.objects.filter (month__month = <month, which is entered by the user with the form>
<day, which is entered by the user with the form> in month__days????
)
</code></pre>
<p>How to check the query that the user entered date is (present) in the m2m communication days in the model Month?</p>
|
<p>You <a href="https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/" rel="nofollow">can query M2M Fields just like you would FK relationships</a>: </p>
<pre><code>day = Day.objects.get(day=1)
Month.objects.filter(days=day)
</code></pre>
<p>But you need to do <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">a reverse lookup</a> on the relationship between <code>MyObject</code> and <code>Day</code>:</p>
<blockquote>
<p>To refer to a “reverse” relationship, just use the lowercase name of the model.</p>
</blockquote>
<pre><code>day = Day.objects.get(day=5)
month = Month.objects.get(month=3)
MyObject.objects.filter(month__month=month, month__days=day)
</code></pre>
|
python|django|model
| 0 |
1,902,885 | 17,104,086 |
Python Brute Force Password Resume Capability
|
<p>Recently, I started coding a simple python Brute Forcer for web forms and so far so good.</p>
<p>But, i want my bruteforcer to be capable of stopping a brute force operation and resume later with the previous session.</p>
<p>To do this i want to keep the last password tested and enter it sometime later, that's not the problem.
My problem is that i don't know how to start bruteforcing from a specific word.</p>
<p>As an example, when i enter the word "Orange",
i want the program to continue testing:
Orangf,
Orangg,
Orangh and so on..</p>
<p>So far i'm using this code to do a simple bruteforce with the charset <code>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789</code>
and length 6 characters.</p>
<pre><code>for word in itertools.imap(''.join, itertools.product('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', repeat=6)):
</code></pre>
|
<p>It might be that this question contains part of the answer to yours:
<a href="https://stackoverflow.com/questions/9864809/using-itertools-product-and-want-to-seed-a-value">Using itertools.product and want to seed a value</a></p>
|
python|passwords
| 1 |
1,902,886 | 16,740,899 |
How would one go about having a python script run automatically across all platforms?
|
<p>I'm writing a fairly simple script that backs up files to AWS S3. But that's fairly irrelevant to my question at hand. The user is going to specify how often they want the script to run, probably through command line inputs. I just want to run the one script just the once. The other requirement is it needs to run on all platforms. I discovered the CronTab module, but that's only relevant to Linux and sometimes OSX. </p>
<p>Basically I'm looking for a set it and forget it approach to a python script.</p>
<p>My other question, does the scheduling have to happen in a separate script, or is there a way to include the scheduling of running the script in the script itself?</p>
|
<p>This is in general a Platform dependent Scheduler Question. For instance <a href="http://en.wikipedia.org/wiki/Cron" rel="nofollow">Cron</a> in *nix, Windows, <a href="http://windows.microsoft.com/en-in/windows7/schedule-a-task" rel="nofollow">Task Scheduler</a> in Windows, <a href="http://publib.boulder.ibm.com/infocenter/zos/v1r11/index.jsp?topic=/com.ibm.zos.r11.hasa300/ch2scen.htm" rel="nofollow">JES2</a> in zOS. Basically you need a demon process, to automatically trigger Job. You can also create a simple Python Script using <a href="http://docs.python.org/2/library/threading.html#timer-objects" rel="nofollow">threading.Timer</a></p>
<p>If you need a platform independent solution, you can look forward to the following solution <a href="http://pythonhosted.org/APScheduler/" rel="nofollow">
Advanced Python Scheduler</a></p>
|
python|scripting|cross-platform
| 2 |
1,902,887 | 16,621,896 |
IPython notebook in zc.buildout not using eggs path
|
<p>I've build an environment with zc.buildout including IPython script.</p>
<p>My problem is simple:</p>
<ul>
<li><p>if I launch IPython in console, everything is OK and I get all my eggs in sys.path</p></li>
<li><p>but if I launch IPython notebook, I only get default system path.</p></li>
</ul>
<p>Is there any way to include all my eggs while starting notebook?</p>
<p>Regards,</p>
<p>Thierry</p>
|
<p>So, I guess somewhere in the notebook startup a process is forked, which means sys.path will get reset and buildout's tricks won't help.</p>
<p>I solved the problems as follows, although it's a bit dirty:</p>
<ol>
<li><p>Create an entry point as follows:</p>
<pre><code>setup(...
entry_points = {
'console_scripts': ['ipython = <yourpackage>.ipython:main']
})
</code></pre></li>
<li><p>Put the following in /ipython.py:</p>
<pre><code>from IPython.frontend.terminal.ipapp import launch_new_instance
import os
import sys
def main():
os.environ['PYTHONPATH']=':'.join(sys.path)
sys.exit(launch_new_instance())
</code></pre></li>
</ol>
<p>Now, running <code>bin/ipython notebook</code> will give you the sys.path you expect.</p>
|
ipython|ipython-notebook
| 1 |
1,902,888 | 17,056,408 |
flask jinja2 href not linking correctly
|
<p>I have a jinja2 template that contains hrefs</p>
<pre><code><td><a href="{{entry.Url}}">Product URL</a></td>
</code></pre>
<p>However, when I run the application and click the link on the page I get the development server in front of the correct url. So it would look like the following in the browser:</p>
<pre><code>http://121.1.2.1:8764/www.google.com/
</code></pre>
<p>When I just want the following link:</p>
<pre><code>www.google.com
</code></pre>
<p>Any ideas on how I can get this to work?</p>
<p>Thanks!</p>
|
<p>This worked for me while testing.</p>
<pre><code><a href="{{ ''.join(['http://', entry.Url]) }}">{{ entry.Url }}</a>
# entry.Url == www.google.com
# <a href="http://www.google.com">www.google.com</a>
</code></pre>
|
python|flask|jinja2
| 9 |
1,902,889 | 53,645,291 |
python pandas module unable to fetch movie name
|
<p>i have these test codes about web scraping i am trying out but i am unable to fetch all the names of the movies from the site.
Here is the Code</p>
<pre><code> from requests import get
from bs4 import BeautifulSoup
import pandas as pd
url = 'http://www.imdb.com/search/title?
release_date=2017&sort=num_votes,desc&page=1'
response = get(url)
print(response.text[:500])
html_soup = BeautifulSoup(response.text, 'html.parser')
type(html_soup)
movie_containers = html_soup.find_all('div', class_ = 'lister-item
mode-advanced')
print(type(movie_containers))
print(len(movie_containers))
first_movie = movie_containers[0]
first_movie
first_movie.div
first_movie.a
first_movie.h3
first_movie.h3.a
first_name = first_movie.h3.a.text
first_year = first_movie.h3.find('span', class_ = 'lister-item-year text-
muted unbold ')
print(first_movie.strong)
first_imdb = float(first_movie.strong.text)
print"IMDB= " ,first_imdb
first_mscore = first_movie.find('span', class_ = 'metascore favorable')
first_mscore = int(first_mscore.text)
print "First MetaScore", first_mscore
first_votes = first_movie.find('span', attrs = {'name':'nv'})
first_votes['data-value']
first_votes = int(first_votes['data-value'])
print "First_Votes=",first_votes
eighth_movie_mscore = movie_containers[7].find('div', class_ = 'ratings-
metascore')
type(eighth_movie_mscore)
# Lists to store the scraped data in
names = []
years = []
imdb_ratings = []
metascores = []
votes = []
# Extract data from individual movie container
for container in movie_containers:
# If the movie has Metascore, then extract:
if container.find('div', class_ = 'ratings-metascore') is not None:
# The name
name = container.h3.a.text
names.append(name)
# The year
year = container.h3.find('span', class_ = 'lister-item-year').text
years.append(year)
# The IMDB rating
imdb = float(container.strong.text)
imdb_ratings.append(imdb)
# The Metascore
m_score = container.find('span', class_ = 'metascore').text
metascores.append(int(m_score))
# The number of votes
vote = container.find('span', attrs = {'name':'nv'})['data-value']
votes.append(int(vote))
test_df = pd.DataFrame({
'movie': names,
'year': years,
'imdb': imdb_ratings,
'metascore': metascores,
'votes': votes})
print(test_df.info())
print (test_df)
</code></pre>
<p>The output is not showing only the movies' name but the rest are showing properly without any problem.
RangeIndex: 46 entries, 0 to 45
Data columns (total 5 columns):
imdb 46 non-null float64
metascore 46 non-null int64
movie 46 non-null object
votes 46 non-null int64
year 46 non-null object
dtypes: float64(1), int64(2), object(2)
memory usage: 1.9+ KB</p>
|
<pre><code>from requests import get
from bs4 import BeautifulSoup
import pandas as pd
url = 'http://www.imdb.com/search/title?release_date=2017&sort=num_votes,desc&page=1'
response = get(url)
print(response.text[:500])
html_soup = BeautifulSoup(response.text, 'html.parser')
type(html_soup)
movie_containers = html_soup.find_all('div', class_ = 'lister-item mode-advanced')
print(type(movie_containers))
print(len(movie_containers))
first_movie = movie_containers[0]
first_movie
first_movie.div
first_movie.a
first_movie.h3
first_movie.h3.a
first_name = first_movie.h3.a.text
first_year = first_movie.h3.find('span', class_ = 'lister-item-year text- muted unbold ')
print(first_movie.strong)
first_imdb = float(first_movie.strong.text)
print("IMDB= ", first_imdb)
first_mscore = first_movie.find('span', class_ = 'metascore favorable')
first_mscore = int(first_mscore.text)
print ("First MetaScore", first_mscore)
first_votes = first_movie.find('span', attrs = {'name':'nv'})
first_votes['data-value']
first_votes = int(first_votes['data-value'])
print ("First_Votes=",first_votes)
eighth_movie_mscore = movie_containers[7].find('div', class_ = 'ratings-metascore')
type(eighth_movie_mscore)
# Lists to store the scraped data in
names = []
years = []
imdb_ratings = []
metascores = []
votes = []
# Extract data from individual movie container
for container in movie_containers:
# If the movie has Metascore, then extract:
if container.find('div', class_ = 'ratings-metascore') is not None:
# The name
name = container.h3.a.text
names.append(name)
# The year
year = container.h3.find('span', class_ = 'lister-item-year').text
years.append(year)
# The IMDB rating
imdb = float(container.strong.text)
imdb_ratings.append(imdb)
# The Metascore
m_score = container.find('span', class_ = 'metascore').text
metascores.append(int(m_score))
# The number of votes
vote = container.find('span', attrs = {'name':'nv'})['data-value']
votes.append(int(vote))
test_df = pd.DataFrame({
'movie': names,
'year': years,
'imdb': imdb_ratings,
'metascore': metascores,
'votes': votes})
print(test_df.info())
print (test_df)
</code></pre>
<p>This works for me.
<a href="https://i.stack.imgur.com/oM710.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oM710.png" alt="enter image description here"></a></p>
|
python|pandas
| -1 |
1,902,890 | 54,506,457 |
Simple Python return "or" condition
|
<p>I'm new at python 3.</p>
<p>in javascript this returns true if any of the conditions are true, otherwise it returns false</p>
<pre><code>return condition1 || condition2 || condition3;
</code></pre>
<p>But in python this returns
<code>TypeError: 'int' object is not iterable</code>
(n1 and n2 being ints)</p>
<pre><code>return (n1==20) or (n2==20) or (sum(n1,n2)==20)
</code></pre>
<p>Is this just not possible in python or am I using the wrong syntax?</p>
|
<p>The problem is with <code>sum</code>; it takes only one argument that is iterable. Just make it a list/tuple:</p>
<pre><code>return (n1==20) or (n2==20) or (sum([n1, n2])==20)
</code></pre>
<p>Or, considering you only have only two numbers, just do <code>n1 + n2</code>.</p>
|
javascript|python|python-3.x|conditional-statements
| 2 |
1,902,891 | 54,523,763 |
Using python to sum n terms of a sequence using only for and while loops
|
<p>I am having to ask the user for an input for n amount of terms and also their chosen value for x for this sequence.</p>
<pre><code>x^5/5 - x^7/7 + x^9/9 - x^11/11 + ...
</code></pre>
<p>I am having trouble accounting for the sign change every other term, and can't use any if statements.</p>
<p>Any help would be much appreciated, thanks!</p>
<p>My code so far:</p>
<pre><code>print(" ")
print("Please enter the number of terms you would like to sum up.")
print("The sequence is x^5/5-x^7/7+x^9/9-...")
print(" ")
n=int(input('Number = '))
print(" ")
print("Please enter the number for x.")
print(" ")
x=int(input('x = '))
#
nsum=0
for i in range(5,n+6,2):
coefficient=1/i
for j in range(5,i+1,2):
coefficient=-1*coefficient
nsum=nsum+coefficient*x**i
#
print(nsum)
</code></pre>
|
<p>Your sequence shows the nth term is positive if n is odd, negative if it is even. So you can do this in your for loop. Also in your code the user input n does not equal to the number of terms:</p>
<pre><code>nsum=0
for index in range(0, n):
coefficient=(-1)**(index)
i = 2*index + 5
nsum=nsum+coefficient*x**i/i
</code></pre>
|
python
| 0 |
1,902,892 | 71,211,685 |
Using .sort_values() in Python
|
<p>I am trying to figure out how to sort a dataframe base on the values of a column.</p>
<p>At the moment, it is re-organising the dataframe order, but not in order of smallest -> largest or largest -> smallest. It seems to be a random order.</p>
<p><a href="https://i.stack.imgur.com/tbjRo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tbjRo.png" alt="enter image description here" /></a></p>
<p>What am I doing wrong?</p>
|
<p>It looks like the <code>Impressions</code> column is stored as a string rather than as an int. So, it's sorting the digit representations in "alphabetical" order.</p>
<p>One solution is to change the values to <code>int</code> within the data frame. Another is to use a <code>key</code> for the <code>sort_values</code> call that converts the string to a number.</p>
|
python|dataframe|sorting
| 0 |
1,902,893 | 37,410,973 |
copy csv file into sqlite database table using python
|
<p>There is a post that tells me how to write data fom a csv-file into a sqlite database (<a href="https://stackoverflow.com/questions/2887878/importing-a-csv-file-into-a-sqlite3-database-table-using-python">link</a>). <strong>Is there a way to simply copy the whole file into a database table</strong> instead of loading the data and then iterate through the rows appending them to the table as suggested in the link.</p>
<p>To do this in sqlite it says <a href="https://stackoverflow.com/questions/2887878/importing-a-csv-file-into-a-sqlite3-database-table-using-python">here</a> to simply type</p>
<pre><code>sqlite> create table test (id integer, datatype_id integer, level integer, meaning text);
sqlite> .separator ","
sqlite> .import no_yes.csv test
</code></pre>
<p>I am new to working with databases and sqlite3, but I thought doing something like this could work</p>
<pre><code>import sqlite3
conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()
def create_table(name):
c.execute("CREATE TABLE IF NOT EXISTS {} (time REAL, event INTEGER, id INTEGER, size INTERGER, direction INTEGER)".format(name))
def copy_data(file2copy,table_name):
c.executescript("""
.separator ","
.import {} {}""".format(file2copy,table_name))
conn.commit()
try:
create_table('abc')
copy_data(r'Y:\MYPATH\somedata.csv','abc')
except Exception as e:
print e
c.close()
conn.close()
</code></pre>
<p>But apparently it doesn't. I get the error</p>
<pre><code>near ".": syntax error
</code></pre>
<p><strong>EDIT:</strong> Thanks to the below suggestion to use the subprocess module, I came up with the follwing solution.</p>
<pre><code>import subprocess
sqlshell = r'c:\sqlite-tools\sqlite3' # sqlite3.exe is a shell that can be obtained from the sqlite website
process = subprocess.Popen([sqlshell], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
cmd = """.open {db}
.seperator ","
.import {csv} {tb}""".format(db='C:/Path/to/database.db', csv='C:/Path/to/file.csv', tb='table_name')
stdout, stderr = process.communicate(input=cmd)
if len(stderr):
print 'something went wrong'
</code></pre>
<p>Importantly, you should use '/' instead of '\' in your directory names. Also, you have to be carefull with blank spaces in your directory names.</p>
|
<p>The commands you're using in <code>copy_data</code> that start with <code>.</code> are not part of <code>sqlite3</code>, but the interactive shell that it ships with it. You can't use them through the <code>sqlite3</code> module. </p>
<p>You either need to manually write the insertion step or use the <code>subprocess</code> module to run the shell program.</p>
|
python|sqlite
| 0 |
1,902,894 | 34,258,677 |
Countdown timer giving me negative numbers
|
<p>I have made a countdown timer in Python3. I have set the month to <code>1</code> and the day set to <code>10</code> just as examples. When I run it I get negative numbers because that date has already passed.</p>
<p>So then my question is how can I set the year to be something like <code>2017</code> so that instead of getting negative numbers I get something like <code>392</code> days.</p>
<p><strong>Countdown Timer</strong>
</p>
<pre><code>import time
from datetime import datetime
while True:
Datetime = datetime.now()
Month = 1 - Datetime.month
Day = 10 - Datetime.day
Hour = 24 - Datetime.hour
Minute = 60 - Datetime.minute
Second = 60 - Datetime.second
Month = str(Month) + " " + "Month"
Day = str(Day) + " " + "Day"
Hour = str(Hour) + " " + "Hour"
Minute = str(Minute) + " " + "Minute"
Second = str(Second) + " " + "Second"
print(Month)
print(Day)
print(Hour)
print(Minute)
print(Second)
time.sleep(1)
</code></pre>
|
<p>You don't need to calculate by hand. Just use the capabilities of the <code>datetime</code> module. It offers time delta calculations:</p>
<pre><code>import datetime
import time
target_date = datetime.datetime(2017, 1, 11)
timedelta_zero = datetime.timedelta(0)
while True:
diff = target_date - datetime.datetime.now()
if diff <= timedelta_zero:
break
print(diff)
time.sleep(1)
print('Takeoff!!!')
</code></pre>
<p>prints:</p>
<pre><code>393 days, 17:09:19.278093
393 days, 17:09:18.276930
393 days, 17:09:17.274710
393 days, 17:09:16.272841
393 days, 17:09:15.270777
393 days, 17:09:14.268744
393 days, 17:09:13.267112
</code></pre>
<p>If you don't like the microseconds, just strip them off:</p>
<pre><code>>>> print(str(diff).rsplit('.')[0])
393 days, 17:09:19
</code></pre>
<p>You need <code>datetime.timedelta(0)</code> as zero value for your time delta comparison.
For testing, set <code>target_date</code> to a date just a few second in the future. There should be no negative dates. </p>
|
python|python-3.x
| 2 |
1,902,895 | 66,113,115 |
Confusing python: empty list as optional kwarg in a class init
|
<p>I understand why the following happens in python, but it seems kind of counter intuitive.
Can anyone provide an explanation of why python should behave like this?
Why on the second instantiation of the class G an empty list is not created again?</p>
<pre><code>class G:
def __init__(self, members=[]):
self.members = members
def append(self, x):
self.members.append(x)
a = G()
a.append(1)
a.append(2)
print(a.members) # prints: [1, 2]
b = G()
print(b.members) # prints: [1, 2] <-------- why????
</code></pre>
<p>Edit:
As mentioned in the comment this issue has been already addressed <a href="https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument?noredirect=1&lq=1">here</a>.</p>
|
<p>Default values are evaluated during definition. So only one list is created and the default value always points to it.</p>
<pre><code>print(id(a.members))
print(id(b.members))
print(a.members is b.members)
</code></pre>
<p>output:</p>
<pre><code>140226208543200
140226208543200
True
</code></pre>
|
python
| 1 |
1,902,896 | 39,856,957 |
Why use Abstract Base Class instead of a regular class with NotImplemented methods?
|
<p>I've used ABC's in Python to enforce coding to a particular interface. However, it seems that I can achieve essentially the same thing by just creating a class whose methods are not implemented and then inheriting and overriding in actual implementations. Is there a more Pythonic reason for why ABC's were added, or was this just to make this coding pattern more prominent in the language?</p>
<p>Below is a code snippet I wrote that implements my "NotImplemented" scheme to define an abstract "optimizer" interface:</p>
<pre><code>class AbstractOptimizer(object):
'''
Abstract class for building specialized optimizer objects for each use case.
Optimizer object will need to internally track previous results and other data so that it can determine the
truth value of stopConditionMet().
The constructor will require a reference argument to the useCaseObject, which will allow the optimizer
to set itself up internally using fields from the use case as needed. There will need to be a close coupling between
the optimizer code and the use case code, so it is recommended to place the optimizer class definition in the same module
as the use case class definition.
Interface includes a constructor and four public methods with no arguments:
0) AbstractOptimizer(useCaseObject) returns an instance of the optimizer
1) getNextPoint() returns the current point to be evaluated
2) evaluatePoint(point) returns the modeling outputs "modelOutputs" evaluated at "point"
3) scorePoint(evaluationResults,metric) returns a scalar "score" for the results output by evaluatePoint according to metric. NOTE: Optimization is set up as a MINIMIZATION problem, so adjust metrics accordingly.
4) stopConditionMet(score) returns True or False based on whatever past result are needed for this decision and the current score. If score = None, it is asumed to be the start of the optimization.
5) getCurrentOptimalPoint() returns currently optimal point along with its iterationID and score
The calling workflow will typically be: getNextPoint() -> evaluatePoint() -> scorePoint -> stopConiditionMet -> repeat or stop
'''
def __init__(self, useCaseObject):
'''
useCaseObject is a reference to use case instance associated with the optimizer.
This optimizer will be "coupled" to this use case object.
'''
return NotImplemented
def stopConditionMet(self,score = None):
'''
Returns True or False based on whether the optimization should continue.
'''
return NotImplemented
def getNextPoint(self):
'''
If stopConditionMet() evaluates to False, then getNextPoint() should return a point; otherwise, it should return None
'''
return NotImplemented
def evaluatePoint(self,point):
'''
Returns the modeling outputs "modelOutputs" evaluated at the current point.
Will utilize the linked
'''
return NotImplemented
def scorePoint(self,evaluationResults,metric):
'''
Returns a scalar "score" for the current results evaluated in at the current point (from evaluatePoint) based on the function "metric"
Note that "metric" will likely need to be a closure with the evaluation results as bound objects.
'''
return NotImplemented
def getCurrentOptimum(self):
'''
returns currently optimal point and it's score as a dictionary: optimalPoint = {"point":point,"score":score}
'''
return NotImplemented
</code></pre>
|
<p><a href="https://www.python.org/dev/peps/pep-3119/" rel="nofollow noreferrer">PEP 3119</a> discusses the rational behind all of this</p>
<blockquote>
<p>...In addition, the ABCs define a minimal set of methods that establish the characteristic behavior of the type. Code that discriminates objects based on their ABC type can trust that those methods will always be present. Each of these methods are accompanied by an generalized abstract semantic definition that is described in the documentation for the ABC. These standard semantic definitions are not enforced, but are strongly recommended..</p>
</blockquote>
<p>This above statement appears to be a key piece of information. An <code>AbstractBaseClass</code> provides guarantees that cannot be guaranteed by a standard <code>object</code>. These guarantees are paramount to paradigms in OOP style development. Particularly <strong>inspection</strong>:</p>
<blockquote>
<p>On the other hand, one of the criticisms of inspection by classic OOP theorists is the lack of formalisms and the ad hoc nature of what is being inspected. In a language such as Python, in which almost any aspect of an object can be reflected and directly accessed by external code, there are many different ways to test whether an object conforms to a particular protocol or not. For example, if asking 'is this object a mutable sequence container?', one can look for a base class of 'list', or one can look for a method named '<strong>getitem</strong>'. But note that although these tests may seem obvious, neither of them are correct, as one generates false negatives, and the other false positives.</p>
<p>The generally agreed-upon remedy is to standardize the tests, and group them into a formal arrangement. This is most easily done by associating with each class a set of standard testable properties, either via the inheritance mechanism or some other means. Each test carries with it a set of promises: it contains a promise about the general behavior of the class, and a promise as to what other class methods will be available.</p>
<p>This PEP proposes a particular strategy for organizing these tests known as Abstract Base Classes, or ABC. ABCs are simply Python classes that are added into an object's inheritance tree to signal certain features of that object to an external inspector. Tests are done using isinstance() , and the presence of a particular ABC means that the test has passed.</p>
</blockquote>
<p>So while yes you can use an object and mimic the behavior of an ABCMeta class, the point of the ABC meta class it reduce boilerplate, false positives, false negatives, and provide guarantees about the code that otherwise would not be possible to guarantee without heavy lifting by you, the developer.</p>
|
python-2.7|oop|abstract-class
| 0 |
1,902,897 | 38,532,778 |
Python/Matlab - Taking rank of matrix in quad precision or more
|
<p>I have a 14x14 matrix of which I'm trying to take the rank. The problem is that it has a high condition number so using double precision my matrix is not full rank. I know that it should be, so I'm trying to take the rank in higher precision. </p>
<p>So far I have installed the bigfloat package in python, but have been unsuccessful in trying to get the rank in higher precision. I have also scaled my matrix, I tried python's jacobi preconditioner and some other scaling methods but it was not sufficient.</p>
<p>I'm not trying to solve a system of linear equations, I just need to verify that all my columns are linearly independent. In other words, I want to verify that a (simplified) matrix such as the one shown is of rank 2, not 1. </p>
<pre><code>[1, 0;
0, 1e-20]
</code></pre>
<p>Any Suggestions?</p>
|
<p>If you're working with ill-conditioned matrices, it's just hard to tell the rank of your matrix. The <code>1.0e-20</code> in your example might perhaps just be a round-off error in actual computation.</p>
<p>In numpy, the rank is checked by looking at the SVD and counting the number of "zero" eigenvalues, where "zero" is with some tolerance. Depending on what you set here, you get different results:</p>
<pre class="lang-py prettyprint-override"><code>import numpy
a = numpy.array([[1, 0], [0, 1e-20]])
rank = numpy.linalg.matrix_rank(a, tol=1.0e-10)
print(rank)
rank = numpy.linalg.matrix_rank(a, tol=1.0e-30)
print(rank)
</code></pre>
<pre><code>1
2
</code></pre>
|
python|matrix|precision|rank
| 0 |
1,902,898 | 68,137,562 |
accuracy for 1D CNN model is very low
|
<p>I tried to build 1D CNN model to DNA mutation classification I built the model and it works correctly but I get test data with low accuracy I have dataset like the picture bellow<img src="https://i.stack.imgur.com/JsBg9.png" alt="1" /></p>
<p>and this is my model</p>
<pre><code>vocab_size = 100
embedding_dim = 150
max_len = 90
X_train = pad_sequences(X_train,padding ='post', maxlen = max_len)
X_test = pad_sequences(X_test,padding ='post', maxlen = max_len)
model = Sequential()
model.add(layers.Embedding(vocab_size,embedding_dim,input_length = max_len))
model.add(layers.Conv1D(128, 7, activation = 'relu'))
model.add(layers.GlobalMaxPooling1D())
model.add(layers.Dense(10, activation = 'relu'))
model.add(layers.Dense(1, activation = 'sigmoid'))
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics= ['accuracy'])
model.summary()
history = model.fit(X_train,y_train,epochs = 10, verbose = False,validation_data = (X_test,y_test),batch_size = 10)
loss,accuracy = model.evaluate(X_train,y_train, verbose = False)
accuracy = accuracy*100
print("training accuracy = {:.2f}".format(accuracy))
loss,accuracy = model.evaluate(X_test,y_test, verbose = False)
accuracy = accuracy*100
print("test accuracy = {:.2f}".format(accuracy))
</code></pre>
<p>my input is ['sequence','normal','mutated','position']
and target column is ['class'] column
so what is the problem with my test accuracy.</p>
<p><strong>Edit:</strong>
I tried to change percent of test data in train_test_split function and increased percent of test data to avoid overfitting but test accuracy still low</p>
|
<p>There are several methods that you can employ to generalize your model and improve test accuracy:</p>
<p>1- check to see if your datasets are unbalanced or not. unbalancing datasets means that the size of data in each class has substantially different.</p>
<p>2- you can use the data/image augmentation technique to increase the size of datasets or balance classes size.</p>
<p>3- Doing Hyperparameter optimization, change optimizer types, batch_size, learning rate and other hyperparameters to find the optimum ones.</p>
<p>4- in some cases using other functions for loss and accuracy can be helpful.</p>
|
python|tensorflow|machine-learning|keras|conv-neural-network
| 1 |
1,902,899 | 1,735,240 |
Set Django model field with a method
|
<p>I'm trying to set <code>title_for_url</code> but it shows up in my database as "<code><property object at 0x027427E0></code>". What am I doing wrong?</p>
<pre><code>from django.db import models
class Entry(models.Model):
def _get_title_for_url(self):
title = "%s" % self.get_title_in_url_format()
return title
AUTHOR_CHOICES = (('001', 'John Doe'),)
post_date = models.DateField()
author = models.CharField(max_length=3, choices=AUTHOR_CHOICES)
title = models.CharField(max_length=100, unique=True)
body = models.TextField()
image = models.ImageField(upload_to='image/blog')
image.blank = 'true'
title_for_url = models.CharField(max_length=100, editable=False, default=property(_get_title_for_url))
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/blog/%s/" % self.get_title_in_url_format()
def get_title_in_url_format(self):
"Returns the title as it will be displayed as a URL, stripped of special characters with spaces replaced by '-'."
import re
pattern = re.compile( '(\'|\(|\)|,)' )
titleForUrl = pattern.sub('', self.title)
pattern = re.compile( '( )' )
titleForUrl = pattern.sub('-', titleForUrl)
return titleForUrl.lower()
</code></pre>
|
<pre><code>title_for_url = models.CharField(max_length=100, editable=False, default=property(_get_title_for_url)
</code></pre>
<p>You couldn't do that way.. 'default' should be a value or a calable(with no args)... (property <strong>is not</strong> calable)</p>
<p>In your case you need to update a save method:</p>
<pre><code>class Entry(models.Model):
def save(self, *args, **kwargs):
self.title_for_url = self.get_title_in_url_format()
super(Entry, self).save(*args, **kwargs)
</code></pre>
|
python|django
| 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.