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,300 | 68,992,837 |
Add prefix and reset index in pyspark dataframe
|
<p>Here's what I usually do in pandas</p>
<pre><code>cdr = datamonthly.pivot(index="msisdn", columns="last_x_month", values="arpu_sum").add_prefix('arpu_sum_l').reset_index()
</code></pre>
<p>But what I did in Pyspark</p>
<pre><code>cdr = datamonthly.groupBy("msisdn").pivot("last_x_month").sum("arpu_sum")
</code></pre>
<p>I cant find alternative for add_prefix('arpu_sum_l').reset_index()</p>
|
<p>There is nothing similar to pandas' <code>add_prefix</code> in spark when doing pivot. But, you can try a workaround like creating a column from concatenation of the custom prefix string and the value of the column to be pivoted.</p>
<pre><code>import pyspark.sql.functions as F
cdr = datamonthly.withColumn("p", F.expr("concat('arpu_sum_l_', last_x_month)")).groupBy("msisdn").pivot("p").sum("arpu_sum")
</code></pre>
|
python|pandas|pyspark
| 2 |
1,902,301 | 62,252,118 |
Deepcopy on two classes containing eachother gives recursion error. Python
|
<p>When I have a object-structure like this:</p>
<pre><code>from copy import deepcopy
class A:
def __init__(self, b):
self.b = b
def __deepcopy__(self, memodict):
return A(deepcopy(self.b, memodict))
class B:
def __init__(self, a):
self.a = a
def __deepcopy__(self, memodict):
return B(deepcopy(self.a, memodict))
test_a = A(None)
test_b = B(None)
test_a.b = test_b
test_b.a = test_a
copy_a = deepcopy(test_a)
</code></pre>
<p>And I try to make a deepcopy of a object I get a "maximum recursion depth exceeded" error.
Which I understand why this happens but I don't know what the best approach would be to solve this?</p>
<p>Help much appreciated</p>
|
<p>You should not override <code>__deepcopy__</code>, just let deepcopy function do its work.
By the way I had to remove annotation <code>:B</code> because its a foreward reference and gives name error.</p>
<pre><code>from copy import deepcopy
class A:
def __init__(self, b):
self.b = b
class B:
def __init__(self, a):
self.a = a
a = A(None)
b = B(None)
a.b = b
b.a = a
aa = deepcopy(a)
print (aa is a) # -> False
print(aa.b is b) # -> False
print(aa.b.a is aa) # -> True
</code></pre>
<p>But if you for any reason want to override the <code>__deepcopy__</code> you should do it like this:</p>
<pre><code>from copy import deepcopy
class A:
def __init__(self, b):
self.b = b
def __deepcopy__(self, memodict):
a = A(None)
memodict[id(self)] = a
a.b = deepcopy(self.b, memodict)
return a
class B:
def __init__(self, a: A):
self.a = a
def __deepcopy__(self, memodict):
b = B(None)
memodict[id(self)] = b
b.a = deepcopy(self.a, memodict)
return b
a = A(None)
b = B(None)
a.b = b
b.a = a
aa = deepcopy(a)
print(aa is a) # -> False
print(aa.b is b) # -> False
print(aa.b.a is aa) # -> True
</code></pre>
<p>ref: <a href="https://stackoverflow.com/a/15774013/1951448">https://stackoverflow.com/a/15774013/1951448</a></p>
|
python|python-3.x|recursion|deep-copy
| 1 |
1,902,302 | 67,220,320 |
Sum of all rows in specific column
|
<p>I am trying to generate the sum of all rows in a specific column in pandas. I am doing the project using a jupyterhub notebook.</p>
<p>The following code below generates a full list with the value in each row and not the total of all rows. Curious to know what I am doing wrong?</p>
<pre><code>ria_aum_total = ria_aum['5F(2)(a)'].sum()
print(ria_aum_total)
</code></pre>
|
<p>According to Pandas documentation you have to use Pandas Dataframe. Here is the example given in the documentation you have to cast the data to Dataframe and then you can use the .sum of the DataFrame datastructure.</p>
<p>Here is the example from the documentation (<a href="https://www.javatpoint.com/pandas-sum" rel="nofollow noreferrer">https://www.javatpoint.com/pandas-sum</a>):</p>
<pre><code>import pandas as pd
info = {'Name': ['Parker', 'Smith', 'William'], 'age' : [32, 28, 39]}
data = pd.DataFrame(info)
data['total'] = data['age'].sum()
print(data)
</code></pre>
|
python|pandas
| 0 |
1,902,303 | 13,311,732 |
Efficiency of calling C function from Python
|
<p>I wrote a python script to do some experiment with the Mandelbrot set. I used a simple function to find Mandelbrot set points. I was wondering how much efficiency I can achieve by calling a simple C function to do this part of my code? Please consider that this function should call many times from Python.</p>
<p>What is the effect of run time? And maybe other factors that should I aware?</p>
|
<p>You'll want the python calls to your C function to be as little as possible. If you can call the C function once from python and get it to do most/all of the work, that would be better.</p>
|
python|c|performance
| 1 |
1,902,304 | 21,965,716 |
Is the test condition computed each time through a loop in Python?
|
<pre><code># returns sum of individual digits in n (incorrect implementation)
def digit_sum(n):
running_sum = 0
count = 0
while count < len(str(n)):
rightmost = n % 10 # value of right-most digit
running_sum += rightmost
n = n // 10 # strip right-most digit
count += 1
return running_sum
</code></pre>
<p>Is the value of <code>len(str(n))</code> computed every time the condition is checked through each iteration of the <code>while</code> loop, or is <code>len(str(n))</code> evaluated the first time and stored some place to optimize execution?</p>
<p>In contrast to the following loop:</p>
<pre><code># returns sum of individual digits in n (correct implementation)
def digit_sum(n):
running_sum = 0
for _ in xrange(len(str(n))):
rightmost = n % 10 # value of right-most digit
running_sum += rightmost
n = n // 10 # strip right-most digit
return running_sum
</code></pre>
|
<p>It's computed every time. Python doesn't know that <code>str(n)</code> will always return the same thing every time. At compile time, for all it knows, this function might be called with an instance of</p>
<pre><code>class IAmABadPersonWhoWantsPeopleToHaveABadTime(int):
def __str__(self):
if random.random() < 0.1:
raise SyntaxError
return super(IAmABadPersonWhoWantsPeopleToHaveABadTime, self).__str__()
</code></pre>
<p>and the program's correctness might rely on that 10% chance of a SyntaxError.</p>
<p>Also, don't compare numbers to <code>range</code> return values. That's definitely not doing what you want. A <code>for</code> loop is closer to what you wanted:</p>
<pre><code>for _ in xrange(len(str(n))):
</code></pre>
<p>though it'd be simpler to use a <code>while</code>:</p>
<pre><code>while n:
</code></pre>
<p>which keeps going as long as <code>n != 0</code>.</p>
|
python|compiler-construction
| 2 |
1,902,305 | 16,614,757 |
wxpython TextCtrl color specific part of the text
|
<p>I'm using wxpython to create GUI with python, now, is there a way to color specific part of the text?</p>
<p>Example (using Tkinter):</p>
<p><a href="http://i.stack.imgur.com/fGAVA.png" rel="nofollow">http://i.stack.imgur.com/fGAVA.png</a></p>
<p>Here is my Print function:</p>
<pre><code>def Print(self, String):
''' Print Received Data '''
self.text_serverLog.AppendText(datetime.now().strftime("[%H:%M:%S] " + String + "\n"))
</code></pre>
<p>I found the function <code>SetForegroundColour</code> but sadly its color the whole <code>TextCtrl</code>.</p>
<p>I'm using Win7, python 2.7, wxpython.
Thanks.</p>
|
<p>You can use the wx.TextCtrl in RichText mode by setting its style flag to wx.TE_RICH or wx.TE_RICH2. You can also use the aforementioned RichTextCtrl or the StyledTextCtrl (1 or 2). There's also FancyText, but I think that's more of a helper for drawing text than a real control the user can edit. Regardless, all of these widgets have examples in the wxPython demo package, which you can find at the wxPython website's download page.</p>
|
python|user-interface|wxpython|textctrl|wxtextctrl
| 1 |
1,902,306 | 54,405,458 |
OSError: [WinError 193] %1 is not a valid Win32 application while automating through Selenium ChromeDriver and Chrome in Python
|
<p>Code block:</p>
<pre><code>import time
from selenium import webdriver
browser = webdriver.Chrome('C:/Users/Cypher/Downloads/chromedriver_win32.zip')
browser.maximize_window()
browser.get('https://www.google.com/gmail/')
email_field = browser.find_element_by_id('identifierId')
email_field.clear()
email_field.send_keys('My mail')
email_next_button = browser.find_element_by_id('identifierNext')
email_next_button.click()
time.sleep(1)
password_field = browser.find_element_by_name('password')
password_field.clear()
password_field.send_keys('My password')
password_next_button = browser.find_element_by_id('passwordNext')
password_next_button.click()
time.sleep(100)
browser.quit()
</code></pre>
<p>Error:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Cypher/PycharmProjects/untitled5/login_gmail.py", line 4, in <module>
driver = webdriver.Chrome('C:/Users/Cypher/Downloads/chromedriver_win32.zip')
File "C:\Users\Cypher\PycharmProjects\untitled5\venv\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
self.service.start()
File "C:\Users\Cypher\PycharmProjects\untitled5\venv\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start
stdin=PIPE)
File "C:\Users\Cypher\Miniconda3\lib\subprocess.py", line 756, in __init__
restore_signals, start_new_session)
File "C:\Users\Cypher\Miniconda3\lib\subprocess.py", line 1155, in _execute_child
startupinfo)
OSError: [WinError 193] %1 is not a valid Win32 application
</code></pre>
|
<p>Just extract the chromedriver you have downloaded... <code>chromedriver_win32.zip</code> make sure you have the <code>chromedriver.exe</code> file in the downloads...</p>
<pre><code>browser = webdriver.Chrome('C:/Users/Cypher/Downloads/chromedriver.exe')
</code></pre>
<p>Hope this helps you!</p>
|
python|selenium|google-chrome|selenium-webdriver|selenium-chromedriver
| 1 |
1,902,307 | 9,292,169 |
python pyqt4 combobox
|
<p>I am working with python plugins.I designed my form using pyqt4 designer.It has one combobox.
I coded in python as follows:</p>
<pre><code>self.db._exec_sql(c, "SELECT "+column_name1+" from "+table_name+" ")
for row in c.fetchall():
print row
self.comboBox.addItem(row)
</code></pre>
<p><strong>row</strong> gives me all the values of specific column of specific table. I am listing all column values from database into combobox.But <strong>self.comboBox.addItem(row)</strong> gives error saying :</p>
<pre><code>TypeError: arguments did not match any overloaded call:
QComboBox.addItem(QString, QVariant userData=QVariant()): argument 1 has unexp
ected type 'tuple'
QComboBox.addItem(QIcon, QString, QVariant userData=QVariant()): argument 1 ha
s unexpected type 'tuple'
</code></pre>
<p>How do i list values in combobox??</p>
|
<p><code>fetchall()</code> method yields tuples, even when you select only one value in the SQL <code>SELECT</code> clause. Change your code to:</p>
<pre><code>for row in c.fetchall():
self.comboBox.addItem(row[0])
</code></pre>
|
python|pyqt
| 5 |
1,902,308 | 9,325,292 |
How do I convert this SQL to Django QuerySet?
|
<p>I have this SQL</p>
<pre><code>select product_id, date_booked, sum(quantity) from booking_hotelcheck where client_id=1 and status='Complete'
group by product_id, date_booked
</code></pre>
<p>and it returns :<br>
<img src="https://i.stack.imgur.com/hRu9V.png" alt="enter image description here"></p>
<p>and i try to convert it to django queryset:</p>
<pre><code>>>> HotelCheck.objects.filter(client=1,status='Complete').values('product','date_booked','quantity').aggregate(Sum('quantity'))
{}
>>>
</code></pre>
<p>but it returns an empty set...</p>
<p>is my django queryset didn't convert my SQL?
can anyone can give me an idea on how can I convert my SQL to django queryset?</p>
<p>thanks in advance...</p>
|
<pre><code>HotelCheck.objects.filter(client=1, status='Complete').values('product','date_booked').annotate(Sum('quantity'))
</code></pre>
|
python|sql|django|django-queryset
| 4 |
1,902,309 | 9,217,367 |
What is a good practice/design to thread mulitple SQL queries in Python
|
<p>I am extracting information from a website and storing it to a database using Python with <a href="http://mysql-python.sourceforge.net/MySQLdb.html" rel="nofollow">MySQLdb</a> and <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>.</p>
<p>The website is organized by about 15 different cities and each city has anywhere from 10 to 150 pages. There is a total of about 500 pages.</p>
<p>For each page per city, I open the site using BeautifulSoup, extract all the neccessary information then perform a <code>insert into</code> or <code>update</code> SQL query.</p>
<p>Currently I am not using threads, and it takes a few minutes to go through all 500 pages because the Python program...</p>
<ol>
<li>Open a page.</li>
<li>Extract information.</li>
<li>Perform SQL query.</li>
<li>Open the next page...</li>
</ol>
<p>Ideally I would want to <em>load balance</em> the thread by having, say, 10 concurrent threads that open up about 50 pages each. But I think that may be too complicated to code.</p>
<p>So instead I am thinking of having one thread per city. How would I accomplish this?</p>
<p>Currently my code looks like something like this:</p>
<pre><code>//import threading
import BeautifulSoup
import urllib2
import MySQLdb
con = MySQLdb.connect( ... )
def open_page( url ):
cur = con.cursor()
// do SQL query
//Get a dictionary of city URL
cities = [
'http://example.com/atlanta/',
'http://example.com/los-angeles/',
...
'http://example.com/new-york/'
]
for city_url in cities:
soup = BeautifulSoup( urllib2.urlopen( city_url ) )
// find every page per city
pages = soup.findAll( 'div', { 'class' : 'page' } )
for page in pages:
page_url = page.find( 'a' )[ 'href' ]
open_page( page_url )
</code></pre>
|
<p>Your initial idea is absolutely feasible. Just start 10 worker threads that wait for input on one and the same queue. Then your mail process puts the urls into this queue. The load-balancing will happen automatically.</p>
<p>If your SQL bindings are thread-safe, you can do the INSERT or UPDATE stuff in the worker threads. Otherwise, I'd add one more thread for the SQL stuff, waiting for input on a different queue. Then your worker threads would put the query into this queue, and the SQL thread would execute it.</p>
<p>If you google for "python worker threads queue" you'll find a few examples.</p>
|
python|mysql|multithreading
| 1 |
1,902,310 | 39,281,956 |
Remove columns where all items in column are identical (excluding header) and match a specified string
|
<p>My question is an extension of <a href="https://stackoverflow.com/questions/21164910/delete-column-in-pandas-based-on-condition">Delete Column in Pandas based on Condition</a>, but I have headers and the information isn't binary. Instead of removing a column containing all zeros, I'd like to be able to pass a variable "search_var" (containing a string) to filter out columns containing only that string.</p>
<p>I initially thought I should read in the df and iterate across each column, read each column in as a list, and print columns where len(col_list) > 2 and search_var not in col_list. The solution provided to the previous post involving a boolean dataframe (df != search_var) intrigued me there might be a simpler way, but how could I go around the issue that the header will not match and therefore cannot purely filter on True/False?</p>
<p>What I have (non-working):</p>
<pre><code>import pandas as pd
df = pd.read_table('input.tsv', dtype=str)
with open('output.tsv', 'aw') as ofh:
df['col_list'] = list(df.values)
if len(col_list) < 3 and search_var not in col_list:
df.to_csv(ofh, sep='\t', encoding='utf-8', header=False)
</code></pre>
<h1>Example input, search_var = 'red'</h1>
<pre><code>Name Header1 Header2 Header3
name1 red red red
name2 red orange red
name3 red yellow red
name4 red green red
name5 red blue blue
</code></pre>
<h1>Expected Output</h1>
<pre><code>Name Header2 Header3
name1 red red
name2 orange red
name3 yellow red
name4 green red
name5 blue blue
</code></pre>
|
<p>You can check the number of <code>non-red</code> item in the column, if it is not zero then select it using <code>loc</code>:</p>
<pre><code>df.loc[:, (df != 'red').sum() != 0]
# Name Header2 Header3
# 0 name1 red red
# 1 name2 orange red
# 2 name3 yellow red
# 3 name4 green red
# 4 name5 blue blue
</code></pre>
|
python|pandas
| 2 |
1,902,311 | 39,034,681 |
Changing Odoo 9 "login title"
|
<p>I was following this post <a href="https://stackoverflow.com/questions/26974431/odoo-8-how-to-change-page-title/29182681#29182681">Odoo 8 - how to change page title?</a> on how to change Odoo 9 login title . I believe I followed the steps and also restarted the server, but the title didn't change. Any suggestions?</p>
<p>Here are steps I followed:</p>
<ol>
<li><p>I created a new folder/module called brin in addons folder</p></li>
<li><p>Created a new xml file(with new title) in that folder that looks like this</p></li>
</ol>
<p><a href="https://i.stack.imgur.com/f18P8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f18P8.png" alt="brin.xml"></a></p>
<ol start="3">
<li>Created an <strong>openerp</strong>.py file in that folder and declared the xml file that looks like this:</li>
</ol>
<p><a href="https://i.stack.imgur.com/NYtoM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NYtoM.png" alt="__openerp__.py file"></a></p>
|
<p>So i figured found a way to do it.</p>
<p>1.Click the drop down menu on administrator(In the upper right corner).</p>
<p>2.Click the "about" link and activate developer mode.</p>
<p>3.Now go to settings,User interface,Views.Type "layout" in search bar.A set of layouts is brought.Click on Web layout.Click edit.In the xml change the title to custom title.</p>
<p>4.Walaaaa !!</p>
|
python|odoo-9
| 0 |
1,902,312 | 52,829,350 |
How to add select in Django Admin?
|
<p>How can I add a a select field type in Django admin page of a table.
How does it store in Database.</p>
|
<p>You can add choices to a charField Type. </p>
<p>ref: <a href="https://docs.djangoproject.com/en/2.1/ref/models/fields/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/2.1/ref/models/fields/</a></p>
|
python|django
| 0 |
1,902,313 | 47,949,267 |
wrapping scipy.interpolate.interp1d into a function
|
<p>am struggling to wrap scipy.interpolate.interp1d into a function.
My input pd.df:</p>
<pre><code>In [108]: rates.tail()
Out[108]:
28 91 182 364
Date
2017-12-18 0.0125 0.0138 0.0151 0.0169
2017-12-19 0.0125 0.0137 0.0151 0.0170
2017-12-20 0.0122 0.0138 0.0151 0.0171
2017-12-21 0.0120 0.0135 0.0154 0.0172
2017-12-22 0.0114 0.0133 0.0154 0.0172
</code></pre>
<p>This works but need to wrap it into a function with <code>date</code> as an argument:</p>
<pre><code>x = np.array(rates.columns[0:4])
y = np.array(rates.loc[date])
f = interp1d(x, y, kind='cubic', fill_value='extrapolate')
</code></pre>
<p>Grateful for any help!</p>
|
<p>It seems that the function should take the date and a numeric value (called t below). So it could be this: </p>
<pre><code>def interpolated(t, date):
x = np.array(rates.columns[0:4])
y = np.array(rates.loc[date])
f = interp1d(x, y, kind='cubic', fill_value='extrapolate')
return f(t)
</code></pre>
<p>(One can also pass in <code>rates</code> if it's preferable to treat is as a parameter instead of taking it from global scope).</p>
|
scipy|python-3.6
| 1 |
1,902,314 | 34,196,006 |
Modify fibonacci python in order to print f(0),f(1),.....f(n)
|
<p>Here is my original function.</p>
<pre><code>def f(n):
if n<0:
print("Error.Bad input")
elif n==0:
return 1
elif n==1:
return 1
else:
return f(n-1)+f(n-2)
</code></pre>
<p>Is it possible to modify Fibonacci Python function so that not only does it have to calculate f(n) but also it prints f(0), f(1), f(2),....,f(n) in the function?</p>
|
<p>Bottom-up approach. Complexity is O(n):</p>
<pre class="lang-py prettyprint-override"><code>def fib(n):
if n in (1, 2):
return 1
i = z = 1
for _ in range(3, n+1):
z, i = i + z, z
return z
</code></pre>
|
python-2.7|fibonacci
| 0 |
1,902,315 | 34,111,158 |
Canvas Class Constructor Function
|
<p>I am working on an assignment involving classes. I have completed the two other class that have been asked of us: Point, and Rectangle. I am currently working on the canvas class and I am not sure what to put in its constructor. The purpose of the canvas is to store rectangles that you have added to the canvas and compare them through multiple functions.</p>
<p>My question is, how do i create a constructor for this class if there is nothing originally in it</p>
|
<p>Just make the constructor initialize the class instance's internal container of objects (Points and Rectangles in this case) to an empty state. Presumably the class will have one or more methods defined to add such objects to it later, after it's created. </p>
<p>That's basically how the <a href="http://effbot.org/tkinterbook/canvas.htm" rel="nofollow"><code>Tkinter.Canvas</code></a> works. Its constructor accepts a large number of keyword option arguments that define other attributes of the widget, such as its background color, height and width, etc (as detailed in <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/canvas.html" rel="nofollow">this</a> reference).</p>
|
python|class|oop|canvas
| 0 |
1,902,316 | 66,059,223 |
Update particular values in a pandas dataframe from another dataframe
|
<p>I have a dataframe consisting of a chat transcript:</p>
<pre><code>id time author text
a1 06:15:19 system aaaaa
a1 13:57:50 Agent(Human) ssfsd
a1 14:00:05 customer ddg
a1 14:06:08 Agent(Human) sdfg
a1 14:08:54 customer sdfg
a1 15:58:48 Agent(Human) jfghdfg
a1 16:18:41 customer urtr
a1 16:51:38 Agent(Human) erweg
</code></pre>
<p>I also have another dataframe of agents containing what time they initiated the chat.
For eg: df2</p>
<pre><code>id agent_id agent_time
a1 D01 13:57:50
a1 D02 15:58:48
</code></pre>
<p>Now, I'm looking to update the values in 'author' column with the values in 'agent_id' based on that particular time, and also filling the in between values of author containing "Agent(Human)" with their respective agent name.</p>
<p>Final output desired:</p>
<pre><code>id time author text
a1 06:15:19 system aaaaa
a1 13:57:50 D01 ssfsd
a1 14:00:05 customer ddg
a1 14:06:08 D01 sdfg
a1 14:08:54 customer sdfg
a1 15:58:48 D02 jfghdfg
a1 16:18:41 customer urtr
a1 16:51:38 D02 erweg
</code></pre>
<p>I tried to do it using .map() operation</p>
<pre><code>df1['author'] = df1['time'].map(df2.set_index('agent_time')['agent_id'])
</code></pre>
<p>But I'm getting a wrong output:</p>
<pre><code>id time author text
a1 06:15:19 NaN aaaaa
a1 13:57:50 D01 ssfsd
a1 14:00:05 NaN ddg
a1 14:06:08 NaN sdfg
a1 14:08:54 NaN sdfg
a1 15:58:48 D02 jfghdfg
a1 16:18:41 NaN urtr
a1 16:51:38 NaN erweg
</code></pre>
<p>I tried using .loc method too but didn't work</p>
<p>Can anyone guide me on how to achieve the desired output? Any leads will be helpful</p>
|
<p>I think in your solution should be added <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.ffill.html" rel="nofollow noreferrer"><code>GroupBy.ffill</code></a> for forward missing values per <code>id</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html" rel="nofollow noreferrer"><code>Series.where</code></a> for repalce non matched <code>Agent(Human)</code> to original values of <code>Author</code>:</p>
<pre><code>m = df1['author'].eq('Agent(Human)')
df1['author'] = (df1['time'].map(df2.set_index('agent_time')['agent_id'])
.groupby(df1['id'])
.ffill()
.where(m, df1['author']))
print (df1)
id time author text
0 a1 06:15:19 system aaaaa
1 a1 13:57:50 D01 ssfsd
2 a1 14:00:05 customer ddg
3 a1 14:06:08 D01 sdfg
4 a1 14:08:54 customer sdfg
5 a1 15:58:48 D02 jfghdfg
6 a1 16:18:41 customer urtr
7 a1 16:51:38 D02 erweg
</code></pre>
|
python|pandas
| 1 |
1,902,317 | 16,450,683 |
ProtoRPC App Engine Hello World test app not working
|
<p>I have been trying to get the rather simple Hello World ProtoRPC App Engine example to work, but to no avail. The code from the website just doesn't seem to work unfortunately. I have looked at a number of possible solutions, but couldn't find a complete working set. Any help would be much appreciated! You can see the error (or lack thereof) below:</p>
<p><strong>app.yaml</strong></p>
<pre><code>application: proto-test
version: 1
runtime: python27
api_version: 1
threadsafe: false
handlers:
- url: /hello.*
script: hello.py
</code></pre>
<p><strong>hello.py</strong></p>
<pre><code>from protorpc import messages
from protorpc import remote
from protorpc.wsgi import service
package = 'hello'
# Create the request string containing the user's name
class HelloRequest(messages.Message):
my_name = messages.StringField(1, required=True)
# Create the response string
class HelloResponse(messages.Message):
hello = messages.StringField(1, required=True)
# Create the RPC service to exchange messages
class HelloService(remote.Service):
@remote.method(HelloRequest, HelloResponse)
def hello(self, request):
return HelloResponse(hello='Hello there, %s!' % request.my_name)
# Map the RPC service and path (/hello)
app = service.service_mappings([('/hello', HelloService)])
</code></pre>
<p><strong>curl command</strong></p>
<pre><code>curl -H 'content-type:application/json' -d '{"my_name":"test1"}' http://proto-test.appspot.com/hello.hello
</code></pre>
<p>When I run the above command in the command line, it just returns the prompt without an error. My logs suggest that the curl command sort of worked, but it just didn't provide a response. This is what appears in the logs:</p>
<pre><code>2013-05-08 22:27:07.409 /hello.hello 200 522ms 0kb curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
2620:0:10c8:1007:a800:1ff:fe00:33af - - [08/May/2013:14:27:07 -0700] "POST /hello.hello HTTP/1.1" 200 0 - "curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3" "proto-test.appspot.com" ms=523 cpu_ms=133 loading_request=1 app_engine_release=1.8.0 instance=00c61b117c66197ad84ad9bc61485b292e5129
I 2013-05-08 22:27:07.409
This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. This request may thus take longer and use more CPU than a typical request for your application.
</code></pre>
<p>An Ajax call through the Chrome JS Console returned the following: <strong>SyntaxError: Unexpected token ILLEGAL</strong>:</p>
<pre><code>$.ajax({url: ‘/hello.hello’, type: 'POST', contentType: 'application/json', data: ‘{ "my_name": "Bob" }’,dataType: 'json',success: function(response){alert(response.hello);}});
</code></pre>
|
<p>The Java script you posted seems to have syntax errors. Mainly, it looks like you are using the ` character in places instead of the ' character.</p>
<p>The reason why your request is not working is because of how you wrote the app.yaml file. You are using the old Python 2.5 way of calling applications by referring to a script rather than a WSGI application. You can correct it by changing the url handler in app.yaml to:</p>
<p>handlers:
- url: /hello.*
script: hello.app</p>
|
python|google-app-engine|protorpc
| 1 |
1,902,318 | 16,109,085 |
Plot two vectors for elements which exist - i.e. skip rows without entries
|
<p>Two vectors:</p>
<pre><code>A = ['1','2','3','4','5','6','','6','7','8','','1','2','3','','']
B = ['2','3','4','','5','','','6','','7','8','9','1','4']
</code></pre>
<p>How do I only plot A vs B for values which have two existing elements? At the moment, I have to loop over each vector and check int() is > 0 at the same row.</p>
|
<p>If you put <code>None</code> in the empty spaces then you can join the two vectors and remove the pairs with missing values like this:</p>
<pre><code>>>> A = [1,2,3,4,5,6,None,6,7,8,None,1,2,3,None,None]
>>> B = [2,3,4,None,5,None,None,6,None,7, 8,9,1,4]
>>> filter(lambda (a,b): a is not None and b is not None, map(lambda a,b: (a,b), A,B))
[(1, 2), (2, 3), (3, 4), (5, 5), (6, 6), (8, 7), (1, 9), (2, 1), (3, 4)]
</code></pre>
<p>then you can use the result for plotting.</p>
<p>Answering your question in comments, if you use Python's CSV module then it will properly parse that CSV with empty spaces and parse the empty spaces as empty strings:</p>
<pre><code>$ cat t.csv
1,2,,4
1,,3,,
$ python
Python 2.7.1 (r271:86832, Mar 18 2011, 09:09:48)
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> with open('t.csv') as f:
... reader = csv.reader(f)
... for row in reader:
... print row
...
['1', '2', '', '4']
['1', '', '3', '', '']
>>>
</code></pre>
|
python|arrays
| 1 |
1,902,319 | 38,527,053 |
Missing values at the beginning - matplotlib
|
<p>Trying to add missing values (None) or in <code>numpy</code> <code>np.nan</code> to my matplot graph. Normally it is possible to have missing values in this way:</p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure(1)
x = range(10)
y = [1, 2, None, 0, 1, 2, 3, 3, 5, 10]
ax = fig.add_subplot(111)
ax.plot(x, y, 'ro')
plt.show()
</code></pre>
<p>But looks like missing values aren't easily supported at the beginning of the graph. </p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure(1)
x = range(10)
y = ([None]*5)+[x for x in range(5)]
ax = fig.add_subplot(111)
ax.plot(x, y, 'ro')
plt.show()
</code></pre>
<p>This displays:</p>
<p><a href="https://i.stack.imgur.com/4L6xI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4L6xI.png" alt=""></a></p>
<p>But I would like to start with <code>x=0</code> instead of <code>x=5</code>.
Hope there is a simple method for this problem.</p>
|
<p>The reason why the empty values don't seem to have an effect on the second plot is because of the automatic determination of the x and y limits of the axes object. In the first case, you have "real" data that spans the whole x / y range you care about and the axes is automatically scaled to fit this data. In the second example, your real data only covers the upper range of x values so matplotlib will truncate the x axis because there is nothing to show.</p>
<p>The way around this is to explicitly specify the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xlim" rel="nofollow">xlims</a> of the axes. You can use your value for <code>x</code> to determine what these should be. </p>
<pre><code>plt.xlim(x[0], x[-1])
</code></pre>
|
python|matplotlib
| 4 |
1,902,320 | 38,707,772 |
Python Encoding that ignores leading 0s
|
<p>I'm writing code in python 3.5 that uses hashlib to spit out MD5 encryption for each packet once it is is given a pcap file and the password. I am traversing through the pcap file using pyshark. Currently, the values it is spitting out are not the same as the MD5 encryptions on the packets in the pcap file. </p>
<p>One of the reasons I have attributed this to is that in the hex representation of the packet, the values are represented with leading 0s. Eg: Protocol number is shown as b'06'. But the value I am updating the hashlib variable with is b'6'. And these two values are not the same for same reason:</p>
<pre><code>>> b'06'==b'6'
False
</code></pre>
<p>The way I am encoding integers is:</p>
<pre><code>(hex(int(value))[2:]).encode()
</code></pre>
<p>I am doing this encoding because otherwise it would result in this error: "TypeError: Unicode-objects must be encoded before hashing"</p>
<p>I was wondering if I could get some help finding a python encoding library that ignores leading 0s or if there was any way to get the inbuilt hex method to ignore the leading 0s.</p>
<p>Thanks!</p>
|
<p>Hashing <code>b'06'</code> and <code>b'6'</code> gives different results because, in this context, '06' and '6' are different.</p>
<p>The <code>b</code> string prefix in Python tells the Python interpreter to convert each character in the string into a byte. Thus, <code>b'06'</code> will be converted into the two bytes <code>0x30 0x36</code>, whereas <code>b'6'</code> will be converted into the single byte <code>0x36</code>. Just as hashing <code>b'a'</code> and <code>b' a'</code> (note the space) produces different results, hashing <code>b'06'</code> and <code>b'6'</code> will similarly produce different results.</p>
<hr>
<p>If you don't understand why this happens, I recommend looking up how bytes work, both within Python and more generally - Python's handling of bytes has always been a bit counterintuitive, so don't worry if it seems confusing! It's also important to note that the way Python represents bytes has changed between Python 2 and Python 3, so be sure to check which version of Python any information you find is talking about. You can comment here, too, </p>
|
python|encryption|hex|md5|encode
| 0 |
1,902,321 | 40,598,302 |
RSA encryption in Python vs Ruby
|
<p>I am trying to encrypt a small string using Python and Ruby. I've written code in both these languages that should do exactly the same thing: </p>
<p>In Python: </p>
<pre><code>from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from Crypto import Random
import sys, time, signal, socket, requests, re, base64
pubkey = "9B596422997705A8805F25232C252B72C6B68752446A30BF9117783FE094F8559CA4A7AA5DBECAEC163596E96CD9577BDF232EF2F45DC474458BDA8EC272311924B8A176896E690135323D16800CFB9661352737FEDA9FB8DD44B6025EA8037CBA136DAE2DC0061B2C66A6F564E2C9E9579DAFD9BFF09ACF3B6E39BF363370F4A8AD1F88E3AE9A7F2C1B1C75AC00EAE308F57EC9FBDA244FC8B0D1234677A6BEE228FEE00BF653E8E010D0E59A30D0A1194298E052399A62E6FBD490CF03E16A1166F901E996D53DE776169B4EE8705E1512CCB69F8086C66213667A070A65DA28AF18FC8FC01D37158706A0B952D0963A9A4E4A6451758710C9ADD1245AB057389535AB0FA1D363A29ED8AE797D1EE958352E55D4AD4565C826E9EF12FA53AE443418FD704091039E190690FD55BF32E7E8C7D7668B8F0550C5E650C7D021F63A5055B7C1AEE6A669079494C4B964C6EA7D131FA1662CF5F5C83721D6F218038262E9DDFE236015EE331A8556D934F405B4203359EE055EA42BE831614919539A183C1C6AD8002E7E58E0C2BCA8462ADBF3916C62857F8099E57C45D85042E99A56630DF545D10DD338410D294E968A5640F11C7485651B246C5E7CA028A5368A0A74E040B08DF84C8676E568FC12266D54BA716672B05E0AA4EE40C64B358567C18791FD29ABA19EACA4142E2856C6E1988E2028703B3E283FA12C8E492FDB"
foobar = "foobar"
pubkey_int = long(pubkey,16)
pub_exp = 65537L
pubkey_obj = RSA.construct((pubkey_int, pub_exp))
encypted_data = pubkey_obj.encrypt(foobar, pub_exp)
encypted_data_b64 = base64.b64encode(encypted_data[0])
print encypted_data_b64
</code></pre>
<p>In Ruby: </p>
<pre><code>require 'openssl'
require 'base64'
pubkey = "9B596422997705A8805F25232C252B72C6B68752446A30BF9117783FE094F8559CA4A7AA5DBECAEC163596E96CD9577BDF232EF2F45DC474458BDA8EC272311924B8A176896E690135323D16800CFB9661352737FEDA9FB8DD44B6025EA8037CBA136DAE2DC0061B2C66A6F564E2C9E9579DAFD9BFF09ACF3B6E39BF363370F4A8AD1F88E3AE9A7F2C1B1C75AC00EAE308F57EC9FBDA244FC8B0D1234677A6BEE228FEE00BF653E8E010D0E59A30D0A1194298E052399A62E6FBD490CF03E16A1166F901E996D53DE776169B4EE8705E1512CCB69F8086C66213667A070A65DA28AF18FC8FC01D37158706A0B952D0963A9A4E4A6451758710C9ADD1245AB057389535AB0FA1D363A29ED8AE797D1EE958352E55D4AD4565C826E9EF12FA53AE443418FD704091039E190690FD55BF32E7E8C7D7668B8F0550C5E650C7D021F63A5055B7C1AEE6A669079494C4B964C6EA7D131FA1662CF5F5C83721D6F218038262E9DDFE236015EE331A8556D934F405B4203359EE055EA42BE831614919539A183C1C6AD8002E7E58E0C2BCA8462ADBF3916C62857F8099E57C45D85042E99A56630DF545D10DD338410D294E968A5640F11C7485651B246C5E7CA028A5368A0A74E040B08DF84C8676E568FC12266D54BA716672B05E0AA4EE40C64B358567C18791FD29ABA19EACA4142E2856C6E1988E2028703B3E283FA12C8E492FDB"
foobar = "foobar"
asn1_sequence = OpenSSL::ASN1::Sequence.new(
[
OpenSSL::ASN1::Integer.new("0x#{pubkey}".to_i(16)),
OpenSSL::ASN1::Integer.new("0x10001".to_i(16))
]
)
public_key = OpenSSL::PKey::RSA.new(asn1_sequence)
data = Base64.encode64(public_key.public_encrypt(foobar))
puts data
</code></pre>
<p>Both these scripts are trying to encrypt the string <code>foobar</code> using the same public key. I expected both of them to output the same results each time, however this is not the case. Furthermore, every time the Ruby Script is executed, it outputs a different result. </p>
<p>Can someone help me identify the difference between these two scripts that is responsible for this behavior? </p>
|
<p>I am able to solve this issue by reading the documentation for <code>Class _RSAobj</code> (<a href="https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA._RSAobj-class.html#encrypt" rel="nofollow noreferrer">https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA._RSAobj-class.html#encrypt</a>)</p>
<blockquote>
<p>Attention: this function performs the plain, primitive RSA encryption
(textbook). In real applications, you always need to use proper
cryptographic padding, and you should not directly encrypt data with
this method. Failure to do so may lead to security vulnerabilities. It
is recommended to use modules Crypto.Cipher.PKCS1_OAEP or
Crypto.Cipher.PKCS1_v1_5 instead.</p>
</blockquote>
<p>Looks like cryptographic padding is not used by default in the RSA module for Python, hence the difference. </p>
<p>Modified Python Script:</p>
<pre><code>from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import sys, time, signal, socket, requests, re, base64
pubkey = "9B596422997705A8805F25232C252B72C6B68752446A30BF9117783FE094F8559CA4A7AA5DBECAEC163596E96CD9577BDF232EF2F45DC474458BDA8EC272311924B8A176896E690135323D16800CFB9661352737FEDA9FB8DD44B6025EA8037CBA136DAE2DC0061B2C66A6F564E2C9E9579DAFD9BFF09ACF3B6E39BF363370F4A8AD1F88E3AE9A7F2C1B1C75AC00EAE308F57EC9FBDA244FC8B0D1234677A6BEE228FEE00BF653E8E010D0E59A30D0A1194298E052399A62E6FBD490CF03E16A1166F901E996D53DE776169B4EE8705E1512CCB69F8086C66213667A070A65DA28AF18FC8FC01D37158706A0B952D0963A9A4E4A6451758710C9ADD1245AB057389535AB0FA1D363A29ED8AE797D1EE958352E55D4AD4565C826E9EF12FA53AE443418FD704091039E190690FD55BF32E7E8C7D7668B8F0550C5E650C7D021F63A5055B7C1AEE6A669079494C4B964C6EA7D131FA1662CF5F5C83721D6F218038262E9DDFE236015EE331A8556D934F405B4203359EE055EA42BE831614919539A183C1C6AD8002E7E58E0C2BCA8462ADBF3916C62857F8099E57C45D85042E99A56630DF545D10DD338410D294E968A5640F11C7485651B246C5E7CA028A5368A0A74E040B08DF84C8676E568FC12266D54BA716672B05E0AA4EE40C64B358567C18791FD29ABA19EACA4142E2856C6E1988E2028703B3E283FA12C8E492FDB"
foobar = "foobar"
pubkey_int = long(pubkey,16)
pub_exp = 65537L
pubkey_obj = RSA.construct((pubkey_int, pub_exp))
cipher = PKCS1_v1_5.new(pubkey_obj)
encypted_data = cipher.encrypt(foobar)
encypted_data_b64 = base64.b64encode(encypted_data)
print encypted_data_b64
</code></pre>
|
python|ruby|encryption
| 1 |
1,902,322 | 40,771,336 |
Reading a text file with multiple columns?
|
<p>I am suppose to read a large text file that consists of states, years, quarters and index. However when I run my code it receives an error saying "not enough values to unpack (expected 4, got 2). Any ideas on where I may be going wrong?</p>
<pre><code>def read(filepath):
data = {}
fd = open(filepath)
for line in fd:
state, year, qtr, index = line.split()
if len(state) == 2:
if index != '.':
if state not in data:
data[state] = [QuarterHPI(int(year), int(qtr), float(index))]
print(data)
return data
</code></pre>
|
<p><code>state, year, qtr, index = line.split()</code></p>
<p>is waiting for 4 items, but <code>line.split()</code> seems returned only 2.</p>
|
python
| 1 |
1,902,323 | 40,640,398 |
Regex to get number after matched pattern
|
<p>I have created a regex pattern to match the following:</p>
<pre><code>'x': 10.61 # Any number, can be negative
</code></pre>
<p><strong>Regex</strong>: <code>'x':\s[-+]?\d*\.*\d+</code></p>
<p>However, I would like to get <strong>only the number</strong>, and so have attempted the following:</p>
<pre><code>re.findall("'x':\K\s[-+]?\d*\.*\d+", info)
</code></pre>
<p>But from what I understand <code>\K</code> doesn't work on python.</p>
<p>Is there any <strong>alternative</strong> that would match e.g: <code>10.61</code> only?</p>
|
<p>This should work:</p>
<pre><code>info = "'x': 10.61"
items = re.findall("'x':\s([-+]?\d*\.*\d+)", info)
print(items[0]) # 10.61
</code></pre>
|
python|regex|python-2.7
| 4 |
1,902,324 | 9,951,927 |
subclassing from OrderedDict and defaultdict
|
<p>Raymond Hettinger <a href="http://rhettinger.wordpress.com/2011/05/26/super-considered-super/" rel="nofollow noreferrer">showed</a> a really cool way to combine collection classes:</p>
<pre><code>from collections import Counter, OrderedDict
class OrderedCounter(Counter, OrderedDict):
pass
# if pickle support is desired, see original post
</code></pre>
<p>I want to do something similar for OrderedDict and defaultdict. But of course, defaultdict has a different <code>__init__</code> signature, so it requires extra work. What's the cleanest way to solve this problem? I use Python 3.3.</p>
<p>I found a good solution here: <a href="https://stackoverflow.com/a/4127426/336527">https://stackoverflow.com/a/4127426/336527</a>, but I was thinking maybe deriving from defaultdict might make this even simpler?</p>
|
<p>Inheriting from <code>OrderedDict</code> as in the answer you linked to is the simplest way. It is more work to implement an ordered store than it is to get default values from a factory function.</p>
<p>All you need to implement for <code>defaultdict</code> is a bit of custom <code>__init__</code> logic and the extremely simple <code>__missing__</code>.</p>
<p>If you instead inherit from <code>defaultdict</code>, you have to delegate to or re-implement at least <code>__setitem__</code>, <code>__delitem__</code> and <code>__iter__</code> to reproduce the in-order operation. You still have to do setup work in <code>__init__</code>, though you might be able to inherit or simply leave out some of the other methods depending on your needs.</p>
<p>Take a look at <a href="http://code.activestate.com/recipes/576693/" rel="nofollow noreferrer">the original recipe</a> or <a href="https://stackoverflow.com/questions/60848/how-do-you-retrieve-items-from-a-dictionary-in-the-order-that-theyre-inserted">any of the others linked to from another Stack Overflow question</a> for what that would entail.</p>
|
python|collections|python-3.x|multiple-inheritance
| 7 |
1,902,325 | 27,939,670 |
Python flask cannot open an xml file
|
<p>I try to implement a server-side multilanguage service on my website. This is the structure on the folders:</p>
<pre><code>data
--locale
static
--css
--images
--js
templates
--index.html
--page1.html
...
main.py
</code></pre>
<p>I use Crowdin to translate the website and the output files are in XML. The locale folder contains one folder for each language with one xml file for every page.</p>
<p>I store on Cookies the language and here is my python code:</p>
<pre><code>from flask import request
from xml.dom.minidom import parseString
def languages(page):
langcode = request.cookies.get("Language")
xml = "/data/locale/%s/%s.xml" % (langcode, page)
dom = parseString(xml)
................
.............
</code></pre>
<p>Which I call in every page, like <code>languages("index")</code></p>
<p>This is an example of the exported xml files</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<!--Generated by crowdin.com-->
<!--
This is a description of my page
-->
<resources>
<string name="name1">value 1</string>
<string name="name2">value 2</string>
<string name="name3">value 3</string>
</resources>
</code></pre>
<p>However, I have the following error <code>ExpatError: not well-formed (invalid token): line 1, column 0</code></p>
<p>I googled it. I ended up to other stackoverflow questions, but most of them says about encoding problems and I cannot find any in my example.</p>
|
<p>You have to use <code>parse()</code> if you want to parse a file. <code>parseString()</code> will parse a string, the file name in your case.</p>
<pre><code>from flask import request
from xml.dom.minidom import parse
def languages(page):
langcode = request.cookies.get("Language")
xml = "/data/locale/%s/%s.xml" % (langcode, page)
dom = parse(xml)
</code></pre>
|
python|xml|flask
| 1 |
1,902,326 | 14,027,835 |
csv.dictreader does not give desired output
|
<p>Merry Christmas!</p>
<p>I have the following data:</p>
<pre><code>a = (" 101, 151, 0,'T1',2,2,1, 1.71470E-1,-1.02880E-1,2,'NUCA GSU ',1, 1,0.3200, 2,0.3900, 3,0.1400, 4,0.1500",
"1.10000E-3, 9.10000E-2, 1200.00",
"21.6000, 21.600, 0.000, 1200.00, 1100.00, 1000.00, 1, 101,22.68000,20.52000, 1.05000, 0.95000, 25, 0, 0.00021, 0.00051",
"500.000, 500.000")
b = (('I','J','K','CKT','CW','CZ','CM','MAG1','MAG2','NMETR','NAME',
'STAT','O1','F1','O2','F2','O3','F3','O4','F4'),
('R1-2','X1-2','SBASE1-2'),
('WINDV1','NOMV1','ANG1','RATA1','RATB1','RATC1','COD1','CONT1',
'RMA1','RMI1','VMA1','VMI1','NTP1','TAB1','CR1','CX1'),
('WINDV2','NOMV2'))
</code></pre>
<p>I would like to form a dict as follows:</p>
<pre><code>{'I': 101, 'J': 151, ...... 'F4': 0.1500}
{'R1-2': 1.10000E-3, ...... 'SBASE1-2': 1200.0}
{'WINDV1': 21.60, ...... 'ÇX1': 0.00051}
{'WINDV2': 500.0, 'NOMV2': 500.0}
</code></pre>
<p>I want to use csv.DicReader so I tried the following code:</p>
<pre><code>for j in range(4):
c=list(csv.DictReader(a[j], fieldnames=b[j]))
print c
</code></pre>
<p>I am not getting the desired output. What am I doing wrong?</p>
<p>I can already do it like this:</p>
<pre><code>for j in range(4):
c=dict(zip( b[j], (a[j].split(','))))
print c
</code></pre>
|
<p>I think it's simpler doing it without csv.DictReader, you aren't reading a CSV.</p>
<pre><code>newListOfDict=[]
for keyLine, valueLine in zip(b, a): #one and one line from a and b
#the string line in b splitted and stripped
splittedValues = map(lambda v: v.strip(), valueLine.split(","))
#create the new dict with the result of zip : ((b1, a1),(b2, a2)...)
newDict = dict(zip(keyLine, splittedValues))
newListOfDict.append(newDict)
print newListOfDict
</code></pre>
|
python
| 2 |
1,902,327 | 14,018,584 |
python with unprivileged ping in linux IPPROTO_ICMP
|
<p>according to
<a href="http://kernelnewbies.org/Linux_3.0#head-c5bcc118ee946645132a834a716ef0d7d05b282e" rel="noreferrer">http://kernelnewbies.org/Linux_3.0#head-c5bcc118ee946645132a834a716ef0d7d05b282e</a>
we can now ping as an unprivileged user, and I can sort of get it to work.</p>
<p>using <a href="https://github.com/jedie/python-ping" rel="noreferrer">https://github.com/jedie/python-ping</a> I modified line 210 to look like</p>
<p>current_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_ICMP)</p>
<p>as root I "echo 1000 1000 > /proc/sys/net/ipv4/ping_group_range"</p>
<p>my group is 1000</p>
<p>and I can run ping.py as myself as an ordinary user, I can see echo requests and echo replies in tcpdump</p>
<pre><code>18:33:24.840291 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto ICMP (1), length 269)
127.0.0.1 > 127.0.0.1: ICMP echo request, id 38, seq 0, length 249
18:33:24.840309 IP (tos 0x0, ttl 64, id 37939, offset 0, flags [none], proto ICMP (1), length 269)
127.0.0.1 > 127.0.0.1: ICMP echo reply, id 38, seq 0, length 249
</code></pre>
<p>but ping.py doesn't see the replies, and says timeout.</p>
<p>Any ideas how to make this work?</p>
<p>edit:</p>
<p>I'm narrowing down the issue.</p>
<pre><code>print "c", icmp_header, address, self.own_id
if icmp_header["packet_id"] == self.own_id: # Our packet
</code></pre>
<p>the problem is icmp_header["packet_id"] is always 8247 and self.own_id is the pid of ping.py. 8247 is 2037 in hex, which I can see quite a few time in the dump.</p>
<p>This is a full dump of a ping on the wire</p>
<pre><code>19:25:15.513285 00:00:00:00:00:00 > 00:00:00:00:00:00, ethertype IPv4 (0x0800), length 283: (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto ICMP (1), length 269)
127.0.0.1 > 127.0.0.1: ICMP echo request, id 70, seq 2, length 249
0x0000: 4500 010d 0000 4000 4001 3bee 7f00 0001 E.....@.@.;.....
0x0010: 7f00 0001 0800 d932 0046 0002 5b36 362c .......2.F..[66,
0x0020: 2036 372c 2036 382c 2036 392c 2037 302c .67,.68,.69,.70,
0x0030: 2037 312c 2037 322c 2037 332c 2037 342c .71,.72,.73,.74,
0x0040: 2037 352c 2037 362c 2037 372c 2037 382c .75,.76,.77,.78,
0x0050: 2037 392c 2038 302c 2038 312c 2038 322c .79,.80,.81,.82,
0x0060: 2038 332c 2038 342c 2038 352c 2038 362c .83,.84,.85,.86,
0x0070: 2038 372c 2038 382c 2038 392c 2039 302c .87,.88,.89,.90,
0x0080: 2039 312c 2039 322c 2039 332c 2039 342c .91,.92,.93,.94,
0x0090: 2039 352c 2039 362c 2039 372c 2039 382c .95,.96,.97,.98,
0x00a0: 2039 392c 2031 3030 2c20 3130 312c 2031 .99,.100,.101,.1
0x00b0: 3032 2c20 3130 332c 2031 3034 2c20 3130 02,.103,.104,.10
0x00c0: 352c 2031 3036 2c20 3130 372c 2031 3038 5,.106,.107,.108
0x00d0: 2c20 3130 392c 2031 3130 2c20 3131 312c ,.109,.110,.111,
0x00e0: 2031 3132 2c20 3131 332c 2031 3134 2c20 .112,.113,.114,.
0x00f0: 3131 352c 2031 3136 2c20 3131 372c 2031 115,.116,.117,.1
0x0100: 3138 2c20 3131 392c 2031 3230 5d 18,.119,.120]
19:25:15.513300 00:00:00:00:00:00 > 00:00:00:00:00:00, ethertype IPv4 (0x0800), length 283: (tos 0x0, ttl 64, id 37971, offset 0, flags [none], proto ICMP (1), length 269)
127.0.0.1 > 127.0.0.1: ICMP echo reply, id 70, seq 2, length 249
0x0000: 4500 010d 9453 0000 4001 e79a 7f00 0001 E....S..@.......
0x0010: 7f00 0001 0000 e132 0046 0002 5b36 362c .......2.F..[66,
0x0020: 2036 372c 2036 382c 2036 392c 2037 302c .67,.68,.69,.70,
0x0030: 2037 312c 2037 322c 2037 332c 2037 342c .71,.72,.73,.74,
0x0040: 2037 352c 2037 362c 2037 372c 2037 382c .75,.76,.77,.78,
0x0050: 2037 392c 2038 302c 2038 312c 2038 322c .79,.80,.81,.82,
0x0060: 2038 332c 2038 342c 2038 352c 2038 362c .83,.84,.85,.86,
0x0070: 2038 372c 2038 382c 2038 392c 2039 302c .87,.88,.89,.90,
0x0080: 2039 312c 2039 322c 2039 332c 2039 342c .91,.92,.93,.94,
0x0090: 2039 352c 2039 362c 2039 372c 2039 382c .95,.96,.97,.98,
0x00a0: 2039 392c 2031 3030 2c20 3130 312c 2031 .99,.100,.101,.1
0x00b0: 3032 2c20 3130 332c 2031 3034 2c20 3130 02,.103,.104,.10
0x00c0: 352c 2031 3036 2c20 3130 372c 2031 3038 5,.106,.107,.108
0x00d0: 2c20 3130 392c 2031 3130 2c20 3131 312c ,.109,.110,.111,
0x00e0: 2031 3132 2c20 3131 332c 2031 3134 2c20 .112,.113,.114,.
0x00f0: 3131 352c 2031 3136 2c20 3131 372c 2031 115,.116,.117,.1
0x0100: 3138 2c20 3131 392c 2031 3230 5d 18,.119,.120]
</code></pre>
<p>AFAICT, the icmp header might be packed wrong. however it's just a wild stab, I will stare at it some more later, in the meantime, any help would be appreciated.</p>
|
<p>There are two things you didn't take into account:</p>
<ul>
<li>When receiving messages on this new type of socket, the IP header is not included. Since the code you are modifying expects to use RAW sockets (which <em>do</em> include the IP header in received messages), you need to change quite a few things:
<ul>
<li>line 306 extracts the ICMP header with <code>packet_data[20:28]</code> but of course since the IP header is not included the 20 byte offset does not make sense. This has to become <code>packet_data[0:8]</code></li>
<li>At line 310, the code attempts to extract the IP header from the beginning of the packet, but it's not there. So this code will actually extract garbage. There are extra options you can set if you want to know things like the TTL (see the <a href="https://lwn.net/Articles/420800/" rel="nofollow">documentation which accompanies the patch that enabled the functionality</a>).</li>
</ul></li>
<li><p>With this new functionality, the kernel controls the ICMP ID through the socket binding mechanism. You can let the kernel choose an ID (implicit bind) or set an ID (explicit bind). It's better to just rely on implicit bind because the kernel will guarantee to choose an ID that's free.</p>
<p>On line 309, the code checks to see if the reply belongs to us by checking the id against <code>self.own_id</code>. But using implicit bind the kernel picks the ID for us. We could set <code>self.own_id</code> to the identifier the kernel has assigned using</p>
<pre><code>self.own_id = current_socket.getsockname()[1]
</code></pre>
<p>(put this right after <code>self.send_one_ping</code> on line 221)</p>
<p>But in fact the check against <code>self.own_id</code> is not even necessary anyway since the kernel already makes sure we only see the replies we're supposed to see.</p></li>
</ul>
|
python|sockets|ping|icmp
| 4 |
1,902,328 | 54,642,915 |
How to sort dict using python?
|
<p>I have problem about sorting my dict. My code is:</p>
<pre><code>x = {('S', 'A'): (5, 8), ('S', 'B'): (11, 17), ('S', 'C'): (8, 14)}
sort_x = sorted(x.items(), key=lambda kv: kv[1])
print sort_x
sort_x_dict = dict(sort_x)
print sort_x_dict
</code></pre>
<h3>Output:</h3>
<pre><code>[(('S', 'A'): (5, 8)), (('S', 'C'): (8, 14)), (('S', 'B'): (11, 17))]
{('S', 'A'): (5, 8), ('S', 'B'): (11, 17), ('S', 'C'): (8, 14)}
</code></pre>
|
<p>It's apparent from your <code>print</code> statements that you're using Python 2.7, and yet dicts are only guaranteed to be ordered since Python 3.7. You can either upgrade to Python 3.7 for your exact code to work, or switch to <code>collections.OrderedDict</code> in place of dict:</p>
<pre><code>from collections import OrderedDict
sort_x = sorted(x.items(), key=lambda kv: kv[1])
print(sort_x)
sort_x_dict = OrderedDict(sort_x)
print(sort_x_dict)
</code></pre>
|
python|sorting|dictionary
| 5 |
1,902,329 | 54,477,891 |
FileNotFoundError: [Errno 2] No such file or directory: 'latex': 'latex' (Python 3.6 issue)
|
<p>I'm trying to use the latex interpreter for figure labels. I generate my figures using the matplotlib library.</p>
<p>I am having trouble finding an answer to this common problem. I see many answers suggesting latex should be added to the path, how do we do this?</p>
<p>I've tried installing Ghostscript, updating matplotlib, etc but to no avail. Any help on this matter would be appreciated greatly. </p>
<p>Snippet of code for testing:</p>
<pre><code>from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
import numpy as np
import matplotlib.pyplot as plt
# Example data
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.plot(t, s)
plt.xlabel(r'\textbf{time} (s)')
plt.ylabel(r'\textit{voltage} (mV)',fontsize=16)
plt.title(r"\TeX\ is Number "
r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
fontsize=16, color='gray')
# Make room for the ridiculously large title.
plt.subplots_adjust(top=0.8)
plt.savefig('tex_demo')
plt.show()
</code></pre>
<p>Here is the result of the executed code:</p>
<pre><code>Traceback (most recent call last):
File "/Users/selih/anaconda3/lib/python3.6/site-packages/IPython/core/formatters.py", line 341, in __call__
return printer(obj)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py", line 241, in <lambda>
png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
File "/Users/selih/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py", line 125, in print_figure
fig.canvas.print_figure(bytes_io, **kw)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 2212, in print_figure
**kwargs)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py", line 513, in print_png
FigureCanvasAgg.draw(self)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py", line 433, in draw
self.figure.draw(self.renderer)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/figure.py", line 1475, in draw
renderer, self, artists, self.suppressComposite)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 2607, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py", line 1192, in draw
renderer)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py", line 1130, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/text.py", line 922, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/text.py", line 309, in _get_layout
ismath=ismath)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py", line 232, in get_text_width_height_descent
s, fontsize, renderer=self)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/texmanager.py", line 501, in get_text_width_height_descent
dvifile = self.make_dvi(tex, fontsize)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/texmanager.py", line 365, in make_dvi
texfile], tex)
File "/Users/selih/anaconda3/lib/python3.6/site-packages/matplotlib/texmanager.py", line 335, in _run_checked_subprocess
stderr=subprocess.STDOUT)
File "/Users/selih/anaconda3/lib/python3.6/subprocess.py", line 356, in check_output
**kwargs).stdout
File "/Users/selih/anaconda3/lib/python3.6/subprocess.py", line 423, in run
with Popen(*popenargs, **kwargs) as process:
File "/Users/selih/anaconda3/lib/python3.6/subprocess.py", line 729, in __init__
restore_signals, start_new_session)
File "/Users/selih/anaconda3/lib/python3.6/subprocess.py", line 1364, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'latex': 'latex'
<Figure size 432x288 with 1 Axes>
</code></pre>
<p>I believe this is quite a common error, but the answers for solving it have not gave me the tools to resolve it. Any help on adding latex, dvipng to my PATH would be appreciated. </p>
|
<p>I had the same problem and installed these packages, and the problem is gone.</p>
<pre><code>sudo aptitude install texlive-fonts-recommended texlive-fonts-extra
sudo apt-get install dvipng
</code></pre>
<p>You may also want to try this answer:
<a href="https://stackoverflow.com/a/55137294/4448477">https://stackoverflow.com/a/55137294/4448477</a></p>
|
python|matplotlib|latex|rc
| 11 |
1,902,330 | 8,088,742 |
python: convert telnet application to ssh
|
<p>I write a python telnet client to communicate with a server through telnet. However, many people tell me that it's no secure. How can I convert it to ssh? Should I need to totally rewrite my program?</p>
|
<p>While Telnet is insecure, it's essentially just a serial console over a network, which makes it easy to code for. SSH is much, much more complex. There's encryption, authentication, negotiation, etc to do. And it's <em>very</em> easy to get wrong in spectacular fashion.</p>
<p>There's nothing wrong with Telnet <em>per se</em>, but if you can change things over the network - and it's not a private network - you're opening yourself up for trouble.</p>
<p>Assuming this is running on a computer, why not restrict the server to localhost? Then ssh into the computer and telnet to localhost? All the security with minimal hassle.</p>
|
python|security|ssh|telnet
| 1 |
1,902,331 | 8,321,319 |
'AnonymousUser' object has no attribute 'backend'
|
<p>Using django-socialregistration, got following error:</p>
<pre><code>'AnonymousUser' object has no attribute 'backend'
</code></pre>
<p>How,</p>
<ol>
<li>I click on facebook connect url.</li>
<li>That took me Facebook and ask me to login. So I did, asked permission, I granted.</li>
<li>After that it redirect me to my site. And ask to setup. I provide user and email address.</li>
<li>Once I submit, got error like above:</li>
</ol>
<p>Trace point:</p>
<pre><code>path/to_file/socialregistration/views.py in post
128. self.login(request, user)
</code></pre>
<p>Do anybody know, what's wrong?</p>
|
<p>Oh man i used to get this error all the time, basically you are calling </p>
<pre><code>self.login(request, user)
</code></pre>
<p>without calling </p>
<p><code>authenticate(username=user, password=pwd)</code> </p>
<p>first</p>
<p>when you call <code>authenticate</code>, django sets the backend attribute on the user, noting which backend to use, see here for more details
<a href="https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticate" rel="noreferrer">https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticate</a></p>
|
python|django
| 8 |
1,902,332 | 41,710,612 |
AttributeError 'int' object has no attribute isdigit in ipython in ubuntu
|
<pre><code>def input_base():
print('please enter the number')
base = input("Number : ")
while not base.isdigit():
print("It`s not integer")
base = input("R.Number : ")
return base
...
</code></pre>
<p>This is my code and the error is:</p>
<blockquote>
<p>AttributeError : 'int' object has no attribute 'isdigit'</p>
</blockquote>
<p>I don't know how I could fix this code. I think, I should install some application, such a <code>python-numpy</code>, inside Ubuntu...<br>
Is that right?</p>
|
<p>You are using python2 therefore you have two functions <code>input</code> and <code>raw_input</code>. The difference being that <code>input</code> calls <code>eval</code> on the inputted string. This turns it from a string to whatever python would interpret it as when input as a script or at the REPL.</p>
<p>For the input <code>1</code> you would get the int value 1. </p>
<p>So the value you now have is an int and not a string. It does not have a method <code>isdigit</code>. If you are sticking with python 2, you should instead use <code>raw_input</code>, which doesnt do the <code>eval</code> and therefore always returns a string, which has an <code>isdigit</code> method.</p>
<p>For python3 <code>input</code> does what <code>raw_input</code> does it py2 and so works correctly here.</p>
|
python|ubuntu|ipython
| 0 |
1,902,333 | 47,105,227 |
Decision tree intuition for one hot encoded data
|
<p>In attempting to understand how scikit decision tree behaves for onehot encoded data I have following : </p>
<pre><code>X = [[1,0,1] , [1,1,1]]
Y = [1,2]
clf = tree.DecisionTreeClassifier(criterion='entropy')
clf = clf.fit(X, Y)
print(clf.predict([1,0,1]))
print(clf.predict([1,1,1]))
print(clf.predict_proba([1,0,1]))
print(clf.predict_proba([1,1,1]))
</code></pre>
<p>Which returns : </p>
<pre><code>[1]
[2]
[[ 1. 0.]]
[[ 0. 1.]]
</code></pre>
<p>Reading doc for predict_proba <a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier.predict_proba" rel="nofollow noreferrer">http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier.predict_proba</a> states following should be returned : </p>
<blockquote>
<p>p : array of shape = [n_samples, n_classes], or a list of n_outputs
such arrays if n_outputs > 1. The class probabilities of the input
samples. The order of the classes corresponds to that in the attribute
classes_.</p>
</blockquote>
<p>Probability of correctness for given input value should be returned ?
How return values [[ 1. 0.]] , [[ 0. 1.]] correspond to class probabilities for input samples ?</p>
|
<p>For instance <code>clf.predict_proba([1,0,1])</code> gives the following:</p>
<pre><code>[[ 1. 0. ]] # sample 1
# ^ ^
# probability for class 1 probability for class 2
</code></pre>
<p>So the prediction says the probability of this sample <code>[1,0,1]</code> to be class 1 is <code>1</code>, to be class 2 is <code>0</code>. So the prediction should be <code>1</code> which is the same as <code>clf.predict([1,0,1])</code> gives you. This could also be other values for instance <code>[[0.8, 0.2]]</code>, so the class with the largest probability is considered as the predicted value.</p>
|
python|scikit-learn|decision-tree
| 1 |
1,902,334 | 47,219,325 |
How to get italic and non italic text with lxml
|
<p>I'm using this command for each row in a table but I'm only getting the text that is not italic.</p>
<pre><code>name = ''.join(row.xpath('td[3]/a/text()'))
</code></pre>
<p>The <code>a</code> element has some text in <code><em> </em</code> tags.</p>
<pre><code><td class="cardname"><a href="http://www.mtgotraders.com/store/PRM_Ball_Lightning_f.html"><em>Ball</em> <em>Lightning</em> *Foil*</a></td>
</code></pre>
<p>I want to get <code>Ball Lightning *Foil*</code></p>
|
<p>Is this what you wanted? Whether you use xpath or css selector, the result is always the same. Give this a shot:</p>
<pre><code>html_content='''
<td class="cardname"><a href="http://www.mtgotraders.com/store/PRM_Ball_Lightning_f.html">
<em>Ball</em> <em>Lightning</em> *Foil*</a></td>
'''
from lxml.html import fromstring
root = fromstring(html_content)
item = root.cssselect(".cardname a")[0].text_content().strip()
item_alternative = root.xpath("//*[@class='cardname']/a")[0].text_content().strip()
print(item)
print(item_alternative)
</code></pre>
<p>Result:</p>
<pre><code>Ball Lightning *Foil*
Ball Lightning *Foil*
</code></pre>
|
python|xpath|web-scraping|lxml
| 1 |
1,902,335 | 47,422,672 |
SQL Delete statement with nested selects
|
<p>I am trying to make a subquery in a <code>DELETE</code> statement in order to improve performance. The plain <code>DELETE</code> statement works but the subquery ones are either deleting all rows indiscriminately, or only one row per invocation. I am confused as to why the statements are not equivalent.</p>
<p>Jump down to "What doesn't work" to see the problem statements.</p>
<h3>Upfront info</h3>
<p>I am using <code>sqlite3</code> from <code>python2</code> to manage a database of pictures with associated tags.</p>
<p>The schema for the table is:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE VIRTUAL TABLE "files" USING fts3(fname TEXT, orig_name TEXT, tags TEXT, md5sum TEXT);
</code></pre>
<p>Tags are organized as a comma separated list so direct string comparison in <code>sqlite</code> doesn't (easily) work, so I've add a helper function <code>TAGMATCH</code></p>
<pre><code>def tag_match(tags, m):
i = int(m in [i.strip() for i in tags.split(',')])
return i
db.create_function('TAGMATCH', 2, tag_match)
</code></pre>
<hr />
<h3>What works</h3>
<p>This does what I want/expect. It deletes all rows where the column <code>tags</code> contains the tag <code>'DELETE'</code>. Downside is, as far as I understand, this requires a linear scan of the table. Because of the "dangers" of deleting something from the table I did want to use <code>MATCH</code> in case, in some hypothetical situation, a match occurs with another unintended tag ie. <code>'DO NOT DELETE THIS'</code>.</p>
<pre class="lang-sql prettyprint-override"><code>DELETE FROM files WHERE TAGMATCH(tags, 'DELETE')
</code></pre>
<hr />
<hr />
<h3>What doesn't work</h3>
<p>To speed things up I tried a trick I read in another stackoverflow post where <code>MATCH</code> is used to narrow down the search, then a direct string comparison is done on those results ie</p>
<pre class="lang-sql prettyprint-override"><code>SELECT * FROM (SELECT * FROM table WHERE words MATCH keyword) WHERE words = keyword
</code></pre>
<hr />
<p>I tried using this trick here, but instead it deletes every row in the table.</p>
<pre class="lang-sql prettyprint-override"><code>DELETE FROM files WHERE TAGMATCH((
SELECT tags FROM files WHERE tags MATCH 'DELETE'), 'DELETE')
</code></pre>
<hr />
<p>This is what I first came up with. I realize now it's not a particularly good solution, but since its effect puzzles me I'm including it. This statement only deletes one row containing the tag <code>'DELETE'</code>. If invoked again, it deletes another row, and so on until all the rows with <code>'DELETE'</code> are removed:</p>
<pre class="lang-sql prettyprint-override"><code>DELETE FROM files WHERE rowid = (
SELECT rowid FROM (
SELECT rowid, tags FROM files WHERE tags MATCH 'DELETE')
WHERE TAGMATCH(tags, 'DELETE'))
</code></pre>
|
<p>Following query deletes everything because the <code>WHERE</code> clause evaluates to a number which if by itself evaluates to <code>TRUE</code>:</p>
<pre class="lang-sql prettyprint-override"><code>DELETE FROM files WHERE TAGMATCH((
SELECT tags FROM files WHERE tags MATCH 'DELETE'), 'DELETE')
</code></pre>
<p>Equivalent to</p>
<pre class="lang-sql prettyprint-override"><code>DELETE FROM files WHERE 1 -- or whatever ##
</code></pre>
<p>Instead, consider using <code>EXISTS</code> with subquery that correlates to main query:</p>
<pre class="lang-sql prettyprint-override"><code>DELETE FROM files WHERE EXISTS
(SELECT 1
FROM (SELECT rowid, tags FROM files WHERE tags MATCH 'DELETE') sub
WHERE TAGMATCH(sub.tags, 'DELETE') AND sub.rowid = files.rowid)
</code></pre>
<p>Alternatively, using your attempt, turn <code>=</code> into an <code>IN</code> as former only uses the first record found.</p>
<pre class="lang-sql prettyprint-override"><code>DELETE FROM files WHERE rowid IN
(SELECT rowid
FROM (SELECT rowid, tags FROM files WHERE tags MATCH 'DELETE') sub
WHERE TAGMATCH(sub.tags, 'DELETE'))
</code></pre>
|
python|sql|sqlite|fts3
| 4 |
1,902,336 | 47,227,654 |
re.VERBOSE and lookahead assertion error
|
<p>I have a verbose (<code>re.X</code>) flagged regex that is throwing an exception, even though it seems to be equivalent to its condensed version. (I built the former from the latter.)</p>
<p>Condensed version:</p>
<pre><code>import re
test = 'catdog'
test2 = 'dogcat'
pat = re.compile(r'(?=\b\w{6}\b)\b\w*cat\w*\b')
print(pat.search(test))
print(pat.search(test2))
# catdog Match object
# dogcat Match object
</code></pre>
<p>Verbose version:</p>
<pre><code>pat = re.compile(r"""( # Start of group (lookahead); need raw string
?= # Positive lookahead; notation = `q(?=u)`
\b\w{6}\b # Word boundary and 6 alphanumeric characters
) # End of group (lookahead)
\b\w*cat\w*\b # Literal 'cat' in between 0 or more alphanumeric""", re.X)
print(pat.search(test).string)
print(pat.search(test2).string)
# Throws exception
# error: nothing to repeat at position 83 (line 2, column 22)
</code></pre>
<p>What's causing this? I can't find why the expanded version is violating any condition for <code>re.X</code>/<code>re.VERBOSE</code>. From docs:</p>
<blockquote>
<p>This flag allows you to write regular expressions that look nicer and
are more readable by allowing you to visually separate logical
sections of the pattern and add comments. Whitespace within the
pattern is ignored, except when in a character class or when preceded
by an unescaped backslash. When a line contains a # that is not in a
character class and is not preceded by an unescaped backslash, all
characters from the leftmost such # through the end of the line are
ignored.</p>
</blockquote>
<p>There are no character classes or whitespace preceded by unescaped backslashes, as far as I can tell.</p>
|
<p>This is <a href="https://bugs.python.org/issue15606" rel="nofollow noreferrer">Python issue 15606</a>. <code>re</code>'s behavior with whitespace inside a token in verbose mode doesn't match the documentation. You can't put whitespace in the middle of <code>(?=</code>.</p>
|
python|regex|python-3.x
| 3 |
1,902,337 | 47,281,338 |
How to speed up my code? Python
|
<p>I need my code to work faster, this one I currently have sometimes even takes up to 5 seconds to print an answer.</p>
<pre><code>import math
n, k = [int(x) for x in input().split()]
myList = [int(i) for i in input().split()]
range_is = math.factorial(n) / (math.factorial(3) * math.factorial(n-3))
range_is = int(range_is)
answer_list = []
q = 0
w = 1
e = 2
for l in range(range_is):
o = myList[q]+myList[w]+myList[e]
answer_list.append(o)
if e == n-1 and w == n-2 and q != n-3:
q = q+1
w = q+1
e = w+1
elif e == n-1 and w != n-2:
w = w+1
e = w+1
elif e != n:
e = e+1
answer_list.sort()
print(answer_list[k-1])
</code></pre>
<p>How can I make it run faster? And what is the problem in this code, so I can avoid this problem in the future?</p>
|
<h1>What should be written in your question</h1>
<p>To summarize:</p>
<ul>
<li>You have a list of <code>n</code> integers.</li>
<li>You want to calculate every combination of <code>p</code> integers.</li>
<li>You want to calculate the sum of every combination.</li>
<li>You want to sort those sums.</li>
<li>You want the <code>k</code>-th sum.</li>
</ul>
<h1>Code with <code>itertools.combinations</code></h1>
<p>With this description, the code becomes straightforward:</p>
<pre><code>from itertools import combinations
n = 5
p = 3
k = 4
integers = range(1, n + 1)
triples = combinations(integers, p)
# [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
triple_sums = [sum(t) for t in triples]
# [6, 7, 8, 8, 9, 10, 9, 10, 11, 12]
triple_sums.sort()
# [6, 7, 8, 8, 9, 9, 10, 10, 11, 12]
print(triple_sums[k - 1])
# 8
</code></pre>
<p>Using <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow noreferrer"><code>itertools.combinations</code></a> might speed your code up, especially since you don't need to calculate <code>math.factorial(n)</code> for large <code>n</code>.</p>
<p>Most of all, this code is much more concise and shows your intent much better.</p>
<h1>Performance</h1>
<p>It's unfortunate that <code>triple_sums</code> isn't sorted even if <code>integers</code> are sorted. Every combination needs to be calculated, and the whole list has to be sorted. There might be an alternative way to produce the combinations with which <code>triple_sums</code> would be sorted directly but I cannot think of any.</p>
<p>If your list has 7000 integers, there will be <code>57142169000</code> triples. Using <code>itertools</code> won't help much for performance. You'd need to provide more information about the list and <code>k</code>.</p>
|
python|performance
| 2 |
1,902,338 | 57,421,318 |
What's ```__new__``` by default in Python 3?
|
<p>I believe I have some sort of understanding of what <code>__new__</code> is supposed to do (create an instance, of a class, but not initialize it, that is the job of <code>__init__</code>). I'd like to understand, however, what Python 3 implements as a <code>__new__</code> method by default.</p>
<p>I also find it somewhat confusing that <code>cls</code> is an argument for <code>__new__</code>, but <code>__new__</code> is a staticmethod and not a classmethod (I got this from the <a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="nofollow noreferrer">documentation</a>). How does it know that it is being passed a type as its first argument?</p>
|
<p>First part: what does <code>__new__</code> do by default? Because the creation of an object from scratch is a fundamental, implementation-specific operation, the definition of <code>object.__new__</code> is necessarily (like the rest of the definition of <code>object</code>) part of the implementation itself. That means you need to look in the source code of CPython, PyPy, Cython, etc. to see exactly how object creation is managed in any particular implementation of Python. Typically, it's all low-level bookkeeping that can't be accessed directly from Python itself.</p>
<p>Second part: how does <code>__new__</code> know that it gets a class argument? Because it <em>assumes</em> its first argument is a class, and the caller had better provide a class if they expect <code>__new__</code> to work correctly! That said, nobody really ever calls <code>__new__</code> expclitly, except via <code>super</code> in an override of <code>__new__</code>, and then, you have to make sure to pass <code>cls</code> explicitly yourself:</p>
<pre><code>def __new__(cls, *args, **kwargs):
rv = super().__new__(cls, *args, **kwargs) # Not super().__new__(*args, **kwargs)
</code></pre>
<p>The rest of the time, you create an instance of a class <code>Foo</code> not by calling <code>Foo.__new__(Foo, ...)</code> directly, but just by calling the type itself: <code>Foo(...)</code>. <em>This</em> is managed because the <code>__call__</code> method of <code>Foo</code>'s metaclass takes care of calling <code>__new__</code> for your. For example, you can imagine that <code>type.__call__</code> is defined roughly as</p>
<pre><code># A regular instance method of type; we use cls instead of self to
# emphasize that an instance of a metaclass is a class
def __call__(cls, *args, **kwargs):
rv = cls.__new__(cls, *args, **kwargs) # Because __new__ is static!
if isinstance(rv, cls):
rv.__init__(*args, **kwargs)
return rv
</code></pre>
<p>Note that <code>__init__</code> is only invoked if <code>__new__</code> actually returns an instance of the class calling <code>__new__</code> in the first place.</p>
|
python|python-3.x|default-constructor|class-constructors
| 13 |
1,902,339 | 11,743,506 |
Python Popen not behaving like a subprocess
|
<p>My problem is this--I need to get output from a subprocess and I am using the following code to call it-- (Feel free to ignore the long arguments. The importing thing is the stdout= subprocess.PIPE) </p>
<pre><code> (stdout, stderr) = subprocess.Popen([self.ChapterToolPath, "-x", book.xmlPath , "-a", book.aacPath , "-o", book.outputPath+ "/" + fileName + ".m4b"], stdout= subprocess.PIPE).communicate()
print stdout
</code></pre>
<p>Thanks to an answer below, I've been able to get the output of the program, but I still end up waiting for the process to terminate before I get anything. The interesting thing is that in my debugger, there is all sorts of text flying by in the console and it is all ignored. But the moment that anything is written to the console in black (I am using pycharm) the program continues without a problem. Could the main program be waiting for some kind of output in order to move on? This would make sense because I am trying to communicate with it.... Is there a difference between text that I can see in the console and actual text that makes it to the stdout? And how would I collect the text written to the console?</p>
<p>Thanks!</p>
|
<p>The first line of <A HREF="http://docs.python.org/library/subprocess.html#using-the-subprocess-module" rel="nofollow">the documentation for <code>subprocess.call()</code></A> describes it as such:</p>
<blockquote>
<p>Run the command described by args. Wait for command to complete, then return the returncode attribute.</p>
</blockquote>
<p>Thus, it necessarily waits for the subprocess to exit.</p>
<p><A HREF="http://docs.python.org/library/subprocess.html#popen-constructor" rel="nofollow"><code>subprocess.Popen()</code></A>, by contrast, does not do this, returning a handle on a process with which one than then <code>communicate()</code>.</p>
|
python|subprocess
| 2 |
1,902,340 | 11,662,063 |
What is verbosity level exactly in python?(difference between each level)
|
<p>What is the verbosity level in python.
I see it in unittest.</p>
<p>In documentation it just say simply that higher verbosity level, more info print out. but
<strong>more</strong> means what? That is to say, which message will be printed out in a higher level and which will not?</p>
<p>Also find verbosity in logging.</p>
<p>I think they are different due to the reason that logging verbosity level is in [0, 50] and unittest's is just a unit number.
I just want to find out the difference between each verbosity level in unittests.</p>
|
<p>Verbosity level is related just to logging. In unit tests you find it for the logging of the information.</p>
<p>Note: It is more pythonic to use levels as constant names(<code>logging.INFO</code>, <code>logging.DEBUG</code> rather than numbers.</p>
<p>These levels decide the amount of information you will get. For example setting the level to <code>ERROR</code> for running unit tests will display only the cases for which the unit tests failed. Setting it to <code>DEBUG</code> will give you more (the most in fact) info such as what were the values of the variables (in assert statements etc).</p>
<p>It is more useful in cases where your program has different levels of logging and you want your users to see different levels of info. For eg. usually you don't want the users to see details of internals, apart from fatal errors. So users will be running the program in FATAL or CRITICAL mode. But when some error occurs you will need such details. In this case you will run the program in debug mode. You can issue custom messages with these levels too. For eg, if you are providing back compatibility with older versions of your program, you can WARN them with <code>logging.warn()</code>, which will be issued only when the logging level is warning or less.</p>
<hr>
<p>DOCS:</p>
<h2> Level related stuff</h2>
<p>Default levels and level names, these can be replaced with any positive set
of values having corresponding names. There is a pseudo-level, NOTSET, which
is only really there as a lower limit for user-defined levels. Handlers and
loggers are initialized with NOTSET so that they will log all messages, even
at user-defined levels.</p>
<pre><code>CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
</code></pre>
|
python|unit-testing|logging
| 1 |
1,902,341 | 33,620,140 |
Cannot get url using urllib2
|
<p><br>
I'm learning Python, and the case for today is download text from a webpage.
This code works fine:</p>
<pre><code>import urllib2
from bs4 import BeautifulSoup
base_url = "http://www.pracuj.pl"
url = urllib2.urlopen(base_url+"/praca/big%20data;kw").read()
soup = BeautifulSoup(url,"html.parser")
for k in soup.find_all('a'):
if "offer__list_item_link_name" in k['class']:
link = base_url+k['href']
print link
</code></pre>
<p>So it prints all links like this:</p>
<pre><code>http://www.pracuj.pl/praca/inzynier-big-data-cloud-computing-knowledge-discovery-warszawa,oferta,4212875
http://www.pracuj.pl/praca/data-systems-administrator-krakow,oferta,4204109
http://www.pracuj.pl/praca/programista-java-sql-python-w-zespole-bigdata-krakow,oferta,4204341
http://www.pracuj.pl/praca/program-challenging-projektowanie-i-tworzenie-oprogramowania-katowice,oferta,4186995
http://www.pracuj.pl/praca/program-challenging-analizy-predyktywne-warszawa,oferta,4187512
http://www.pracuj.pl/praca/software-engineer-r-language-krakow,oferta,4239818
</code></pre>
<p>When add one line to assign new address, to fetch each lines content :</p>
<pre><code>url2 = urllib2.urlopen(link).read()
</code></pre>
<p>I get an error:</p>
<pre><code>Traceback (most recent call last):
File "download_page.py", line 10, in <module>
url2 = urllib2.urlopen(link).read()
NameError: name 'link' is not defined
</code></pre>
<p>What is wondering, it doesn't work only when in <code>for</code> loop. When I add the same line outside the loop it works.</p>
<p>Can you point what I'm doing wrong?</p>
<p>Pawel</p>
|
<p>I assume your line <code>url2 = urllib2.urlopen(link).read()</code> is not in the same scope as your <code>link</code> variable. The <code>link</code> variable is local to the scope of the <code>for</code> loop, so it will work if you move your call inside of the for loop.</p>
<pre><code>for k in soup.find_all('a'):
if "offer__list_item_link_name" in k['class']:
link = base_url+k['href']
url2 = urllib2.urlopen(link).read()
</code></pre>
<p>If you want to process the url outside of the for loop, save your links in a list:</p>
<pre><code>links = []
for k in soup.find_all('a'):
if "offer__list_item_link_name" in k['class']:
link = base_url+k['href']
links.append(link)
for link in links:
#do stuff with link
</code></pre>
|
python|python-2.7|beautifulsoup
| 1 |
1,902,342 | 46,896,347 |
Pairwise comparison in list of lists taking too long
|
<p>I have a list of lists, let's call it thelist, that looks like this: </p>
<pre><code>[[Redditor(name='Kyle'), Redditor(name='complex_r'), Redditor(name='Lor')],
[Redditor(name='krispy'), Redditor(name='flyry'), Redditor(name='Ooer'), Redditor(name='Iewee')],
[Redditor(name='Athaa'), Redditor(name='The_Dark_'), Redditor(name='drpeterfost'), Redditor(name='owise23'), Redditor(name='invirtibrit')],
[Redditor(name='Dacak'), Redditor(name='synbio'), Redditor(name='Thosee')]]
</code></pre>
<p>thelist has 1000 elements (or lists). I'm trying to compare each one of these with the other lists pairwise and try to get the number of common elements for each pair of lists. the code doing that:</p>
<pre><code>def calculate(list1,list2):
a=0
for i in list1:
if (i in list2):
a+=1
return a
for i in range(len(thelist)-1):
for j in range(i+1,len(thelist)):
print calculate(thelist[i],thelist[j])
</code></pre>
<p>My problem is: the calculation of the function is extremely slow taking 2 or more seconds per a list pair depending on their length. I'm guessing, this has to do with my list structure. What am i missing here?</p>
|
<p>First I would recommend making your class hashable which is referenced here: <a href="https://stackoverflow.com/questions/2909106/whats-a-correct-and-good-way-to-implement-hash">What's a correct and good way to implement __hash__()?</a> </p>
<p>You can then make your list of lists a list of sets by doing:</p>
<pre><code>thelist = [set(l) for l in thelist]
</code></pre>
<p>Then your function will work much faster!</p>
|
python|performance|list|search
| 2 |
1,902,343 | 67,886,429 |
Is there a way to save many values in one variable using a for-Loop in Robot framework?
|
<p>I need to collect every text witch is in a span element
but the loop overwrite the items...</p>
<pre><code>*** Variables ***
${items} ${EMPTY}
*** Test Cases ***
...
FOR ${i_i} IN RANGE ${Items_Count}
${i}= Evaluate ${i_i}+1
${items[i_i]}= Get Text //body[1]/table[1]/tbody[1]/tr/span[${i}]
END
</code></pre>
<p>...</p>
<p>it should look like this:</p>
<pre><code>${items} = {txt1 | txt2 | txt3 | ... | textN}
</code></pre>
<p>but my result is:</p>
<pre><code>${items} = {last text from span-element}
</code></pre>
|
<p>If you want to have a list of values:</p>
<pre><code>@{list} Create List
Append To List ${list} value_to_append
</code></pre>
<p>If you want a Dict-like of values:</p>
<pre><code>&{dictionary} Create Dictionary
Set To Dictionary ${dictionary} key value
</code></pre>
|
python|for-loop|variables|text|robotframework
| 1 |
1,902,344 | 67,973,931 |
Unable to run .bat file with python code: ImportError: Unable to import required dependencies: numpy:
|
<p>I'm using Anaconda. I created an environment called ENGINEERING. In than environment I installed python 3.6, pandas 1.1.3, spyder 3.3.6, numpy 1.19.2, and many more. The base environment has these packages also but not necessarily the same version. Within the ENGINEERING env I created a python script in Spyder that runs without any issues when I run it in spyder. Then, I want to automate that script by creating a .bat file and then using that to automate via windows task scheduler. My .bat looks like this:</p>
<pre><code>"C:\Users\alopo000\Anaconda3\envs\engineering\python.exe" "C:\Users\alopo000\Files\Python\Valid\Portf.py"
pause
</code></pre>
<p>when I run the .bat I get an error message:</p>
<pre><code>ImportError: Unable to import required dependencies:
numpy:
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.
We have compiled some common reasons and troubleshooting tips at:
https://numpy.org/devdocs/user/troubleshooting-importerror.html
Please note and check the following:
* The Python version is: Python3.6 from "C:\Users\alopo000\Anaconda3\envs\engineering\python.exe"
* The NumPy version is: "1.19.2"
and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.
Original error was: DLL load failed: The specified module could not be found.
</code></pre>
<p>I've tried many things to fix this. I went to the website they suggested and couldn't find anything there. I uninstalled pandas and numpy and reinstall them again but still, same error. The one thing I haven't tried is to fix the VARIABLE PATHS, mostly because I've read in many places not to change those. I can change them if that's what it is, but I would like to understand first why it is not recommended. I read it can create issues with other versions of python but not sure if that's what it is.</p>
<p>Do I need to activate the environment in the .bat file? is the problem that the .bat file is trying to run it outside the environment? Any help would be appreciated.</p>
|
<p>You will need to upgrade/change your base Python & numpy version installations to match those specified (3.6, 1.19.2). I had the same issue and same situation as OP (write/dev program in a virtual Spyder environment "spyder-env", then automate .py file with WTS). I tried copying over & running the 'activate.bat' in the /scripts/ folder of the virtual environment but that didn't work. In my situation, my conda spyder-env was Python = 3.9.12 and numpy = 1.21.5.</p>
<p>I ended up upgrading my base global Python version (conda install) for Python which changed from 3.8.3 and did the same with numpy (had to downgrade). I'm not sure if this is exactly necessary, why this works, or if it may cause problems down the line (I was about to just re-install conda).</p>
<p>The appropriate .bat file should be something like this once you do that:</p>
<pre><code>call "C:\Users\alopo000\Anaconda3\Scripts\activate.bat"
call "C:\Users\alopo000\Files\Python\Valid\Portf.py" %*
REM Uncomment below to debug
REM pause
</code></pre>
|
python|numpy|batch-file
| 1 |
1,902,345 | 29,818,876 |
Getting "ValueError: concat() expects at least one object!" in a simple python code block
|
<p>I ran the following code block in my IPython notebook and got a valueerror. I am not able to figure out whether it is a syntactical error. </p>
<pre><code>import sys
sys.version
</code></pre>
<p>would give me</p>
<pre><code>'2.7.9 |Anaconda 2.2.0 (64-bit)| (default, Dec 18 2014, 16:57:52) [MSC v.1500 64 bit (AMD64)]'
</code></pre>
<p>and on running</p>
<pre><code>from nltk.corpus import brown
[(genre, word) for genre in brown.categories() for word in brown.words(categories=genre) ]
</code></pre>
<p>I got the following error:</p>
<pre><code>---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-94-884c4187e29a> in <module>()
1 from nltk.corpus import brown
----> 2 [(genre, word) for genre in brown.categories() for word in brown.words(categories=genre) ]
C:\Anaconda\lib\site-packages\nltk\corpus\reader\tagged.pyc in words(self, fileids, categories)
198 def words(self, fileids=None, categories=None):
199 return TaggedCorpusReader.words(
--> 200 self, self._resolve(fileids, categories))
201 def sents(self, fileids=None, categories=None):
202 return TaggedCorpusReader.sents(
C:\Anaconda\lib\site-packages\nltk\corpus\reader\tagged.pyc in words(self, fileids)
81 self._para_block_reader,
82 None)
---> 83 for (fileid, enc) in self.abspaths(fileids, True)])
84
85 def sents(self, fileids=None):
C:\Anaconda\lib\site-packages\nltk\corpus\reader\util.pyc in concat(docs)
412 return docs[0]
413 if len(docs) == 0:
--> 414 raise ValueError('concat() expects at least one object!')
415
416 types = set(d.__class__ for d in docs)
ValueError: concat() expects at least one object!"
</code></pre>
<p>Thanks in advance for all the help.</p>
|
<p><p> From the traces what is see is there is no categories by name <code>genre</code>.<br>
<p> If I just display the categories in brown corpus:</p>
<pre><code>for name in brown.categories():
print name
Outputs:
adventure
belles_lettres
editorial
fiction
government
hobbies
humor
learned
lore
mystery
news
religion
reviews
romance
science_fiction
</code></pre>
<p><p> You can use any of the above category present in brown corpus.</p>
<p><p> Change this to:</p>
<pre><code>[(genre, word) for genre in brown.categories() for word in brown.words(categories=genre) ]
</code></pre>
<p><p> This:</p>
<pre><code>[(genre, word) for genre in brown.categories() for word in brown.words(categories=['news']) ] //Interested in news categories
</code></pre>
<p><p> More over what ever category you specify in outer <code>for loop</code>, inner <code>for loop</code> iterate over all the category in the corpus and hence the output will be same.</p>
|
python|nltk|ipython-notebook
| 1 |
1,902,346 | 61,386,299 |
Pandas: Convert Column to timedelta64
|
<p>I try to read a CSV file as pandas data frame. Beside column names, I get the expected dtype. My approach is:</p>
<ol>
<li>reading the CSV with inferring column types (as I want to be able
to catch issues)</li>
<li>reading the expected column types</li>
<li>iterating over the columns and try to convert them with <code>'astype'</code></li>
</ol>
<p>Now, I have timedeltas in nanoseconds. They are read in as float64 and can contain missing values. <code>'astype'</code> fails with the following message:</p>
<pre><code>ValueError: Cannot convert non-finite values (NA or inf) to integer
</code></pre>
<p>This little script can reproduce my issue. The method <code>'to_timedelta'</code> works perfekt on my data while the conversion give the error.</p>
<pre><code>import pandas as pd
import numpy as np
timedeltas = [200800700,30020010030,np.NaN]
data = {'timedelta': timedeltas}
pd.to_timedelta(timedeltas)
df = pd.DataFrame(data)
df.dtypes
df['timedelta'].astype('timedelta64[ns]')
</code></pre>
<p>Can anybody help to fix this issue? Is there any other save representation than nanoseconds which would work with <code>'astype'</code>?</p>
|
<p>Thanks to <a href="https://stackoverflow.com/questions/61386299/pandas-convert-column-to-timedelta64?noredirect=1#comment108713254_61386299">MrFuppes</a>.</p>
<p>It's not possible to use <code>astype()</code> but <code>to_timedelta</code> works. Thank you!</p>
<pre><code>df['timedelta'] = pd.to_timedelta(df['timedelta'])
</code></pre>
|
python|pandas|timedelta
| 0 |
1,902,347 | 61,339,788 |
dict attribute 'type' to select Subclass of dataclass
|
<p>I have the following class </p>
<pre><code>@dataclass_json
@dataclass
class Source:
type: str =None
label: str =None
path: str = None
</code></pre>
<p>and the two subclasses: </p>
<pre><code>@dataclass_json
@dataclass
class Csv(Source):
csv_path: str=None
delimiter: str=';'
</code></pre>
<p>and </p>
<pre><code>@dataclass_json
@dataclass
class Parquet(Source):
parquet_path: str=None
</code></pre>
<p>Given now the dictionary: </p>
<pre><code>parquet={type: 'Parquet', label: 'events', path: '/.../test.parquet', parquet_path: '../../result.parquet'}
</code></pre>
<pre><code>csv={type: 'Csv', label: 'events', path: '/.../test.csv', csv_path: '../../result.csv', delimiter:','}
</code></pre>
<p>Now I would like to do something like </p>
<pre><code>Source().from_dict(csv)
</code></pre>
<p>and that the output will be the class Csv or Parquet. I understand that if you initiate the class source you just "upload" the parameters with the method "from dict", but is there any posibility in doing this by some type of inheritence without using a "Constructor" which makes a if-else if-else over all possible 'types'?</p>
<p>Pureconfig, a Scala Library, creates different case classes when the attribute 'type' has the name of the desired subclass. In Python this is possible? </p>
|
<p>You can build a helper that picks and instantiates the appropriate subclass.</p>
<pre><code>def from_data(data: dict, tp: type):
"""Create the subtype of ``tp`` for the given ``data``"""
subtype = [
stp for stp in tp.__subclasses__() # look through all subclasses...
if stp.__name__ == data['type'] # ...and select by type name
][0]
return subtype(**data) # instantiate the subtype
</code></pre>
<p>This can be called with your data and the base class from which to select:</p>
<pre><code>>>> from_data(
... {'type': 'Csv', 'label': 'events', 'path': '/.../test.csv', 'csv_path': '../../result.csv', 'delimiter':','},
... Source,
... )
Csv(type='Csv', label='events', path='/.../test.csv', csv_path='../../result.csv', delimiter=',')
</code></pre>
<hr>
<p>If you need to run this often, it is worth building a <code>dict</code> to optimise the subtype lookup. A simple means is to add a method to your base class, and store the lookup there:</p>
<pre><code>@dataclass_json
@dataclass
class Source:
type: str =None
label: str =None
path: str = None
@classmethod
def from_data(cls, data: dict):
if not hasattr(cls, '_lookup'):
cls._lookup = {stp.__name__: stp for stp in cls.__subclasses__()}
return cls._lookup[data["type"]](**data)
</code></pre>
<p>This can be called directly on the base class:</p>
<pre><code>>>> Source.from_data({'type': 'Csv', 'label': 'events', 'path': '/.../test.csv', 'csv_path': '../../result.csv', 'delimiter':','})
Csv(type='Csv', label='events', path='/.../test.csv', csv_path='../../result.csv', delimiter=',')
</code></pre>
|
python|json|inheritance|subclass|python-dataclasses
| 3 |
1,902,348 | 27,630,155 |
AppRegistryNotReady: The translation infrastructure cannot be initialized
|
<p>When I try to access to my app, I'm getting the following error.</p>
<blockquote>
<p>AppRegistryNotReady: The translation infrastructure cannot be
initialized before the apps registry is ready. Check that you don't
make non-lazy gettext calls at import time</p>
</blockquote>
<p>Here is my wsgi.py file:</p>
<pre><code>"""
WSGI config for Projectizer project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Projectizer.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
</code></pre>
<p>And here is the stacktrace.</p>
<pre><code>mod_wsgi (pid=28928): Exception occurred processing WSGI script '/var/www/projectizer/apache/django.wsgi'.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 187, in __call__
response = self.get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 199, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 236, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/usr/local/lib/python2.7/dist-packages/django/views/debug.py", line 91, in technical_500_response
html = reporter.get_traceback_html()
File "/usr/local/lib/python2.7/dist-packages/django/views/debug.py", line 350, in get_traceback_html
return t.render(c)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 148, in render
return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 142, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 844, in render
bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py", line 80, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py", line 90, in render
output = self.filter_expression.resolve(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 624, in resolve
new_obj = func(obj, *arg_vals)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaultfilters.py", line 769, in date
return format(value, arg)
File "/usr/local/lib/python2.7/dist-packages/django/utils/dateformat.py", line 343, in format
return df.format(format_string)
File "/usr/local/lib/python2.7/dist-packages/django/utils/dateformat.py", line 35, in format
pieces.append(force_text(getattr(self, piece)()))
File "/usr/local/lib/python2.7/dist-packages/django/utils/dateformat.py", line 268, in r
return self.format('D, j M Y H:i:s O')
File "/usr/local/lib/python2.7/dist-packages/django/utils/dateformat.py", line 35, in format
pieces.append(force_text(getattr(self, piece)()))
File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py", line 85, in force_text
s = six.text_type(s)
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 144, in __text_cast
return func(*self.__args, **self.__kw)
File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/__init__.py", line 83, in ugettext
return _trans.ugettext(message)
File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 325, in ugettext
return do_translate(message, 'ugettext')
File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 306, in do_translate
_default = translation(settings.LANGUAGE_CODE)
File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 209, in translation
default_translation = _fetch(settings.LANGUAGE_CODE)
File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 189, in _fetch
"The translation infrastructure cannot be initialized before the "
AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.
</code></pre>
|
<p>I faced the same error. Following worked for me.
In your wsgi file change the last line to :</p>
<pre><code>from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
</code></pre>
<p>This have been changed since Django 1.6 to newer version.
<a href="http://jee-appy.blogspot.com/2015/04/deploy-django-project-on-apache-using.html" rel="nofollow noreferrer"><strong>Here</strong></a> is the post that helped to deploy the django app.</p>
<p>If you want to use Nginx as webserver to deploy django app follow <strong><a href="http://jee-appy.blogspot.com/2017/01/deply-django-with-nginx.html" rel="nofollow noreferrer">this</a></strong> post.</p>
|
python|django|django-i18n
| 30 |
1,902,349 | 27,754,393 |
Get fast functor from text of expression in Python (faster than eval)
|
<p>I have some trouble with performance.
I need to execute expression written in Python syntax in string.</p>
<pre><code>def FindOccurences( data, condition, left, right ):
result = []
func = eval( u"lambda data, i : " + condition )
for i in range(left, right):
if(func( data, i ) == True ):
result.append( i )
return result
</code></pre>
<p>This code works but it it ~3-4 times slower than if</p>
<pre><code>if(func( data, i ) == True):
result.append( i )
</code></pre>
<p>will be replaced with:</p>
<pre><code>if( *condition* ):
result.append( i )
</code></pre>
<p>But I don't wanna generate python script from template for each condition. </p>
<p>Is there any way to increase performance of first variant of the script?</p>
<p>PS there is no need to care about safety, this functionality will be used by people, who included in project</p>
|
<p>Try using <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehensions</a>. That way you won't have to load the <code>list.append</code> function into memory and it can boost your script, for not having to do a lot of appends, so check <a href="http://blog.cdleary.com/2010/04/efficiency-of-list-comprehensions/" rel="nofollow">this article</a> for a comparison. The code using list comprehensions can be written this way:</p>
<pre><code>def FindOccurences(data, condition, left, right):
func = eval( u"lambda data, i : " + condition)
return [i for i in range(left, right) if func(data, i)]
</code></pre>
<p>I'd also return an iterator over the <code>indexes</code> which are the result of the function, like this:</p>
<pre><code>def FindOccurences(data, condition, left, right):
func = eval( u"lambda data, i : " + condition)
return (i for i in range(left, right) if func(data, i))
</code></pre>
<p>That way, we can take the first three results of FindOcurrences method without getting the list with all of the results, sure we can do it by tweaking the left, right, but this way is more an on-demand approach:</p>
<pre><code>from itertools import islice
results = islice(FindOccurrences(mydata, condition_str, 0, 100)
for item in result:
print item
</code></pre>
|
python|performance|exec|eval|functor
| 0 |
1,902,350 | 43,100,441 |
I am trying to run Dickey-Fuller test in statsmodels in Python but getting error
|
<p>I am trying to run Dickey-Fuller test in statsmodels in Python but getting error P
Running from python 2.7 & Pandas version 0.19.2. Dataset is from Github and imported the same</p>
<pre><code>enter code here
from statsmodels.tsa.stattools import adfuller
def test_stationarity(timeseries):
print 'Results of Dickey-Fuller Test:'
dftest = ts.adfuller(timeseries, autolag='AIC' )
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
for key,value in dftest[4].items():
dfoutput['Critical Value (%s)'%key] = value
print dfoutput
test_stationarity(tr)
</code></pre>
<p>Gives me following error :</p>
<pre><code>Results of Dickey-Fuller Test:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-10ab4b87e558> in <module>()
----> 1 test_stationarity(tr)
<ipython-input-14-d779e1ed35b3> in test_stationarity(timeseries)
19 #Perform Dickey-Fuller test:
20 print 'Results of Dickey-Fuller Test:'
---> 21 dftest = ts.adfuller(timeseries, autolag='AIC' )
22 #dftest = adfuller(timeseries, autolag='AIC')
23 dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
C:\Users\SONY\Anaconda2\lib\site-packages\statsmodels\tsa\stattools.pyc in adfuller(x, maxlag, regression, autolag, store, regresults)
209
210 xdiff = np.diff(x)
--> 211 xdall = lagmat(xdiff[:, None], maxlag, trim='both', original='in')
212 nobs = xdall.shape[0] # pylint: disable=E1103
213
C:\Users\SONY\Anaconda2\lib\site-packages\statsmodels\tsa\tsatools.pyc in lagmat(x, maxlag, trim, original)
322 if x.ndim == 1:
323 x = x[:,None]
--> 324 nobs, nvar = x.shape
325 if original in ['ex','sep']:
326 dropidx = nvar
ValueError: too many values to unpack
</code></pre>
|
<p><em>tr</em> must be a 1d array-like, as you can see <a href="http://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.adfuller.html" rel="noreferrer">here</a>. I don't know what is <em>tr</em> in your case. Assuming that you defined <em>tr</em> as the dataframe that contains the time serie's data, you should do something like this:</p>
<pre><code>tr = tr.iloc[:,0].values
</code></pre>
<p>Then <em>adfuller</em> will be able to read the data.</p>
|
python-2.7|pandas|jupyter-notebook
| 11 |
1,902,351 | 43,262,746 |
How do I insert a condition under while loop?
|
<p>I am a beginner trying to learn python through MIT OpenCourseware. This problem is from <a href="https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/assignments/MIT6_0001F16_ps1.pdf" rel="nofollow noreferrer">part B of problem set 1</a>. I understand the mathematical expression but I do not know how to write it out in code.
This is the problem:
Determine how long it will take to save enough
money to make the down payment for a house given the following assumptions:</p>
<ul>
<li>portion_down payment = 0.25 (25%)</li>
<li>You start with a current savings of $0</li>
<li>Assume that you invest your current savings wisely, with an annual return of r = 0.04 (4%)</li>
<li>Your salary increases by a certain percentage every 6 months (semi-annual rise)</li>
</ul>
<p>Here is a test case:</p>
<p>Enter your starting annual salary: 120000
Enter the percent of your salary to save, as a decimal: .05
Enter the cost of your dream home: 500000
Enter the semiannual raise, as a decimal: .03
Number of months: 142 </p>
<p>Here is my code:</p>
<pre><code>annual_salary = float(input('Annual Salary: '))
portion_saved = float(input('Portion saved (decimal): '))
total_cost = float(input('Total Cost of House: '))
semi_annual_rise = float(input('Semi-annual salary rise (decimal): '))
downp = float(0.25*total_cost)
current_savings = 0
monthly_savings = float(portion_saved*annual_salary/12)
ret = 1 + .04/12
rise = 1 + semi_annual_rise
n = 0
while current_savings < downp:
for n in range(0,300,6):
monthly_savings = monthly_savings*(rise)
current_savings = (current_savings + monthly_savings)*(ret)
n += 1
print ('Number of months: ' + str(n))
</code></pre>
<p>Under the while loop, I am trying to increase the salary after 6, 12, 18 etc... months. But I dont know how to insert such a conditionI know it's wrong but I do not know how to correct it. Please help me!!</p>
|
<p>Just make the raise when <em>n%6 == 0</em> ...</p>
<pre><code>...
n = 0
while current_savings < downp:
n += 1
if n % 6 == 0: #every six months
monthly_savings = monthly_savings*(rise)
current_savings = (current_savings + monthly_savings)*(ret)
...
</code></pre>
|
python-3.x
| 0 |
1,902,352 | 48,490,297 |
Graph a custom function in python
|
<p>I would like to graph a custom function including <code>min</code> and <code>max</code> :</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
f = lambda x: max(0, x)
x = np.linspace(-10, 10)
y = f(x)
plt.plot(x, y)
plt.show()
</code></pre>
<p>Result:</p>
<blockquote>
<p>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</p>
</blockquote>
<p>Some help will be welcome</p>
|
<p>use vectorized <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html" rel="nofollow noreferrer"><code>np.clip()</code></a> instead of <code>f</code> - this way you can set both lower (<code>a_min</code>) and upper (<code>a_max</code>) boundaries in one step:</p>
<pre><code>y = np.clip(x, a_min=0, a_max=None)
</code></pre>
<p>or try to vectorize your scalar funcion:</p>
<pre><code>In [146]: x = np.linspace(-1000, 1000, 10**6)
In [147]: x.shape
Out[147]: (1000000,)
In [148]: vf = np.vectorize(f)
In [149]: %timeit [f(i) for i in x]
1.46 s ± 5.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [150]: %timeit vf(x)
1.03 s ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
|
python|numpy|matplotlib
| 5 |
1,902,353 | 48,663,623 |
Falcon cannot read request body
|
<p>I am trying to read a simple request body with JSON data.</p>
<p>The request body:</p>
<pre><code>[
{
...data
},
{
...data
}
]
</code></pre>
<p>When I try (In <code>EventResource</code>)</p>
<pre><code>def on_post(self, req, resp):
print(req.stream.read())
</code></pre>
<p>The following is logged into the console: <code>b''</code></p>
<p>I have no clue what I am doing wrong or why it is not displaying my body data. Every example I see when doing this it actually logs the data instead of what I am getting.</p>
<p>Requirements.txt (might be some out of context, but I've added the full list just to be sure.)</p>
<pre><code>astroid==1.5.3
bson==0.5.0
cffi==1.11.2
click==6.7
falcon==1.4.1
falcon-auth==1.1.0
falcon-jsonify==0.1.1
Flask==0.12.2
greenlet==0.4.12
gunicorn==19.7.1
isort==4.2.15
itsdangerous==0.24
Jinja2==2.10
lazy-object-proxy==1.3.1
MarkupSafe==1.0
mccabe==0.6.1
mimeparse==0.1.3
mongoengine==0.15.0
pycparser==2.18
PyJWT==1.5.3
pylint==1.7.4
pymongo==3.5.1
python-mimeparse==1.6.0
pytz==2017.3
readline==6.2.4.1
six==1.11.0
Werkzeug==0.12.2
wrapt==1.10.11
</code></pre>
<p>app.py</p>
<pre><code>api = falcon.API(middleware=[
falcon_jsonify.Middleware(help_messages=settings.DEBUG)
])
</code></pre>
<p>routes.py</p>
<pre><code>from app import api
from resources.event import EventResource
from resources.venue import VenueResource
# EventResources
api.add_route('/api/event', EventResource())
api.add_route('/api/event/{event_id}', EventResource())
api.add_route('/api/venue/{venue_id}/events', EventResource())
# VenueResources
api.add_route('/api/venue', VenueResource())
api.add_route('/api/venue/{venue_id}', VenueResource())
api.add_route('/api/event/{event_id}/venue', VenueResource())
</code></pre>
<p>I run my project with <code>gunicorn routes:api --reload</code></p>
<p>Example POST request (that logs the <code>b''</code>):</p>
<pre><code>curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:8000/api/event
</code></pre>
<p>The only thing I added as a header is <code>Content-Type</code>/<code>application/json</code></p>
<p>I've read through <a href="https://github.com/falconry/falcon/issues/471" rel="nofollow noreferrer" title="this">this</a> but it didn't help me.</p>
|
<p>The behavior happens because your</p>
<pre><code>falcon_jsonify.Middleware(help_messages=settings.DEBUG)
</code></pre>
<p>The stream is already read by it. You need to use <code>req.json</code> in that case. If you remove the middleware then <code>req.stream.read()</code> will return the value correctly. If you look at the middleware's <code>process_request</code> method</p>
<pre><code>def process_request(self, req, resp):
if not req.content_length:
return
body = req.stream.read()
req.json = {}
self.req = req
req.get_json = self.get_json
try:
req.json = json.loads(body.decode('utf-8'))
except ValueError:
self.bad_request("Malformed JSON", "Syntax error")
except UnicodeDecodeError:
self.bad_request("Invalid encoding", "Could not decode as UTF-8")
</code></pre>
<p>You can see the that middleware reads the body and then spits out the same in <code>req.json</code> as a parsed object. But the original body is not saved anywhere else. Once a request stream is read, you have emptied its buffer and won't get the data again. Hence you get <code>b''</code></p>
|
python-3.x|rest|gunicorn
| 5 |
1,902,354 | 48,414,190 |
Python Dictionary duplicates
|
<p>I have 2 lists </p>
<pre><code>list_a = [1, 1, 2, 2, 4, 5]
list_b = ['good', 'bad', 'worst', 'cheap', 'waste', 'waste1']
</code></pre>
<p>I am trying to write a python script and my mapping element in <code>list_a</code> with element in <code>list_b</code> and if someone inputs value <code>1</code> all the related values should populate. Eg if I enter <code>1</code> as input parameter the output should be</p>
<pre><code>good
bad
</code></pre>
<p>if I enter <code>2</code> as input parameter output should be</p>
<pre><code>worst
cheap
</code></pre>
<p>I tried python dictionaries but dictionary is not allowing duplicate keys. Is there is a way to achieve this in Python?</p>
|
<p>A rare use case for <a href="https://docs.python.org/3/library/itertools.html#itertools.compress" rel="nofollow noreferrer"><code>itertools.compress</code></a>:</p>
<pre><code>idx = get_index(...) # Get index to check by whatever means
for x in itertools.compress(list_b, (idx == i for i in list_a)):
print(x)
</code></pre>
<p><code>compress</code> takes an iterable of values, and an iterable of "truthy or falsy" values, returning the items from the first iterable when the second iterable provides a truthy paired value. So in this case, we want items from <code>list_b</code>, when the value in <code>list_a</code> matches the provided index, which we compute on the fly with a generator expression.</p>
<p>Mind you, for repeated lookups, a <code>dict</code> is a better bet. Simply using:</p>
<pre><code>lookup = {1: ['good', 'bad'], 2: ['worst', 'cheap'], 4: ['waste'], 5: ['waste1']}
</code></pre>
<p>will allow you to efficiently do <code>for x in lookup[idx]: print(x)</code> as many times as needed (possibly catching <code>KeyError</code> to ignore the case when the key doesn't exist, or to produce a friendlier error message).</p>
|
python|list|dictionary
| 3 |
1,902,355 | 51,548,794 |
Compare 2 maps together with matplotlib
|
<p>@Julien : I see no point in downvoting a question that could be useful to many beginners. That's ridiculous to see so much hate, your comment (which I respected) was more than enough. </p>
<p>I am working on geopandas and I try to compare 2 maps of NYC, based on their BoroCode (BoroCode & Borocode2). </p>
<p>Please find the code that you can reproduce at home : </p>
<pre><code>import pandas as pd
import geopandas
# We import the database of NYC and we plot it :
df = geopandas.read_file(geopandas.datasets.get_path('nybb'))
ax1 = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')
ax1
# Then I want to make another dataframe which has also a BoroCode column :
df_tmp1 = pd.DataFrame([[1.1, 5], [2.7, 4], [5.3, 3], [7, 1], [20, 2]], index = ['0', '1', '2', '3', '4'], columns = ['BoroCode2', 'BoroCode'])
df_tmp1
Out [4] :
BoroCode2 BoroCode
0 1.1 5
1 2.7 4
2 5.3 3
3 7.0 1
4 20.0 2
# Now I merge both dataframes :
df1 = pd.merge(df, df_tmp1, on = ['BoroCode'])
# And I can make to maps based on their BoroCode :
map1 = df1.plot(column='BoroCode', cmap='tab10', figsize=(15, 5), legend=True)
</code></pre>
<p><img src="https://image.ibb.co/bSsUb8/index.png" alt="map1"></p>
<pre><code>map2 = df1.plot(column='BoroCode2', cmap='tab10', figsize=(15, 5), legend=True)
</code></pre>
<p><img src="https://image.ibb.co/m6M0io/index2.png" alt="map2"></p>
<p>And then, I want to show side-by-side the <code>map1</code> & <code>map2</code> togethers in the same row. Just to compare them. </p>
<p>I have tested with <code>subplot</code>, but I think I don't master it well yet. </p>
<p>Because I am not familiar with the tutorials as they use functions to make plots and scatters from scratch with <code>ax</code>, <code>x</code>, and <code>y</code>, <code>axes</code>, etc. And I am a beginner so I can't succeed to adapt the code to my case. </p>
<p>I just want to show those maps together. Nothing more. </p>
<p>Could somebody help me to show such a way ? Thank you very much. </p>
|
<p>Subplots in matplotlib are created e.g. as </p>
<pre><code>fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(15,5))
</code></pre>
<p>Geopandas' <a href="http://geopandas.org/reference.html#geopandas.GeoDataFrame.plot" rel="nofollow noreferrer"><code>plot</code></a> accepts an argument <code>ax</code> to which to supply the axes to plot to. </p>
<pre><code>df1.plot(column='BoroCode', cmap='tab10', legend=True, ax=ax1)
df2.plot(column='BoroCode2', cmap='tab10', legend=True, ax=ax2)
</code></pre>
|
python|pandas|matplotlib
| 0 |
1,902,356 | 64,340,247 |
Scrolling to the next element in Selenium (Python)
|
<p>I'm trying to make a facebook commenting bot in Selenium in Python. I need to scroll down to the button for uploading photos in comments to make the comment and I have this line of code:</p>
<pre><code>ActionChains(driver).move_to_element(driver.find_element_by_id('my-id')).perform()
</code></pre>
<p>When I run it again it scrolls to the same button and I need to scroll to the next one. There's also another issue: this button doesn't have an id.
Is there any way to do it?</p>
|
<p>So, in order to scroll to multiple elements, you would need to use the <code>driver.execute_script()</code> method. If you have your driver and you have your page opened, then you need to isolate the element that you want to navigate to.</p>
<pre><code>element = driver.find_element(By.XPATH, "Whatever xpath you want")
driver.execute_script("return arguments[0].scrollIntoView();", element)
</code></pre>
<p>Once you have this, you will need to get a count of all elements that you want to scroll through. For example, in the <a href="https://www.imdb.com/list/ls055592025/" rel="nofollow noreferrer">Top 100 Greatest Movies List</a> website, I created a method to get the current count of displayed movies</p>
<pre><code>def get_movie_count(self):
return self.driver.find_elements(By.XPATH, "//div[@class='lister-list']//div[contains(@class, 'mode-detail')]").__len__()
</code></pre>
<p>After that, I created another method for scrolling to my element</p>
<pre><code>def scroll_to_element(self, xpath : str):
element = self.driver.find_element(By.XPATH, xpath)
self.driver.execute_script("return arguments[0].scrollIntoView();", element)
</code></pre>
<p>Once that was done, I created a <code>for-loop</code> and scrolled to each element</p>
<pre><code>for row in range(movieCount):
driver.scroll_to_element("//div[@class='lister-list']//div[contains(@class, 'mode-detail')][{0}]".format(row + 1))
</code></pre>
<p><strong>UPDATE: Added photo to help</strong>
<a href="https://i.stack.imgur.com/0ljyg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0ljyg.png" alt="Sample Program to Scroll through 100 elements" /></a></p>
<p><strong>Photo Explanation</strong>
<br>In this photo, we have our <code>WebDriver</code> class. This is the class that creates our Chrome WebDriver and includes any options that we want. In my case, I did not want to see the "This is being controlled by automation" alert all the time. <br><br>In the <code>WebDriver</code> class, I have a method called <code>wait_displayed</code> that has <code>selenium</code> check the browser's <code>DOM</code> for a specific element using <code>xpath</code>. If the element exists in the browser's <code>DOM</code>, all is good. Otherwise, <code>python</code> will raise an <code>Exception</code> and let me know that <code>selenium</code> could not find my element. In this class, I included the <code>scroll_to_element</code> method which allows my chrome driver to find an element on the page and executes <code>JavaScript</code> code to scroll to the element that was found.</p>
<p>In the <code>SampleSite</code> class, we inherit the <code>WebDriver</code> class. This means that my <code>SampleSite</code> class can use the methods that display in my <code>WebDriver</code> class. ( like <code>wait_displayed</code> and <code>scroll_to_element</code> ) In the <code>SampleSite</code> class, I provide an <code>optional parameter</code> in it's <code>constructor</code> method. ( <code>__init__()</code> ) This optional parameter tells the programmer that, if they want to create an <code>instance</code> or <code>object</code> of the <code>SampleSite</code> class, they need to, either, pass in an existing chrome driver; or, pass in <code>None</code> and the <code>SampleSite</code> class will open Google Chrome and navigate to our Top 100 Greatest Movies Page. This is the class where I created the <code>def get_movie_count(self):</code> method.</p>
<p>In our <code>main_program.py</code> file, I imported our <code>SampleSite</code> class. After import, I created an instance of our class and called the <code>get_movie_count</code> method. Once that method returned my movie count ( 100 ), I created a <code>for-loop</code> that scrolls through each of my elements.</p>
|
python|selenium
| 3 |
1,902,357 | 70,667,484 |
module 'website.management.commands.updatemodels' has no attribute 'Command'
|
<p>I am finding a problem while executing this code on my app 'website' using django</p>
<p><a href="https://i.stack.imgur.com/rr15N.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/rr15N.jpg</a></p>
<p><a href="https://i.stack.imgur.com/LWMP6.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/LWMP6.jpg</a></p>
|
<p>Please do not add code as screen shots as it is incovenient to access.</p>
<p>here is the mistake I can see:</p>
<ol>
<li>the class name needs to be class Command(BaseCommand):</li>
</ol>
<pre><code>class Command(BaseCommand):
....
</code></pre>
|
python|django|database|django-models|django-templates
| 0 |
1,902,358 | 56,006,317 |
How to convert dictionary list to custom objects in Python
|
<p>I have a list which has some dictionaries to be bulk uploaded. I need to check if elements of list can be cast to a custom object(as below). Is there any elegant way to do it like type comparison?</p>
<p>This is my model </p>
<pre><code>class CheckModel(object):
def __init__(self,SerialNumber,UID, Guid = None,Date = None):
self.SerialNumber = SerialNumber
self.UID = UID
self.Guid = str(uuid.uuid4()) if Guid is None else Guid
self.Date = datetime.now().isoformat() if Date is None else Date
</code></pre>
<p>And this is my test data. How can I cast only first element(because first element is the only correct one.) of this list into CheckModel object?</p>
<pre><code>test = [{
"Guid":"d0c035a7-0e01-4a37-8fe9-251fb5633fc9",
"SerialNumber":"1716154A",
"UID":"F13BDB3B",
"Date":"2019-12-03T13:50:19.882Z"
},
{
"Guid":"d0585-0e01-4a47-8fe9-251245f33fc9",
"SerialNumber":"1716154A",
"Date":"2019-12-03T13:50:19.882Z"
},
{
"Guid":"12414a7-0e01-4a47-8fe9-251245f33fc9",
"SerialNumber":"1716154A",
"UID":"F13BDB3B",
"Date":"2019-12-03"
}]
</code></pre>
|
<p>You can create a custom cleanup function and then use <code>filter</code></p>
<p><strong>Ex:</strong></p>
<pre><code>import datetime
import uuid
class CheckModel(object):
def __init__(self,SerialNumber,UID, Guid = None,Date = None):
self.SerialNumber = SerialNumber
self.UID = UID
self.Guid = str(uuid.uuid4()) if Guid is None else Guid
self.Date = datetime.datetime.now().isoformat() if Date is None else Date
#Clean Up Function.
def clean_data(data):
if all(key in data for key in ("Guid", "SerialNumber", "UID", "Date")):
try:
datetime.datetime.strptime(data["Date"], "%Y-%m-%dT%H:%M:%S.%fZ")
return True
except:
pass
return False
test = [{
"Guid":"d0c035a7-0e01-4a37-8fe9-251fb5633fc9",
"SerialNumber":"1716154A",
"UID":"F13BDB3B",
"Date":"2019-12-03T13:50:19.882Z"
},
{
"Guid":"d0585-0e01-4a47-8fe9-251245f33fc9",
"SerialNumber":"1716154A",
"Date":"2019-12-03T13:50:19.882Z"
},
{
"Guid":"12414a7-0e01-4a47-8fe9-251245f33fc9",
"SerialNumber":"1716154A",
"UID":"F13BDB3B",
"Date":"2019-12-03"
}]
model_data = [CheckModel(**data) for data in filter(clean_data, test)]
print(model_data)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>[<__main__.CheckModel object at 0x0000000002F0AFD0>]
</code></pre>
|
python
| 2 |
1,902,359 | 66,594,213 |
Return/obtain values from json if keypair matches - Python
|
<p>Currently I am able to pull a list of hard drive statuses from a website using its api. <strong>I want to slim down my results and have return back the data that the key pair "status": "Degraded", or "status": "Pred Fail" from my result.</strong></p>
<p>Here is what the json looks like without any parsing:</p>
<pre class="lang-json prettyprint-override"><code>{
"results": [
{
"bytesPerSector": 512,
"description": "SSD",
"interfaceType": "RAID",
"manufacturer": "UNKNOWN",
"mediaType": "Fixed hard disk media",
"model": "OEM Genuine 500GB",
"name": "\\\\.\\PHYSICALDRIVE0",
"partitionCount": 1,
"serialNumber": "Notputting that in here",
"size": 500105249280,
"smartCapable": true,
"status": "OK",
"deviceId": taking this out as well,
"timestamp": 1573080987.0
},
</code></pre>
<p>Currently, I have slimmed down my results to only show ['interfaceType'],['manufacturer'],['model'],['status']; however, I only want to pull the sections that have ['status':'Degraded'] or ['status':'Pred Fail'] as their status for the hard drive. (If that make sense?)</p>
<p>Here is the code I have so far:</p>
<pre class="lang-py prettyprint-override"><code>alerts = ''
for i in range (len(napialert['results'])):
ninjainterfaceType_str = json.dumps(napialert['results'][i]['interfaceType'], indent=2,)
ninjamanufacturer_str = json.dumps(napialert['results'][i]['manufacturer'], indent=2,)
ninjamodel = json.dumps(napialert['results'][i]['model'], indent=2,)
ninjastatus = json.dumps(napialert['results'][i]['status'], indent=2,)
alerts += (ninjainterfaceType_str + "\n" + ninjamanufacturer_str + "\n" + ninjamodel + "\n" + ninjastatus + "\n _____________________________\n")
print("Here are a list of Hard drive with manufacturer problems: " + alerts)
</code></pre>
<p>Here are the results (but it prints all of them instead of just the ones that have a failure status):</p>
<pre><code>Here are a list of Hard drive with manufacturer problems: "RAID"
"UNKNOWN"
"OEM Genuine 500GB"
"OK"
_____________________________
"SATA"
"Western Digital"
"WDC WD1502FAEX-007BA0"
"OK"
_____________________________
"SATA"
"UNKNOWN"
"ADATA SP550"
"OK"
More below this...
</code></pre>
<p>Let me know if anyone has any ideas or suggestions to try.</p>
|
<p>I see a couple of potential issues, the first one might be with the format of the json object you are getting it has '"' that might need to get stripped, maybe your API is actually returning this correctly, if that's the case is just matter of doing an actual check on the status property, you can find an example below, using an array and checking if the status of the current object is in that array:</p>
<pre><code>import json
napialert = {
"results": [
{
"bytesPerSector": 512,
"description": "SSD",
"interfaceType": "RAID",
"manufacturer": "UNKNOWN",
"mediaType": "Fixed hard disk media",
"model": "OEM Genuine 500GB",
"name": "\\\\.\\PHYSICALDRIVE0",
"partitionCount": 1,
"serialNumber": "Notputting that in here",
"size": 500105249280,
"smartCapable": True,
"status": "OK",
"deviceId": "taking this out as well",
"timestamp": 1573080987.0
},
{
"bytesPerSector": 512,
"description": "SSD",
"interfaceType": "RAID",
"manufacturer": "UNKNOWN",
"mediaType": "Fixed hard disk media",
"model": "OEM Genuine 500GB",
"name": "\\\\.\\PHYSICALDRIVE0",
"partitionCount": 1,
"serialNumber": "Notputting that in here",
"size": 500105249280,
"smartCapable": True,
"status": "Degraded",
"deviceId": "taking this out as well",
"timestamp": 1573080987.0
},
{
"bytesPerSector": 512,
"description": "SSD",
"interfaceType": "RAID",
"manufacturer": "UNKNOWN",
"mediaType": "Fixed hard disk media",
"model": "OEM Genuine 500GB",
"name": "\\\\.\\PHYSICALDRIVE0",
"partitionCount": 1,
"serialNumber": "Notputting that in here",
"size": 500105249280,
"smartCapable": True,
"status": "Pred Fail",
"deviceId": "taking this out as well",
"timestamp": 1573080987.0
}
]
}
alerts = ''
checks = ["Pred Fail", "Degraded"]
for i in range (len(napialert['results'])):
status = json.dumps(napialert['results'][i]['status'])
if status.strip('"') in checks:
ninjainterfaceType_str = json.dumps(napialert['results'][i]['interfaceType'], indent=2,)
ninjamanufacturer_str = json.dumps(napialert['results'][i]['manufacturer'], indent=2,)
ninjamodel = json.dumps(napialert['results'][i]['model'], indent=2,)
ninjastatus = json.dumps(napialert['results'][i]['status'], indent=2,)
alerts += (ninjainterfaceType_str + "\n" + ninjamanufacturer_str + "\n" + ninjamodel + "\n" + ninjastatus + "\n _____________________________\n")
print("Here are a list of Hard drive with manufacturer problems: " + alerts)
</code></pre>
|
python|json|for-loop|parsing
| 0 |
1,902,360 | 66,743,019 |
How do I properly compare performance of machine learning models, in the case of a multi-output classification problem?
|
<p><strong>TL,DR</strong>: I'm looking for a good way to compare the output of different scikit learn ML models on a multi-output classification problem: labelling social media messages according to the different disaster response categories they might fall into. I'm currently just using precision_recall_fscore_support on each label and then averaging the results, but I'm not convinced that this is a good solution.</p>
<p><strong>In detail:</strong> As part of an exercise I'm doing for an online data science course, I'm looking at a dataset of social media messages that occurred during natural disasters. The goal of the exercise is to train a machine learning model to classify these messages according to the various emergency departments they relate to, such as: aid_related, medical_help, weather_related, floods, etc...</p>
<p>So for example the following message: <em>"UN reports Leogane 80-90 destroyed. Only Hospi..."</em> is classed in my training data as 'medical_products', 'aid_related' and 'request'.</p>
<p>I've started off using scikit-learn's KNeighborsClassifier, and MultiOutputClassifier. I'm also using gridsearch to compare parameters inside the model:</p>
<pre><code>pipeline = pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(KNeighborsClassifier()))
])
parameters = { 'clf__estimator__n_neighbors': [5, 7]}
cv = GridSearchCV(pipeline, parameters)
cv.fit(X_train, y_train)
y_pred = pipeline.predict(X_test)
</code></pre>
<p>When I finally (it takes forever just with two parameteres to compare) get the model output, I've written the following function to pull out a matrix with the average precision, recall and fscore for each column:</p>
<pre><code>def classify_model_output(y_test, y_pred):
classification_scores = []
for i, column in enumerate(y_test.columns): classification_scores.append(precision_recall_fscore_support(y_test[column], y_pred[:, i]))
df_classification = pd.DataFrame(classification_scores)
df_classification.columns = ['precision', 'recall', 'fscore', 'support']
df_classification.set_index(y_test.columns, inplace=True)
# below loop splits the precision, recall and f-score columns into two, one for negatives and one for positives (0 and 1)
for column in df_classification.columns:
column_1 = df_classification[column].apply(lambda x: x[0]).rename(column+str(0), inplace=True)
column_2 = df_classification[column].apply(lambda x: x[1]).rename(column+str(1), inplace=True)
df_classification.drop([column], axis=1, inplace=True)
df_classification = pd.concat([df_classification, column_1, column_2], axis=1)
# finally, take the average of the dataframe to get a classifier for the model
df_classification_avg = df_classification.mean(axis=0)
return df_classification_avg
</code></pre>
<p>The df_classification table which looks like this (top 5 rows):</p>
<p><a href="https://i.stack.imgur.com/hmyf7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hmyf7.jpg" alt="enter image description here" /></a></p>
<p>And here's what I get when I compare the average classification tables (produced by the previous method) for <em>knn with 5 neighbors</em> (avg_knn), <em>knn with 7 neighbors</em> (knn_avg_2), and <em>random forest</em> (rf) - yellow cells represent the max for that row:</p>
<p><a href="https://i.stack.imgur.com/psOMH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/psOMH.jpg" alt="enter image description here" /></a></p>
<p>But I'm not sure how to interpret this. One the face of it it looks like Random Forest (rf) performed best. But I'm not sure if this is the best way to achieve this, or if using the average even makes sense here.</p>
<p>Does anyone have any advice on the best way to accurately and transparently compare my models, in the case of a multioutput problem like this one?</p>
<p>Edit: updated code block with easier to read function, and added comparison of three models</p>
|
<p>If your training data is not biased towards any particular output label, then you can go for your accuracy score. i.e. corresponding all labels, there is balanced amount of training data.</p>
<p>However if your data is imbalanced i.e. training data is more towards one or two particular output label then go for precision and recall.</p>
<p>Now between precision and recall , the choice depends on your need . If you are not much considered about accuracy go for recall e.g. on airport there is minimum chance that any bomb would be recovered from luggage, but you check all bags. That is recall.</p>
<p>When you are more considered about how much correct predictions are done from a sample , go for precision.</p>
|
python|machine-learning|scikit-learn|random-forest|knn
| 0 |
1,902,361 | 66,616,312 |
Numpy - count nonzero elements in 3d array
|
<p>I have a soduko board stored as <code>blocks = np.full(81, fill_value=0 ).reshape((9,3,3))</code>(<em>Important note: blocks are indexed sequentially, but to take up less space I show them as a single 9x9 block instead of <code>9x3x3</code>; middle block is index 4 (instead of <code>(1,1)</code>, bottom left is index 6</em>).<br />
I want to count the amount of nonzero element in this per block, example:</p>
<pre><code>[[0 0 0 0 0 0 0 0 0]
[2 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0]
[0 0 0 5 7 4 0 0 0]
[0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0]]
</code></pre>
<p>This has 1 nonzero in block 0 and 3 in block 4. I'm trying to use np.count_nonzero to achieve this, but the return value is never what I want no matter what axis I set as the parameter.<br />
<strong>What I'd like to have as the output is a 9 long 1d array</strong>, but instead I get a <code>(3,3)</code> if I use count_nonzero along axis 0, a <code>(9,3)</code> along axes 1 and 2. While <code>axis=2</code> does contain the value I want they are in different columns. Should I try to extract the values in a 1d array, or is there a way to make this work properly with count_nonzero?</p>
<p>Edit: Just to clarify blocks looks like this:</p>
<pre><code>[[[0 0 0]
[2 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[5 7 4]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]]
</code></pre>
|
<p>I think this is what you are trying to do if I understand your requirements correctly:</p>
<pre><code>>>> z
array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
[2, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 5, 7, 4, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]])
>>> np.bincount(z.nonzero()[0], minlength=9)
array([0, 1, 0, 3, 0, 0, 0, 0, 0])
</code></pre>
|
python|numpy|multidimensional-array
| 0 |
1,902,362 | 64,877,281 |
Extract the text between all sets of brackets
|
<p>In Python, how do I turn this:</p>
<pre><code>"(test1)(test2)"
</code></pre>
<p>into this:</p>
<pre><code>["test1","test2"]
</code></pre>
<p>?</p>
|
<p>Split, replace, filter and attack! (Basically regex might not be allowed for you)</p>
<pre><code>s = "(test1)(test2)"
print([x for x in s.replace("(","").split(")") if x != ''])
</code></pre>
|
python|string
| 0 |
1,902,363 | 64,800,534 |
how can i display the properties of my models that are stored in the QuerySet object?
|
<p>My django app has a simple model, i created 3 instances, each has title and description properties, how can i use these properties to display in html template?</p>
<p>models.py:</p>
<pre><code>from django.db import models
class Solution(models.Model):
title = models.CharField(max_length=200, help_text='Enter a title of solution')
description = models.TextField(max_length=1000, help_text='Enter a description of solution',)
def __str__(self):
return self.title
</code></pre>
<p>views.py:</p>
<pre><code>from django.shortcuts import render
from .models import Solution
from django.views import generic
def index(request):
solutions = Solution.objects.all()
return render(request, "main/index.html", {'solutions': solutions})
</code></pre>
<p>I need to do something like this in a file html:</p>
<pre><code><div class="content">
<h3>{{ solution.title }}</h3>
</code></pre>
|
<p>If you only need the first object then you have to edit your query, try it like this:</p>
<p>Views.py</p>
<pre><code>from django.shortcuts import render
from .models import Solution
from django.views import generic
def index(request):
solutions = Solution.objects.first()
return render(request, "main/index.html", {'solutions': solutions})
</code></pre>
<p>template</p>
<pre><code>{{ solutions.title }}
</code></pre>
<p>if you do not want to change your query, you can also use <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#first" rel="nofollow noreferrer">this</a> in your template to get the first object:</p>
<pre><code>{{ solutions|first }}
</code></pre>
|
python|django|django-queryset
| 0 |
1,902,364 | 64,770,682 |
Odd pandas date slicing behavior (doesn't slice day)
|
<p>I could be missing something here but I believe that there is something odd going on with pandas datetime slicing. Here is a reproducible example:</p>
<pre><code>import pandas as pd
import pandas_datareader as pdr
testdf = pdr.DataReader('SPY', 'yahoo')
testdf.index = pd.to_datetime(testdf.index)
testdf['2020-11']
</code></pre>
<p>Here we can see that slicing to find the month's data returns the expected output.
However, now lets try to find the row corresponding to Nov 9 2020.</p>
<pre><code>testdf['2020-11-09']
</code></pre>
<p>And we get the following traceback.</p>
<pre><code>---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
C:\Anaconda\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2894 try:
-> 2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: '2020-11-09'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-78-a42a45b5c3a4> in <module>
----> 1 testdf['2020-11-09']
C:\Anaconda\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2900 if self.columns.nlevels > 1:
2901 return self._getitem_multilevel(key)
-> 2902 indexer = self.columns.get_loc(key)
2903 if is_integer(indexer):
2904 indexer = [indexer]
C:\Anaconda\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
-> 2897 raise KeyError(key) from err
2898
2899 if tolerance is not None:
KeyError: '2020-11-09'
</code></pre>
<p>Here we can see that the key is in fact in the index:</p>
<pre><code>testdf['2020-11'].index
DatetimeIndex(['2020-11-02', '2020-11-03', '2020-11-04', '2020-11-05',
'2020-11-06', '2020-11-09'],
dtype='datetime64[ns]', name='Date', freq=None)
</code></pre>
<p>Is this a bug or am I a bug?</p>
|
<p><code>testdf['2020-11-09']</code> slice <strong>column-wise</strong>, i.e. looking in columns for <code>'2020-11-09'</code>. Do you mean:</p>
<pre><code>testdf.loc['2020-11-09']
</code></pre>
|
python-3.x|pandas|datetime
| 2 |
1,902,365 | 71,944,307 |
Branching in Pyscipopt
|
<p>Branching on t_x21 led to this error</p>
<blockquote>
<p>[scip_branch.c:1061] ERROR: cannot branch on variable <t_x21> with fixed domain [-0,0]</p>
</blockquote>
<p>So, my guess as to why this did not work is that during presolving, SCIP fixed this variable to be 0 and hence it throws an error if we try to branch on it? Is this correct? (Also, this error occured after a restart)</p>
<p><a href="https://github.com/scipopt/scip/blob/3d229190c1e6768d7c98641aca26d6e709a4f870/src/scip/scip_branch.c#L1061" rel="nofollow noreferrer">Link to scip_branch.c</a></p>
|
<p>Yeah, branching on a fixed variable does not make much sense. You should check the bounds before selecting a variable as a branching candidate, I suppose.</p>
|
python|optimization|scip
| 0 |
1,902,366 | 71,570,653 |
styleframe.ExcelWriter's date_format and datetime_format is not work~
|
<p>Today I use styleframe to help beautify my Excel.</p>
<p>While I add the date_format or datetime_format, it's not work.</p>
<pre class="lang-py prettyprint-override"><code>def _write_xlsx(self, filename, data, columns):
print(f'Writing {filename} length: {len(data)}')
data_frame = pandas.DataFrame(data, columns=columns)
excel_writer = StyleFrame.ExcelWriter(
filename,
date_format='YYYY-MM-DD', # TODO: not work!
datetime_format='YYYY-MM-DD HH:MM:SS', # TODO: not work!
)
style_frame = StyleFrame(data_frame)
style_frame.to_excel(
excel_writer=excel_writer,
best_fit=columns,
columns_and_rows_to_freeze='B2',
row_to_add_filters=0,
)
excel_writer.save()
</code></pre>
<p>I changed the input time object into 'datetime.datetime' or 'Pandas.Timestamp', It's still not working.</p>
<pre class="lang-py prettyprint-override"><code>pandas.to_datetime(pandas_col.get('my_time')).to_pydatetime() # datetime.datetime
pandas.to_datetime(pandas_col.get('my_time')) # Pandas.Timestamp
</code></pre>
<p>I read styleframe's source code. StyleFrame.ExcelWriter is pandas.ExcelWriter.</p>
<p>pandas.ExcelWriter's <strong>init</strong> func has date_format and datetime_format, and it looks like used date_format and datetime_format.</p>
<p>So, am I have sth. wrong?</p>
|
<p><code>styleframe</code> uses <a href="https://styleframe.readthedocs.io/en/latest/styler.html" rel="nofollow noreferrer"><code>Styler</code></a> objects to represent and apply styles. It can specify different formats for <code>date</code>, <code>time</code> and <code>datetime</code> objects.</p>
<p>See this example:</p>
<pre class="lang-py prettyprint-override"><code>from styleframe import StyleFrame, Styler
sf = StyleFrame({'a': [datetime.now().date(), datetime.now()]},
Styler(date_format='YYYY-MM-DD',
date_time_format='YYYY-MM-DD HH:MM:SS'))
sf.to_excel('dates.xlsx').save()
</code></pre>
<p>The only oversight is that pandas converts <code>date</code> objects to <code>Timestamp</code> objects, so the format passed as <code>date_format</code> to <code>Styler</code> is not used (because internally <code>styleframe</code> uses the <code>date_time_format</code> for <code>Timestamp</code> objects).</p>
|
python|pandas|styleframe
| 0 |
1,902,367 | 62,662,064 |
How to Iterate over the list and convert the datatype
|
<p>Below is my list</p>
<p><code>list_a = ['20.3', '6.74', '323','a']</code></p>
<p>Code is below</p>
<pre><code>try:
list_a = map(float, list_a)
except ValueError:
pass
for i in list_a:
print (i)
</code></pre>
<p>Expected result</p>
<p><code>[20.3, 6.74, 323,'a']</code></p>
|
<p>You can use following:</p>
<pre><code>list_a = ['20.3', '6.74', '323','a']
for i,v in enumerate(list_a):
try:
x=float(v)
list_a[i]=x
except:
pass
</code></pre>
<p>This would be working for your scenario.</p>
|
python|list
| 2 |
1,902,368 | 62,483,663 |
Python: Start and stop thread using keyboard presses
|
<p>I'm working on Python 3.8 and I'm trying to be able to toggle a thread on and off using a keyboard shortcut.</p>
<p>This is my Thread class:</p>
<pre><code>import keyboard
from threading import Thread
import time
class PrintHi(Thread):
def __init__(self):
Thread.__init__(self)
self.active = False
def run(self):
while True:
if self.active:
print("Hi,", time.time())
time.sleep(1)
</code></pre>
<p>It seems to work as intended I can start the thread and later change 'thread.active' to True or False depending on if I want to enable it or disable.</p>
<p>The problem is when I try to use it with the "keyboard" module it doesnt work as expected:</p>
<pre><code>class KeyboardHook(object):
def __init__(self):
self.thread = PrintHi()
self.thread.start()
self.set_keyboard_hotkeys()
def toggle_print(self):
print("Toggle Print")
self.thread.active = not self.thread.active
def set_keyboard_hotkeys(self):
print("Setting hotkeys hooks")
keyboard.add_hotkey('ctrl+c', self.toggle_print)
keyboard.wait()
if __name__ == '__main__':
hook = KeyboardHook()
</code></pre>
<p>These are the steps:</p>
<ul>
<li>I first create the thread, store it in 'self.thread' and start it.</li>
<li>Then I set the keyboard hotkeys hooks</li>
<li>When I press 'ctrl+c' the 'toggle_print()' function should execute </li>
<li>This should set the active property of the thread to True thus enabling the printing.</li>
</ul>
<p>The thread by itself works fine, and the keyboard hook by itself also works fine but when I combine both they don't work.</p>
<p>Does anyone have an idea of what I'm doing wrong? Is there a approach of toggling threads on and off by using keyboard shortcuts? In my application, I will have multiple threads that I will have to toggle on and off independently.</p>
<p>Thanks!</p>
|
<p>I'd suggest to refactor your code a bit, namely to use <code>Event</code> in the printer thread instead of a <code>bool</code> variable to signal a print action, and to add logic which will allow you to stop the printer thread on program exit:</p>
<pre><code>import time
from threading import Thread, Event
import keyboard
class PrintThread(Thread):
def __init__(self):
super().__init__()
self.stop = False
self.print = Event()
def run(self):
while not self.stop:
if self.print.wait(1):
print('Hi,', time.time())
def join(self, timeout=None):
self.stop = True
super().join(timeout)
</code></pre>
<p>Also, I'd suggest to move the blocking code out from the <code>KeyboadHook</code> initializer to a separate <code>start</code> method:</p>
<pre><code>class KeyboardHook:
def __init__(self):
self.printer = PrintThread()
self.set_keyboard_hotkeys()
def toggle_print(self):
print('Toggle the printer thread...')
if self.printer.print.is_set():
self.printer.print.clear()
else:
self.printer.print.set()
def set_keyboard_hotkeys(self):
print('Setting keyboard hotkeys...')
keyboard.add_hotkey('ctrl+p', self.toggle_print)
def start(self):
self.printer.start()
try:
keyboard.wait()
except KeyboardInterrupt:
pass
finally:
self.printer.join()
</code></pre>
<p>Run it like this:</p>
<pre><code>hook = KeyboardHook()
hook.start()
</code></pre>
<p>This code works for me like a charm.</p>
|
python|python-3.x|multithreading
| 1 |
1,902,369 | 63,498,117 |
how to handle timeout exception error using selenium webdriver
|
<p>I am coding a bot for <a href="http://www.kith.com" rel="nofollow noreferrer">www.kith.com</a> I have gotten past the card number and when I use the last 10 lines of code(name on card, expiration, security code)... I get this error,</p>
<p>"raise TimeoutException(message, screen, stacktrace)</p>
<p>TimeoutException'</p>
<p>before I added webdriver wait the code I was getting was <strong>init</strong> uses 3 arguments but 2 were given or something like that I'm relatively new to coding so this has kinda been a challenge.</p>
<pre><code> code:
driver = webdriver.Chrome(executable_path=r'C:\webdrivers\Chromedriver.exe')
driver.get(str(url))
#size
driver.find_element_by_xpath('//div[@data-value="S"]').click()
#ATC
driver.find_element_by_xpath('//button[@class="btn product-form__add-to-cart"]').click()
time.sleep(6)
#checkout
driver.find_element_by_xpath('//button[@class="btn ajaxcart__checkout"]').click()
time.sleep(3)
#email
driver.find_element_by_xpath('//input[@placeholder="Email"]').send_keys('example@gmail.com')
#first
driver.find_element_by_xpath('//input[@placeholder="First name"]').send_keys('first')
#last
driver.find_element_by_xpath('//input[@placeholder="Last name"]').send_keys('last')
#address
driver.find_element_by_xpath('//input[@placeholder="Address"]').send_keys('address')
#city
driver.find_element_by_xpath('//input[@placeholder="City"]').send_keys('town')
#zip
driver.find_element_by_xpath('//input[@placeholder="ZIP code"]').send_keys('99999')
#phone number
driver.find_element_by_xpath('//input[@placeholder="Phone"]').send_keys('9999999999' + u'\ue007')
time.sleep(5)
#continue to payment
driver.find_element_by_xpath('//button[@type="submit"]').click()
time.sleep(8)
#card number
driver.switch_to.frame(driver.find_element_by_class_name("card-fields-iframe"))
driver.find_element_by_id("number").send_keys('1234')
driver.find_element_by_id("number").send_keys('1234')
driver.find_element_by_id("number").send_keys('1234')
driver.find_element_by_id("number").send_keys('1234')
#payment
Exception(TimeoutException)
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[contains(@title,'Name on card')]")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@data-current-field]"))).send_keys('john')
driver.switch_to.default_content()
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[contains(@title,'Expiration date')]")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@data-current-field]"))).send_keys('11/23')
driver.switch_to.default_content()
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[contains(@title,'Security code')]")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@data-current-field]"))).send_keys('123')
driver.switch_to.default_content()
</code></pre>
<p>any suggestions would mean a lot to me. StackOverflow has helped me a ton so far. <3</p>
|
<p>Its look like you have issues with frames you are switching. Note as per your below line of code</p>
<pre><code> driver.switch_to.frame(driver.find_element_by_class_name("card-fields-iframe"))
</code></pre>
<p>You are inside frame <strong>card-fields-iframe</strong>, now as per below</p>
<pre><code> WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[contains(@title,'Expiration date')]")))
</code></pre>
<p>It will try to search for frame <strong>Expiration date</strong> inside <strong>card-fields-iframe</strong>. And so on for next two frames. I am not sure if your frames are cascaded like this. If these frames <strong>names on card</strong>, Expiry Date etc. are not inside each other, after performing your action please go to parent frame where all of these are tucked in.</p>
<pre><code>driver.driver.switch_to.parent_frame()
</code></pre>
<p><strong>Note :</strong> I am not sure which country you are doing your purchase. However I have done at my location (Singapore ) and able to click payment with below code. Please see for Singapore objects and frames are different from your location.</p>
<pre><code>driver.get("https://kith.com/collections/mens-apparel/products/mc8g75300v8162-984")
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//a[text()='Shop now']"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//span[contains(text(),'Add to Cart')]"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn ajaxcart__checkout']"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//a[text()='I ACCEPT COOKIES']"))).click()
WebDriverWait(driver, 30).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"Intrnl_CO_Container")))
WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, '//div[contains(text(),"Order Summary")]')))
# Buyer Details
driver.find_element_by_xpath('//input[@placeholder="First Name"]').send_keys('first')
driver.find_element_by_xpath('//input[@placeholder="Last Name"]').send_keys('last')
driver.find_element_by_xpath('//input[@placeholder="Email"]').send_keys('example@gmail.com')
driver.find_element_by_id('CheckoutData_BillingAddress1').send_keys('address')
driver.find_element_by_id('BillingCity').send_keys('town')
driver.find_element_by_id('BillingZIP').send_keys('999999')
driver.find_element_by_xpath('//input[@placeholder="Mobile Phone"]').send_keys('9999999999' + u'\ue007')
# card number
driver.switch_to.frame('secureWindow')
driver.find_element_by_id("cardNum").send_keys('5225517926810376')
month = Select(driver.find_element_by_id('cardExpiryMonth'))
year = Select(driver.find_element_by_id('cardExpiryYear'))
month.select_by_index(1)
year.select_by_index(4)
driver.find_element_by_id("cvdNumber").send_keys('124')
# Click on payment. Its not inside secure window Frame rather its under parent frame of it
driver.switch_to.parent_frame()
paybtn = driver.find_element_by_id('btnPay')
driver.execute_script("arguments[0].scrollIntoView();", paybtn)
paybtn.click()
</code></pre>
|
python|selenium|exception|automation|webdriver
| 2 |
1,902,370 | 63,717,357 |
mod_wsgi in apache not rendering html root properly
|
<p>I have the following python script that pulls in my index.html, which will eventually be split into a header.html, a footer.html and then python code will make up the body. How do I tell python to make the site directory the root directory for all html and html related files so css and the img folder render properly?</p>
<pre><code>#!/usr/bin/env python
import os
def application(environ, start_response):
status = '200 OK'
localpath = os.path.dirname(__file__)
index_file = 'index.html'
index_path = os.path.join(localpath, "adminUI", index_file)
with open(index_path, 'rb') as index:
output = index.read()
#output = b'Hello World!\n'
response_headers = [('Content-type', 'text/html'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
</code></pre>
|
<p>Never mind, adding Alias' to the virtual httpd.conf fixed the issue:</p>
<pre><code>Alias /img /usr/local/apache2/site/img
Alias ../vendors /usr/local/apache2/vendors
</code></pre>
|
python-3.x|apache|mod-wsgi
| 0 |
1,902,371 | 59,015,829 |
Need to replace specific line (1st line in the text) in with open & for loop
|
<p>I have an issue with a text file where I need to replace the 1st line from (Name 80010695) to (Name 80010695_05_76) noting I do the for loop as the (05_76) is changeable across the files.</p>
<p>When I use the append the write is removing all the txt then adding the needed txt. </p>
<p>What is needed is a syntax to write a specific line without removing any other.</p>
<pre class="lang-py prettyprint-override"><code>with open("D:/Upper - Sources/Antenna/OneDrive_1_11-21-2019/80010965/pattern/source.txt",'r')as source:
source_=source.readlines() #creating the source list of the antennas file names
for i in range(0,int(len(source_))):
source_[i]=source_[i].replace("\n","")
for L in source_: #creating the for loop to check all the names of the files that need edit
with open("D:/Upper - Sources/Antenna/OneDrive_1_11-21-2019/80010965/pattern/" + L,'a')as msi:
msi.writelines("Name " + L)
with open("D:/Upper - Sources/Antenna/OneDrive_1_11-21-2019/80010965/pattern/index.txt",'w')as index:
index.write(L+"\n")
</code></pre>
|
<p>Does this answer your question?</p>
<pre><code>with open ('index.txt', 'r') as f:
old_data = f.read()
new_data = old_data.replace('what_change', 'for_what_change')
with open ('index.txt', 'w') as f:
f.write(new_data)
</code></pre>
|
python
| 0 |
1,902,372 | 50,858,746 |
Ignore errors in pandas astype
|
<p>I have a numeric column that could contain another characters different form <strong>[0-9]</strong>. Say: <code>x = pandas.Series(["1","1.2", "*", "1", "**."])</code>.
Then I want to <b> convert </b> that serie into a numerical column using <code>x.astype(dtype = float, errors = 'ignore')</code> . I just can't figure out why Pandas keeps giving me an error despite the fact that I ask him not to! Is there something wrong with my code ?</p>
|
<p>I think you want to use <a href="http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.to_numeric.html" rel="noreferrer">pd.to_numeric(x, errors='coerce')</a> instead:</p>
<pre><code>In [73]: x = pd.to_numeric(x, errors='coerce')
In [74]: x
Out[74]:
0 1.0
1 1.2
2 NaN
3 1.0
4 NaN
dtype: float64
</code></pre>
<p>PS actually <code>x.astype(dtype = float, errors = 'ignore')</code> - works as expected, it doesn't give an error, it just leaves series as it is as it can't convert some elements:</p>
<pre><code>In [77]: x.astype(dtype = float, errors = 'ignore')
Out[77]:
0 1
1 1.2
2 *
3 1
4 **.
dtype: object # <----- NOTE!!!
In [81]: x.astype(dtype = float, errors = 'ignore').tolist()
Out[81]: ['1', '1.2', '*', '1', '**.']
</code></pre>
|
pandas
| 48 |
1,902,373 | 61,314,839 |
libtorch (PyTorch C++) weird class syntax
|
<p>In the official PyTorch C++ examples on GitHub <a href="https://github.com/pytorch/examples/blob/master/cpp/custom-dataset/custom-dataset.cpp" rel="noreferrer">Here</a>
you can witness a strange definition of a class:</p>
<pre><code>class CustomDataset : public torch::data::datasets::Dataset<CustomDataset> {...}
</code></pre>
<p>My understanding is that this defines a class <code>CustomDataset</code> which "inherits from" or "extends" <code>torch::data::datasets::Dataset<CustomDataset></code>. This is weird to me since the class we're creating is inheriting from another class which is parameterized by the class we're creating...How does this even work? What does it mean? This seems to me like an <code>Integer</code> class inheriting from <code>vector<Integer></code>, which seems absurd.</p>
|
<p>This is the <a href="https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="nofollow noreferrer">curiously-recurring template pattern</a>, or CRTP for short. A major advantage of this technique is that it enabled so-called <em>static polymorphism</em>, meaning that functions in <code>torch::data::datasets::Dataset</code> can call into functions of <code>CustomDataset</code>, without needing to make those functions virtual (and thus deal with the runtime mess of virtual method dispatch and so on). You can also perform compile-time metaprogramming such as compile-time <code>enable_if</code>s depending on the properties of the custom dataset type.</p>
<p>In the case of PyTorch, <a href="https://github.com/pytorch/pytorch/blob/master/torch/csrc/api/include/torch/data/datasets/base.h" rel="nofollow noreferrer"><code>BaseDataset</code></a> (the superclass of <code>Dataset</code>) uses this technique heavily to support operations such as mapping and filtering:</p>
<blockquote>
<pre><code> template <typename TransformType>
MapDataset<Self, TransformType> map(TransformType transform) & {
return datasets::map(static_cast<Self&>(*this), std::move(transform));
}
</code></pre>
</blockquote>
<p>Note the static cast of <code>this</code> to the derived type (legal as long as CRTP is properly applied); <code>datasets::map</code> constructs a <code>MapDataset</code> object which is also parametrized by the dataset type, allowing the <code>MapDataset</code> implementation to statically call methods such as <code>get_batch</code> (or encounter a <em>compile-time</em> error if they do not exist). </p>
<p>Furthermore, since <code>MapDataset</code> receives the custom dataset type as a type parameter, compile-time metaprogramming is possible:</p>
<blockquote>
<pre><code> /// The implementation of `get_batch()` for the stateless case, which simply
/// applies the transform to the output of `get_batch()` from the dataset.
template <
typename D = SourceDataset,
typename = torch::disable_if_t<D::is_stateful>>
OutputBatchType get_batch_impl(BatchRequestType indices) {
return transform_.apply_batch(dataset_.get_batch(std::move(indices)));
}
/// The implementation of `get_batch()` for the stateful case. Here, we follow
/// the semantics of `Optional.map()` in many functional languages, which
/// applies a transformation to the optional's content when the optional
/// contains a value, and returns a new optional (of a different type) if the
/// original optional returned by `get_batch()` was empty.
template <typename D = SourceDataset>
torch::enable_if_t<D::is_stateful, OutputBatchType> get_batch_impl(
BatchRequestType indices) {
if (auto batch = dataset_.get_batch(std::move(indices))) {
return transform_.apply_batch(std::move(*batch));
}
return nullopt;
}
</code></pre>
</blockquote>
<p>Notice that the conditional enable is dependent on <code>SourceDataset</code>, which we only have available because the dataset is parametrized with this CRTP pattern.</p>
|
c++|pytorch|libtorch
| 9 |
1,902,374 | 55,302,325 |
simple web scraper very slow
|
<p>I'm fairly new to python and web-scraping in general. The code below works but it seems to be awfully slow for the amount of information its actually going through. Is there any way to easily cut down on execution time. I'm not sure but it does seem like I have typed out more/made it more difficult then I actually needed to, any help would be appreciated. </p>
<p>Currently the code starts at the sitemap then iterates through a list of additional sitemaps. Within the new sitemaps it pulls data information to construct a url for the json data of a webpage. From the json data I pull an xml link that I use to search for a string. If the string is found it appends it to a text file.</p>
<pre><code>#global variable
start = 'https://www.govinfo.gov/wssearch/getContentDetail?packageId='
dash = '-'
urlSitemap="https://www.govinfo.gov/sitemap/PLAW_sitemap_index.xml"
old_xml=requests.get(urlSitemap)
print (old_xml)
new_xml= io.BytesIO(old_xml.content).read()
final_xml=BeautifulSoup(new_xml)
linkToBeFound = final_xml.findAll('loc')
for loc in linkToBeFound:
urlPLmap=loc.text
old_xmlPLmap=requests.get(urlPLmap)
print(old_xmlPLmap)
new_xmlPLmap= io.BytesIO(old_xmlPLmap.content).read()
final_xmlPLmap=BeautifulSoup(new_xmlPLmap)
linkToBeFound2 = final_xmlPLmap.findAll('loc')
for pls in linkToBeFound2:
argh = pls.text.find('PLAW')
theWanted = pls.text[argh:]
thisShallWork =eval(requests.get(start + theWanted).text)
print(requests.get(start + theWanted))
dict1 = (thisShallWork['download'])
finaldict = (dict1['modslink'])[2:]
print(finaldict)
url2='https://' + finaldict
try:
old_xml4=requests.get(url2)
print(old_xml4)
new_xml4= io.BytesIO(old_xml4.content).read()
final_xml4=BeautifulSoup(new_xml4)
references = final_xml4.findAll('identifier',{'type': 'Statute citation'})
for sec in references:
if sec.text == "106 Stat. 4845":
Print(dash * 20)
print(sec.text)
Print(dash * 20)
sec313 = open('sec313info.txt','a')
sec313.write("\n")
sec313.write(pls.text + '\n')
sec313.close()
except:
print('error at: ' + url2)
</code></pre>
|
<p>No idea why i spent so long on this, but i did. Your code was really hard to look through. So i started with that, I broke it up into 2 parts, getting the links from the sitemaps, then the other stuff. I broke out a few bits into separate functions too.
This is checking about 2 urls per second on my machine which seems about right.
How this is better (you can argue with me about this part).</p>
<ul>
<li>Don't have to reopen and close the output file after each write</li>
<li>Removed a fair bit of unneeded code</li>
<li>gave your variables better names (this does not improve speed in any way but please do this especially if you are asking for help with it)</li>
<li>Really the main thing... once you break it all up it becomes fairly clear that whats slowing you down is waiting on the requests which is pretty standard for web-scraping, you can look into multi threading to avoid the wait. Once you get into multi threading, the benefit of breaking up your code will likely also become much more evident.</li>
</ul>
<pre><code># returns sitemap links
def get_links(s):
old_xml = requests.get(s)
new_xml = old_xml.text
final_xml = BeautifulSoup(new_xml, "lxml")
return final_xml.findAll('loc')
# gets the final url from your middle url and looks through it for the thing you are looking for
def scrapey(link):
link_id = link[link.find("PLAW"):]
r = requests.get('https://www.govinfo.gov/wssearch/getContentDetail?packageId={}'.format(link_id))
print(r.url)
try:
r = requests.get("https://{}".format(r.json()["download"]["modslink"][2:]))
print(r.url)
soup = BeautifulSoup(r.text, "lxml")
references = soup.findAll('identifier', {'type': 'Statute citation'})
for ref in references:
if ref.text == "106 Stat. 4845":
return r.url
else:
return False
except:
print("bah" + r.url)
return False
sitemap_links_el = get_links("https://www.govinfo.gov/sitemap/PLAW_sitemap_index.xml")
sitemap_links = map(lambda x: x.text, sitemap_links_el)
nlinks_el = map(get_links, sitemap_links)
links = [num.text for elem in nlinks_el for num in elem]
with open("output.txt", "a") as f:
for link in links:
url = scrapey(link)
if url is False:
print("no find")
else:
print("found on: {}".format(url))
f.write("{}\n".format(url))
</code></pre>
|
python|web-scraping
| 1 |
1,902,375 | 57,469,877 |
Create deterministic graph with networkx
|
<p>I've created a networkx static graph using the following code:</p>
<pre><code> G = nx.Graph()
G.add_edges_from(edges)
pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos,node_size=6000, cmap="jet")
nx.draw_networkx_labels(G, pos, labels, font_size=11)
nx.draw_networkx_edges(G, pos, edge_color='b', alpha = 1, arrows=True)
plt.show()
</code></pre>
<p>Running this multiple times on the same structure, I get different results (these results change every time I run it too):</p>
<p><a href="https://i.stack.imgur.com/0aYcq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0aYcq.png" alt="enter image description here"></a></p>
<p>I want to be able to use the same graph each time but only change the labels so I can see what is going on. How can I do this?</p>
|
<p>According to the <a href="https://networkx.github.io/documentation/latest/reference/generated/networkx.drawing.layout.spring_layout.html" rel="nofollow noreferrer">docs</a>, <code>nx.spring_layout</code> takes an optional <code>seed</code> argument which allows you to seed the underlying random number generator. Try:</p>
<pre class="lang-py prettyprint-override"><code>pos = nx.spring_layout(G, seed=1)
</code></pre>
|
python|networkx
| 3 |
1,902,376 | 39,900,010 |
Wanting to get an output and run a programme together with Tkinter
|
<p>What I want to be able to do is run a list of MIDI files, I have the programme to list them out and play them...</p>
<pre><code>import os,fnmatch,pygame
pygame.mixer.init()
List = []
Song = 0
def Update():
List = []
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.mid'):
List.append(file)
return List
List = Update()
while True:
while Song <= len(List):
pygame.mixer.music.load(List[Song])
pygame.mixer.music.play(1)
while pygame.mixer.music.get_busy() == True:
List = Update()
Song = Song + 1
Song = 0
</code></pre>
<p>This currently works with .mid files that it is in the same folder as, however I want to implement a slider with the programme to control the volume, I also have that code already...</p>
<pre><code>from Tkinter import *
master = Tk()
def getThrottle(event):
Volume = Throttle.get()
Throttle = Scale(master, from_=0, to=100, tickinterval=10, length=200, orient=HORIZONTAL, command=getThrottle)
Throttle.set(0)
Throttle.pack()
mainloop()
</code></pre>
<p>What I want to know is how I can make both programmes run at the same time with a single variable global between both with that variable being Volume</p>
|
<p>Nevermind, I discovered how to run both a tkinter window and music at the same time, however a new problem is that the tkinter window is blank.</p>
<p>New question is "<a href="https://stackoverflow.com/questions/39976875/why-is-the-tkinter-window-blank">Why is the tkinter window blank?</a>"</p>
|
python-2.7|tkinter|python-multithreading
| 0 |
1,902,377 | 47,518,902 |
Created Nested JSON Instead of Separate JSON
|
<p>So I have a small script the output of which I want to store as a JSON Object. Here is the script:</p>
<pre><code>import dns.resolver
import json
def get(domain):
ids = [
'CNAME',
'A',
'NS',
]
for _iter in ids:
try:
inf = dns.resolver.query(domain, _iter)
response_dict["Domain"] = domain
for _resp in inf:
print(_iter, ':', _resp.to_text())
response_dict[_iter] = _resp.to_text()
except Exception as e:
print(e)
# dump information as a JSON file. 'a' to append file.
with open('data.txt', 'a') as outfile:
json.dump(response_dict, outfile)
print(response_dict)
if __name__ == "__main__":
response_dict = dict()
get("apple.com")
get("google.com")
</code></pre>
<p>Now the output of this generates separate objects in JSON as viz.</p>
<pre><code>{"Domain": "apple.com", "A": "17.178.96.59", "NS": "b.ns.apple.com."}
{"Domain": "google.com", "A": "172.217.21.238", "NS": "ns3.google.com."}
</code></pre>
<p>What I actually want is:</p>
<p><a href="https://i.stack.imgur.com/84AiR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/84AiR.png" alt="JSON"></a></p>
<p>How can this be achieved? Thanks!</p>
|
<p>Instead of appending to the file with each call to <code>get()</code>, append the results to a list and dump at the end. Also don't define <code>response_dict</code> in <code>__main__</code>.</p>
<pre><code>import dns.resolver
import json
def get(domain):
ids = [
'CNAME',
'A',
'NS',
]
response_dict = {}
for _iter in ids:
try:
inf = dns.resolver.query(domain, _iter)
response_dict["Domain"] = domain
for _resp in inf:
print(_iter, ':', _resp.to_text())
response_dict[_iter] = _resp.to_text()
except Exception as e:
print(e)
print(response_dict)
return response_dict # return a value
if __name__ == "__main__":
response_list = []
# append each output of get() to this list
response_list.append(get("apple.com"))
response_list.append(get("google.com"))
# write the list to a file
with open('data.txt', 'a') as outfile:
json.dump(response_list, outfile)
</code></pre>
|
python|json
| 2 |
1,902,378 | 43,410,635 |
to get the integer value after : and subtract it from the next value
|
<p>I have text file like this and I need to get the integer from each line like 246012 and subtract it from the next line's integer using python</p>
<pre><code>[739:246012] PHYThrad: DSPMsgQ Received: msg type is[130] and SFNSF [14996] [SFN:937 SF:4]
[739:246050] START of MACThread:receved msg type[47]
[739:247021] PHYThrad: DSPMsgQ Received: msg type is[130] and SFNSF [14997] [SFN:937 SF:5]
[739:247059] START of MACThread:receved msg type[47]
[739:248013] PHYThrad: DSPMsgQ Received: msg type is[130] and SFNSF [14998] [SFN:937 SF:6]
[739:248053] START of MACThread:receved msg type[47]
</code></pre>
|
<p>This should do the trick:</p>
<pre><code>with open('myfile.txt') as a:
a = a.readlines()
nums = [int(lines[lines.find(':')+1:lines.find(']')]) for lines in a]
result = [y - x for x, y in zip(nums, nums[1:])]
print result
</code></pre>
|
python-2.7
| 0 |
1,902,379 | 70,447,464 |
Total label for stacked bar
|
<p>I have the following code:</p>
<pre><code>fig, ax = plt.subplots()
single_customer_g['Size_GB'] = round(single_customer_g['Size_GB'] / 1024, 2)
single_customer_g = single_customer_g.pivot('Date', 'Vault', 'Size_GB')
single_customer_g.plot.bar(stacked=True, rot=1, figsize=(15, 10), ax=ax, zorder=3)
for c in ax.containers:
labels = [round(v.get_height(), 2) if v.get_height() > 0 else 0 for v in c]
ax.bar_label(c, labels=labels, label_type='center')
</code></pre>
<p>I am trying to add total figure as a label on top of each column, but just can't figure it out. i tried multiple examples, and nothing is working so far.</p>
|
<p>By default, the function <code>bar_label()</code> uses the sum of the bar height and its bottom (<code>.get_y()</code>) as the number shown on top (only the height for the centered labels). You only want to call this for the last set of bars shown (so <code>ax.containers[-1]</code>).</p>
<p>Here is an example:</p>
<pre class="lang-py prettyprint-override"><code>from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({'Date': np.tile(pd.date_range('20211201', freq='D', periods=10), 5),
'Vault': np.repeat([*'abcde'], 10),
'Size_GB': np.random.uniform(0, 3, 50)})
df_pivoted = df.pivot('Date', 'Vault', 'Size_GB')
ax = df_pivoted.plot.bar(stacked=True, figsize=(12, 5))
ax.set_xticklabels([d.strftime('%b %d\n%Y') for d in df_pivoted.index], rotation=0)
ax.bar_label(ax.containers[-1], fmt='%.2f') # default on top
for bars in ax.containers:
labels = [f"{bar.get_height():.2f}" if bar.get_height() > 0.2 else '' for bar in bars]
ax.bar_label(bars, labels=labels, label_type='center', color='white')
ax.set_xlabel('')
plt.tight_layout()
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/CyWf8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CyWf8.png" alt="pandas stacked bar with total labels" /></a></p>
|
python|pandas|matplotlib
| 2 |
1,902,380 | 73,126,437 |
My code seems not to be printing nothing on streamlit but it works good on jupiter
|
<p>Here is my code:</p>
<pre class="lang-py prettyprint-override"><code>def month_year(d):
m, y = d
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
return months[m - 1] + '-' + str(y % 100)
ax2 = new_df['Average_Answer_Speed'].plot(kind='bar', stacked=True, figsize=(15,10))
plt.xticks(rotation = 45)
ax2.set_title('Average Call Answer Speed in Seconds', fontsize = 18, fontweight = "bold")
ax2.set_xlabel('')
for p in ax2.patches:
ax2.annotate(f'{int(round(p.get_height()))}', (p.get_x() + p.get_width() / 2., p.get_height() / 2), ha='center', va='center', xytext=(0, 10), textcoords='offset points', color='white')
plt.show()
</code></pre>
<p>Do I need to use something else instead of <code>plt</code> show ? so it work on streamlit?</p>
|
<p><strong><code>plt.show()</code></strong> will show output on a different window, use <strong><code>st.write(ax2)</code></strong> instead</p>
<pre class="lang-py prettyprint-override"><code>import streamlit as st
ax2 = new_df['Average_Answer_Speed'].plot(kind='bar', stacked=True, figsize=(15,10))
plt.xticks(rotation = 45)
ax2.set_title('Average Call Answer Speed in Seconds', fontsize = 18, fontweight = "bold")
ax2.set_xlabel('')
for p in ax2.patches:
ax2.annotate(f'{int(round(p.get_height()))}', (p.get_x() + p.get_width() / 2., p.get_height() / 2), ha='center', va='center', xytext=(0, 10), textcoords='offset points', color='white')
st.write(ax2)
# plt.show()
</code></pre>
|
python|matplotlib|streamlit
| 2 |
1,902,381 | 72,993,290 |
How do I include an output file when I convert a .py file to .exe using Pyinstaller?
|
<p>I have a Python script that looks like</p>
<pre><code>path = os.path.join(os.path.dirname(sys.executable), 'data.txt')
file = open(path, 'w')
file.write("something")
file.close()
</code></pre>
<p>When I use Pyinstaller (with the option <code>--onefile</code>), and open the resulting .exe-file, it does not seem to do anything. In particular, I cannot find a data.txt file. How do I fix this?</p>
|
<p><code>os.path.dirname(sys.executable)</code> would point at the directory where Python.exe is if you were not running under Pyinstaller, and it's unlikely you'd want to write there. It's likely that under PyInstaller, it's some temporary directory.</p>
<p>Instead, just <code>'data.txt'</code> (or <code>os.path.join(os.getcwd(), 'data.txt')</code> if you want to be pedantic) would create the file in the program's current <a href="https://en.wikipedia.org/wiki/Working_directory" rel="nofollow noreferrer">working directory</a>, which, if you just double-click on the EXE, would be the EXE's directory.</p>
|
python|output|pyinstaller|exe
| 2 |
1,902,382 | 55,878,540 |
Getting different hash digest values for the same string when using hash functions in a list
|
<p>I seem to be getting different digest values for the same word in my program. I am not sure this is because I am keeping the hash functions in a list (So I can add to the list)</p>
<p>When I use direct hash functions the hash digest is the same for the same word. It is different when I use the hashes from inside a list. What am I doing wrong ?</p>
<p>What is working </p>
<pre class="lang-py prettyprint-override"><code>import hashlib
bloom_len = 100
def bytes_to_int(hash_value):
return int.from_bytes(hash_value, byteorder='big') #big-endiang format
def bloom_index(hashint):
return hashint % bloom_len
def hashIt(word):
m1 = hashlib.md5()
m2 = hashlib.sha1()
m3 = hashlib.sha256()
m4 = hashlib.sha3_512()
m5 = hashlib.blake2s()
m1.update(word)
m2.update(word)
m3.update(word)
m4.update(word)
m5.update(word)
hash_values = [m1.digest(), m2.digest(), m3.digest(), m4.digest(), m5.digest()]
hashints = list(map(bytes_to_int, hash_values))
indices = list(map(bloom_index, hashints))
print(indices)
inputWord = 'sent'
word = inputWord.encode('utf-8')
hashIt(word)
inputWord = 'blue'
word = inputWord.encode('utf-8')
hashIt(word)
inputWord = 'sent'
word = inputWord.encode('utf-8')
hashIt(word)
</code></pre>
<p>What is NOT working </p>
<pre class="lang-py prettyprint-override"><code>import hashlib
class BloomFilter():
def __init__(self, length = 100):
self.bloomFilterLen = length
self.bloomFilterArray = [0] * self.bloomFilterLen
m1 = hashlib.md5()
m2 = hashlib.sha3_512()
m3 = hashlib.blake2s()
self.hashes = [m1, m2, m3]
def encode(self, inputWord):
encoded_word = inputWord.encode('utf-8')
return encoded_word
def bytes_to_int(self, hash_value):
return int.from_bytes(hash_value, byteorder='big')
def bloom_index(self, hashint):
return hashint % self.bloomFilterLen
def getIndices(self, inputWord):
word = self.encode(inputWord)
print(word)
hashDigests = []
for hashFunction in self.hashes:
hashFunction.update(word)
print('hashFunction ', hashFunction , '\n')
print('hashDigest ', hashFunction.digest() , '\n')
hashDigests.append(hashFunction.digest())
hashInts = [self.bytes_to_int(h) for h in hashDigests]
#print('hashInts ', hashInts)
bloomFilterIndices = [self.bloom_index(hInt) for hInt in hashInts]
return bloomFilterIndices
def insert(self, inputWord):
bloomFilterIndices = self.getIndices(inputWord)
for index in bloomFilterIndices:
self.bloomFilterArray[index] = 1
print(bloomFilterIndices)
def lookup(self, inputWord):
bloomFilterIndices = self.getIndices(inputWord)
print('Inside lookup')
print(bloomFilterIndices)
for idx in bloomFilterIndices:
print('idx value ', idx)
print('self.bloomFilterArray[idx] value ', self.bloomFilterArray[idx])
if self.bloomFilterArray[idx] == 0:
# Indicates word not present in the bloom filter
return False
return True
if __name__ == '__main__':
word = 'sent'
bloomFilter = BloomFilter()
bloomFilter.insert(word)
print(bloomFilter.lookup(word))
</code></pre>
<p>From the first program - I consistently get same integer indices</p>
<ul>
<li>Indices for '<strong>sent</strong>'</li>
</ul>
<p><code>[61, 82, 5, 53, 87]</code></p>
<ul>
<li>Indices for '<strong>blue</strong>'</li>
</ul>
<p><code>[95, 25, 24, 69, 85]</code></p>
<ul>
<li>Indices for '<strong>sent</strong>'</li>
</ul>
<p><code>[61, 82, 5, 53, 87]</code></p>
<p>For the non-working program the integer indices are different and when I printed out the hash digest is different</p>
<ul>
<li>Indices for '<strong>sent</strong>' - first time via add</li>
</ul>
<p><code>[61, 53, 87]</code></p>
<p><code>HashDigest</code> from <code>MD5</code> for '<strong>sent</strong>'</p>
<blockquote>
<p>hashDigest b'x\x91\x83\xb7\xe9\x86F\xc1\x1d_\x05D\xc8\xf3\xc4\xc9'</p>
</blockquote>
<ul>
<li>Indices for '<strong>sent</strong>' - second time via <code>lookup</code></li>
</ul>
<p><code>[70, 89, 8]</code></p>
<p><code>HashDigest</code> from <code>MD5</code> for '<strong>sent</strong>'</p>
<blockquote>
<p>hashDigest b'\x95\x17bC\x17\x80\xb5\x9d]x\xca$\xda\x89\x06\x16'</p>
</blockquote>
|
<p>So I changed the code in __init __</p>
<p>From </p>
<pre><code>m1 = hashlib.md5()
m2 = hashlib.sha3_512()
m3 = hashlib.blake2s()
self.hashes = [m1, m2, m3]
</code></pre>
<p>To</p>
<pre><code>self.hashes = ['md5', 'sha3_512', 'blake2s']
</code></pre>
<p>And then inside the for loop in method getIndices()</p>
<p>Changed from </p>
<pre><code> for hashFunction in self.hashes:
hashFunction.update(word)
</code></pre>
<p>To</p>
<pre><code>for hashName in self.hashes:
hashFunction = hashlib.new(hashName)
hashFunction.update(word)
</code></pre>
<p>Works now !</p>
|
python|hashlib
| 0 |
1,902,383 | 50,202,168 |
Access data within tupples
|
<p>I have a list of tupples like so:</p>
<pre><code> tupples=[(41, 'Mike'), (29, 'Tom'), (28, 'Sarah'), (22, 'Jane'), (18, 'John']
</code></pre>
<p>The ints are ages of the individuals and the strings are their names. The tupples are ordered by the individials age on purpose.</p>
<p>I understand list indexes work here. So if I want to access the first tupple then:</p>
<pre><code> tupples[0]
</code></pre>
<p>will access </p>
<pre><code> (41, 'Mike')
</code></pre>
<p>How do I access the values within the tupples?</p>
<p>I would like to loop through the tupple and print:
"They are" AGE "years old, and their name is" NAME. </p>
<p>So for tupples[0] it would look like:</p>
<pre><code> "They are" 41 "years old, and their name is" Mike.
</code></pre>
|
<p>You can use <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow noreferrer">sequence unpacking</a> like:</p>
<pre><code>data = [(41, 'Mike'), (29, 'Tom'), (28, 'Sarah'),
(22, 'Jane'), (18, 'John')]
for age, name in data:
print("They are {} years old, and their name is {}.".format(age, name))
</code></pre>
<p>Or you can access the elements in the tuple as <code>[0]</code> and <code>[1]</code> like:</p>
<pre><code>for datum in data:
print("They are {} years old, and their name is {}.".format(datum[0], datum[1]))
</code></pre>
<p>Or you can use <a href="https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow noreferrer">argument unpacking</a> like:</p>
<pre><code>for datum in data:
print("They are {} years old, and their name is {}.".format(*datum))
</code></pre>
|
python|list
| 2 |
1,902,384 | 50,141,002 |
finding non matching records in pandas
|
<p>I would like to identify if a set of records is not represented by a distinct list of values; so in this example of: </p>
<pre><code>raw_data = {
'subject_id': ['1', '2', '3', '4', '5'],
'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches'],
'sport' : ['soccer','soccer','soccer','soccer','soccer']}
df_a = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name', 'last_name','sport'])
raw_data = {
'subject_id': ['9', '5', '6', '7', '8'],
'first_name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'last_name': ['Bonder', 'Black', 'Balwner', 'Brice', 'Btisan'],
'sport' : ['soccer','soccer','soccer','soccer','soccer']}
df_b = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name', 'last_name','sport'])
raw_data = {
'subject_id': ['9', '5', '6', '7'],
'first_name': ['Billy', 'Brian', 'Bran', 'Bryce'],
'last_name': ['Bonder', 'Black', 'Balwner', 'Brice'],
'sport' : ['football','football','football','football']}
df_c = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name', 'last_name','sport'])
raw_data = {
'subject_id': ['1', '3', '5'],
'first_name': ['Alex', 'Allen', 'Ayoung'],
'last_name': ['Anderson', 'Ali', 'Atiches'],
'sport' : ['football','football','football']}
df_d = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name', 'last_name','sport'])
frames = [df_a,df_b,df_c,df_d]
frame = pd.concat(frames)
frame = frame.sort_values(by='subject_id')
raw_data = {
'sport':['soccer','football','softball']
}
sportlist = pd.DataFrame(raw_data,columns=['sport'])
</code></pre>
<p>Desired output: I would like to get a list of first_name and last_name pairs that do not play football. And also I would like be able to return a list of all the records since softball is not represented in the original list.</p>
<p>I tried using merge with how= outer, indicator=True options but since there is a record that plays soccer there is a match. And the '_right_only' yields no records since it was not populated in the original data.</p>
<p>Thanks,
aem</p>
|
<p>If you only want to get the names of people who do not play football all you need to do is:</p>
<pre><code>frame[frame.sport != 'football']
</code></pre>
<p>Which would select only those persons who are not playing football.</p>
<p>If it has to be a list you can further call <code>to_records(index=False)</code></p>
<pre><code>frame[frame.sport != 'football'][['first_name', 'last_name']].to_records(index=False)
</code></pre>
<p>which returns a list of tuples:</p>
<pre><code>[('Alex', 'Anderson'), ('Amy', 'Ackerman'), ('Allen', 'Ali'),
('Alice', 'Aoni'), ('Brian', 'Black'), ('Ayoung', 'Atiches'),
('Bran', 'Balwner'), ('Bryce', 'Brice'), ('Betty', 'Btisan'),
('Billy', 'Bonder')]
</code></pre>
|
python-3.x|pandas
| 0 |
1,902,385 | 66,621,746 |
Text based adventure challenge issues
|
<p>I'm new at coding and I've been trying this <strong>text-based adventure game</strong>. I keep running into syntax error and I don't seem to know how to solve this. Any suggestions on where I could have gone wrong would go a long way to helping.</p>
<pre><code>
def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
def game_over(reason):
print("\n", reason)
print("Game Over!!!")
play_again()
def diamond_room():
print("\nYou are now in the room filled with diamonds")
print("what would you like to do?")
print("1) pack all the diamonds")
print("2) Go through the door")
answer = input(">")
if answer == "1":
game_over("The building collapsed bcos the diamonds were cursed!")
elif answer == "2":
print("You Win!!!")
play_again()
else:
game_over("Invalid prompt!")
def monster_room():
print("\nYou are now in the room of a monster")
print("The monster is sleeping and you have 2 choices")
print("1) Go through the door silently")
print("2) Kill the monster and show your courage")
answer = input(">")
if answer == "1":
diamond_room()
elif answer == "2":
game_over("You are killed")
else:
game_over("Invalid prompt")
def bear_room():
print("\nThere's a bear in here!")
print("The bear is eating tasty honey")
print("what would you like to do?")
print("1) Take the honey")
print("2) Taunt the bear!")
answer = input(">").lower()
if answer == "1":
game_over("The bear killed you!!!")
elif answer == "2":
print("The bear moved from the door, you can now go through!")
diamond_room()
else:
game_over("Invalid prompt")
def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
start()
</code></pre>
<p>it keeps popping error and i cant detect where the error is coming from.</p>
|
<p>You have 2 problems.</p>
<ol>
<li>Assertion instead of Assignment.</li>
<li>Calling the wrong function.</li>
</ol>
<p>For 1. You have</p>
<pre><code>def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
</code></pre>
<p>You should uuse <code>answer = input(">")</code> and not <code>answer ==</code>.</p>
<p>For 2. You have</p>
<pre><code>def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
</code></pre>
<p>You should call <code>start</code> not <code>play_again</code></p>
|
python|python-3.x
| 0 |
1,902,386 | 64,994,760 |
Preserve YAML files with only comments when formatting using ruamel.yaml?
|
<p>I'd like to preserve comments in YAML files with only comments. With my current setup, ruamel.yaml outputs null upon formatting such a file. Is there a good way to do this? Here is what I have so far:</p>
<pre><code>from ruamel.yaml import YAML
def round_trip(sout, sin, idt):
yaml = YAML()
assert idt >= 2
yaml.indent(mapping=idt, sequence=idt, offset=idt-2)
yaml.preserve_quotes = True
data = yaml.load(sin)
if data is not None:
yaml.dump(data, sout)
else:
print("the file is empty") # needs fixing: should dump original file
</code></pre>
|
<p>The comments are not preserved as there is no location on your instance <code>data</code>
to put them. In round-trip mode <code>ruamel.yaml</code> doesn't create normal Python
dicts/lists from YAML mappings/sequences, but subclasses thereof
(<code>CommentedMap</code>/<code>CommentedSeq</code>) and attaches comments indexed by the previous
element in those container. At the same time, dunder methods like <code>__get__()</code>
allow for (most) normal use of these containers to use and or modify them in
your program and then dump them.</p>
<p><code>ruamel.yaml</code> does subclass strings, integers, floats (and to some extend
booleans) to preserve information on quotes, exponentials, base, any
anchor, etc. that may occur in your YAML. But if comments would be
attached to a scalar, instead of the container of which it is a value or
element, would result in loss of that comment on assignment of a new value. That
is if you have YAML:</p>
<pre><code>a: 18 # soon to be 55
b: 42
</code></pre>
<p>load that into <code>data</code> and do <code>data['a'] = 55</code> your comment would be lost. It am
not sure if this behaviour can be improved upon, by making the container
smarter, that is worth investigating, but only if such a scalar is part of mapping/sequence.</p>
<p>Apart from that <code>None</code> cannot be subclassed, so there is no place to attach
comments. Booleans cannot be subclassed either, but to preserve anchors <code>ruamel.yaml</code>
constructs booleans as a subclass of <code>int</code>, which allows for normal usage e.g. in
<code>if</code> statements testing for the truth value. A typical usage for <code>None</code>
however is testing for identity (using `... is None``) and AFAIK there is no way to fake that.</p>
<p>So there is no way for <code>.load()</code> to give you something back that has the comment
information. But you do yave the <code>YAML()</code> instance and IMO it is best to
subclass that to preserve the comment information. It currently stores some
information about the last loaded document, e.g. the documents YAML version
directive if provided (<code>%YAML 1.1</code>)</p>
<pre><code>import sys
import ruamel.yaml
yaml_str = """\
# this document is, by default,
# round-tripped to null
"""
class YAML(ruamel.yaml.YAML):
def load(self, stream):
if not hasattr(stream, 'read') and hasattr(stream, 'open'):
# pathlib.Path() instance
data = super().load(stream)
if data is None:
buf = stream.read_text()
elif isinstance(stream, str):
data = super().load(stream)
buf = stream
else: # buffer stream data
buf = stream.read()
data = super().load(buf)
if data is None and buf.strip():
self._empty_commented_doc = buf
return data
def dump(self, data, stream=None, transform=None):
# dump to stream or Path
if not hasattr(self, '_empty_commented_doc'): # the simple case
return super().dump(data, stream=stream, transform=transform)
# doesn't handle transform
if not hasattr(stream, 'read') and hasattr(stream, 'open'):
with stream.open('w') as fp:
fp.write(self._empty_commented_doc)
super().dump(data, stream)
else:
stream.write(self._empty_commented_doc)
if data is not None:
super().dump(data, stream)
yaml = YAML()
# yaml.indent(mapping=4, sequence=4, offset=2)
# yaml.preserve_quotes = True
data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)
data = True
print('----------------')
yaml.dump(data, sys.stdout)
</code></pre>
<p>which gives:</p>
<pre><code># this document is, by default,
# round-tripped to null
----------------
# this document is, by default,
# round-tripped to null
true
...
</code></pre>
<hr />
<sup>
The above could be extended to handle root level scalar documents as well, and
I'm considering adding a more complete implementation to ruamel.yaml.</sup>
|
python|yaml|ruamel.yaml
| 1 |
1,902,387 | 53,184,547 |
Why can't I get the output for this code?
|
<p>Why can't I get the output for this code?,</p>
<pre><code>def armstrong(lower,higher):
for num in range(lower, higher+1):
order=len(str(num))
sum=0
temp = num
while temp >0:
digit=temp%10
sum += digit**order
temp//=10
if num == temp:
return num
lower=int(input('lower number: '))
higher=int(input('higher number: '))
armstrong(lower,higher)
</code></pre>
|
<p>There are few logic erros in the code, I've fixed them and added comments to show exactly where. </p>
<pre><code>def armstrong(lower,higher):
result_list = [] # define a result list
for num in range(lower, higher+1):
order=len(str(num))
total = 0 # Do not use sum as it is python keyword
temp = num
while temp != 0:
digit=temp%10
total += digit**order # change the variable name
temp//=10
if num == total: # Check with total instead of temp
result_list.append(num) # append to a list instead of returning
return result_list # return the total list after all results are collected.
lower=int(input('lower number: '))
higher=int(input('higher number: '))
output = armstrong(lower,higher) # store the output of the function
print(output)
</code></pre>
<p>Outputs:</p>
<pre><code>lower number: 100
higher number: 500
[153, 370, 371, 407]
</code></pre>
|
python-3.x
| 0 |
1,902,388 | 65,233,123 |
Adding percentage of count to a stacked bar chart in plotly
|
<p>Given the following chart created in plotly.
<a href="https://i.stack.imgur.com/yCNPd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yCNPd.png" alt="enter image description here" /></a></p>
<p>I want to add the percentage values of each count for M and F categories inside each block.</p>
<p>The code used to generate this plot.</p>
<pre class="lang-py prettyprint-override"><code>arr = np.array([
['Dog', 'M'], ['Dog', 'M'], ['Dog', 'F'], ['Dog', 'F'],
['Cat', 'F'], ['Cat', 'F'], ['Cat', 'F'], ['Cat', 'M'],
['Fox', 'M'], ['Fox', 'M'], ['Fox', 'M'], ['Fox', 'F'],
['Dog', 'F'], ['Dog', 'F'], ['Cat', 'F'], ['Dog', 'M']
])
df = pd.DataFrame(arr, columns=['A', 'G'])
fig = px.histogram(df, x="A", color='G', barmode="stack")
fig.update_layout(height=400, width=800)
fig.show()
</code></pre>
|
<p>As far as I know histograms in Plotly don't have a text attribute. But you could generate the bar chart yourself and then add the percentage via the text attribute.</p>
<pre><code>import numpy as np
import pandas as pd
import plotly.express as px
arr = np.array([
['Dog', 'M'], ['Dog', 'M'], ['Dog', 'F'], ['Dog', 'F'],
['Cat', 'F'], ['Cat', 'F'], ['Cat', 'F'], ['Cat', 'M'],
['Fox', 'M'], ['Fox', 'M'], ['Fox', 'M'], ['Fox', 'F'],
['Dog', 'F'], ['Dog', 'F'], ['Cat', 'F'], ['Dog', 'M']
])
df = pd.DataFrame(arr, columns=['A', 'G'])
df_g = df.groupby(['A', 'G']).size().reset_index()
df_g['percentage'] = df.groupby(['A', 'G']).size().groupby(level=0).apply(lambda x: 100 * x / float(x.sum())).values
df_g.columns = ['A', 'G', 'Counts', 'Percentage']
px.bar(df_g, x='A', y=['Counts'], color='G', text=df_g['Percentage'].apply(lambda x: '{0:1.2f}%'.format(x)))
</code></pre>
<p><a href="https://i.stack.imgur.com/E4cYG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/E4cYG.png" alt="enter image description here" /></a></p>
|
python|plotly|data-visualization|plotly-dash|plotly-python
| 12 |
1,902,389 | 71,988,651 |
Django not redirecting to the web page
|
<p>I am creating a messaging application in django with a built-in DLP system. I want to redirect to a web page when a sensitive word is detected in the message. But the webpage is not being redirected to. It is showing in the terminal but not on the front-end.</p>
<p>In consumers.py</p>
<pre><code>
async def chat_message(self, event):
message = event['message']
username = event['username']
if (re.findall("yes|Yes", message)):
response = await requests.get('http://127.0.0.1:8000/dlp/')
print('message')
else:
await self.send(text_data=json.dumps({
'message': message,
'username': username
}))
</code></pre>
<p>The output in the terminal</p>
<pre><code>WebSocket CONNECT /ws/2/ [127.0.0.1:32840]
HTTP GET /dlp/ 200 [0.00, 127.0.0.1:32842]
message
</code></pre>
|
<p>Now your backends requests <code>/dlp</code> page, receives the response and prints string <code>'message'</code> to console. It doesn't send any data to frontend.</p>
<p>The most simple solution, I think, will be to add <code>status</code> field to your json and handle it in javascript.</p>
<pre><code>async def chat_message(self, event):
message = event['message']
username = event['username']
if re.findall("yes|Yes", message):
print('message')
await self.send(text_data=json.dumps({
'status': 1,
'redirect_to': '/dlp/',
}))
else:
await self.send(text_data=json.dumps({
'status': 0,
'message': message,
'username': username,
}))
</code></pre>
<pre class="lang-js prettyprint-override"><code>const socket = new WebSocket(...) // url of WS here
socket.onmessage = ev => {
data = json.loads(ev.data);
if (data.status === 1){
window.location.href = new URL(data.redirect_to, window.location.origin);
} else if (!data.status) {
// handle normal message
} else {
alert('Error code forgotten!')
}
}
</code></pre>
|
python|django|django-channels
| 0 |
1,902,390 | 71,940,944 |
How define the number of class in Detectron2 bounding box predict Pytorch?
|
<p>Where should i define the number os classes ?</p>
<p>ROI HEAD or RETINANET ?
Or both should have the same value ?</p>
<pre><code>cfg.MODEL.RETINANET.NUM_CLASSES =int( len(Classe_list)-1)
cfg.MODEL.ROI_HEADS.NUM_CLASSES=int( len(Classe_list)-1)
</code></pre>
|
<p>It depends on the network architecture you choose to use. If you use the "MaskRCNN", then you should set the cfg.MDOEL.ROI_HEADS.NUM_CLASSES.</p>
<p>The deep reason is that ROI_HEAD is the component used by MaskRCNN. If you use different network, you may need to change different things dependent on their implementation</p>
|
pytorch
| 1 |
1,902,391 | 72,103,671 |
Plotly 3D plot with right aspect ratio
|
<p>the relevant post is here: <a href="https://stackoverflow.com/questions/71318810/interactive-3d-plot-with-right-aspect-ratio-using-plotly">interactive 3D plot with right aspect ratio using plotly</a></p>
<p>For a further improvment, I am wondering how to plot a container frame according to the bin size, so the graph can display more clearly how much spare space is left, when container is not full? just like what is shown below:</p>
<p><a href="https://i.stack.imgur.com/yQBfg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yQBfg.png" alt="enter image description here" /></a></p>
<p><strong>UPADTE: drawing outer container frame</strong></p>
<pre><code>def parallelipipedic_frame(xm, xM, ym, yM, zm, zM):
# defines the coords of each segment followed by None, if the line is
# discontinuous
x = [xm, xM, xM, xm, xm, None, xm, xM, xM, xm, xm, None, xm, xm, None, xM, xM,
None, xM, xM, None, xm, xm]
y = [ym, ym, yM, yM, ym, None, ym, ym, yM, yM, ym, None, ym, ym, None, ym, ym,
None, yM, yM, None, yM, yM]
z = [zm, zm, zm, zm, zm, None, zM, zM, zM, zM, zM, None, zm, zM, None, zm, zM,
None, zm, zM, None, zm, zM]
return x, y, z
x, y, z = parallelipipedic_frame(0, 1202.4, 0, 235, 0, 269.7)
# fig = go.Figure(go.Scatter3d(x=x, y=y, z=z, mode="lines", line_width=4))
fig.add_trace(
go.Scatter3d(
x=x,
y=y,
z=z,
mode="lines",
line_color="blue",
line_width=2,
hoverinfo="skip",
)
)
ar = 4
xr = max(d["x"].max()) - min(d["x"].min())
fig.update_layout(
title={"text": pbin, "y": 0.9, "x": 0.5, "xanchor": "center", "yanchor": "top"},
margin={"l": 0, "r": 0, "t": 0, "b": 0},
# autosize=False,
scene=dict(
camera=dict(eye=dict(x=2, y=2, z=2)),
aspectratio={
**{"x": ar},
**{
c: ((max(d[c].max()) - min(d[c].min())) / xr) * ar
for c in list("yz")
},
},
aspectmode="manual",
),
)
</code></pre>
<p><a href="https://i.stack.imgur.com/I4r30.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I4r30.png" alt="enter image description here" /></a></p>
|
<p>The frame consists of segments, and a segment is drawn between two points. Hence I cannot give the code for plottin the frame only from your length, width and height.
I need the coordinates of the parallelipiped vertices, i.e. x.min(), x.max(), y.min(), y.max(), etc (see above), denoted xm, xM, ym, yM, zm, zM:</p>
<pre><code>import plotly.graph_objects as go
def parallelipipedic_frame(xm, xM, ym, yM, zm, zM):
#defines the coords of each segment followed by None, if the line is
discontinuous
x = [xm, xM, xM, xm, xm, None, xm, xM, xM, xm, xm, None, xm, xm, None, xM, xM,
None, xM, xM, None, xm, xm]
y = [ym, ym, yM, yM, ym, None, ym, ym, yM, yM, ym, None, ym, ym, None, ym, ym,
None, yM, yM,None, yM, yM]
z= [zm, zm, zm, zm, zm, None, zM, zM, zM, zM, zM, None, zm, zM, None, zm, zM,
None, zm, zM, None, zm, zM]
return x, y, z
x, y, z= parallelipipedic_frame(2.3, 4.5, 0,5, 0, 2)
fig=go.Figure(go.Scatter3d(x=x, y=y, z=z, mode="lines", line_width=4))
fig.update_layout(width=600, height=450, font_size=11, scene_aspectmode="data",
scene_camera_eye=dict (x=1.45, y=1.45, z=1), template="none")
fig.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/4wOtc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4wOtc.png" alt="enter image description here" /></a></p>
|
python|plotly|aspect-ratio|bin-packing
| 1 |
1,902,392 | 71,904,007 |
plotly express scatter plot python
|
<p>I have a problem with plotly I want to make a scatter plot
I want to make this same graph but with other circle shape for ind1, tringale for ind2 and the color is according to the type</p>
<p>here is my my code code for your help:</p>
<pre><code>data = {'ind1':[4,8,12,13,22,23],'ind2':[1,5,9,60,90,30],'type':['reg1','reg2','reg1','reg1','reg2','reg1']}
df = pd.DataFrame(data=data)
fig = px.scatter(df, x=df['ind1'],y= df['ind2'],color='type')
fig.show()
</code></pre>
<p>the graph that I compe to make and like the one in my answer but instead of having the shape of point in the two indicator I want to make the difference by changing the shape of the indicator 2 in triangle and keep the color by type like c is the case in this figure</p>
<p><a href="https://i.stack.imgur.com/Y9SxT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y9SxT.png" alt="enter image description here" /></a></p>
|
<p>I don't really understand how the desired graph should look like,</p>
<p>but here is an example of <a href="https://plotly.com/python-api-reference/generated/plotly.express.scatter" rel="nofollow noreferrer">styling symbols with plotly express</a></p>
<p>Note, that in order for this to work you need to pass a <strong>list</strong> <code>list_of_symbols</code> to <code>symbol</code> variable (in this case it is the name of the column in <code>df</code> containting that list) and a <strong>dictionary</strong> <code>dict</code> with <code>dict.keys() = list_of_symbols</code>, while values for desired symbols you can <a href="https://plotly.com/python/marker-style/#custom-marker-symbols" rel="nofollow noreferrer">look up here</a>
<a href="https://i.stack.imgur.com/mck5D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mck5D.png" alt="exemplar graph with marker_size = 15" /></a></p>
<pre><code>data = {'ind1':[4,8,12,13,22,23],'ind2':[1,5,9,60,90,30],'type':['reg1','reg2','reg1','reg1','reg2','reg1']}
df = pd.DataFrame(data=data)
fig = px.scatter(df, x='ind1', y= 'ind2', color='type',
symbol = 'ind2',
symbol_map = {1:'diamond-open-dot',
5:'diamond-open',
9:'diamond',
60:'cross-open-dot',
90:'triangle-right-open-dot',
30:'hexagon'})
fig.show()
</code></pre>
|
python|express|plotly|scatter
| 0 |
1,902,393 | 68,747,015 |
Sending messages in discord.py @tasks.loop()
|
<p><strong>Goal:</strong></p>
<p>I am simply trying to send a message to a discord channel from a <code>@tasks.loop()</code> without the need for a discord message variable from <code>@client.event async def on_message</code>. The discord bot is kept running in repl.it using uptime robot.</p>
<p><strong>Method / Background:</strong></p>
<p>A simple <code>while True</code> loop in will not work for the larger project I will be applying this principle to, as detailed by <a href="https://stackoverflow.com/a/63846957/16402702">Karen's answer here</a>. I am now using <code>@tasks.loop()</code> which Lovesh has quickly detailed here: <a href="https://stackoverflow.com/a/66753449/16402702">(see Lovesh's work)</a>.</p>
<p><strong>Problem:</strong></p>
<p>I still get an error for using the <a href="https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-send-a-message-to-a-specific-channel" rel="nofollow noreferrer">most common method to send a message in discord using discord.py</a>. The error has to have something to do with the <code>await channel.send( )</code> method. Neither of the messages get sent in discord. <a href="https://i.stack.imgur.com/uXvHX.jpg" rel="nofollow noreferrer">Here is the error message</a>.</p>
<p><strong>Code:</strong></p>
<pre><code>from discord.ext import tasks, commands
import os
from keep_alive import keep_alive
import time
token = os.environ['goofyToken']
# Set Up Discord Client & Ready Function
client = discord.Client()
channel = client.get_channel(CHANNEL-ID)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@tasks.loop(count=1)
async def myloop(word):
await channel.send(word)
@client.event
async def on_message(message):
msg = message.content
if msg.startswith('!'):
message_to_send = 'Hello World!'
await channel.send(message_to_send)
myloop.start(message_to_send)
keep_alive()
client.run(token)
</code></pre>
<p><strong>Attempted Solutions:</strong></p>
<p>A message can be sent from the <code>on_message</code> event using the syntax <code>await message.channel.send('Hello World!)</code>. However, I just can't use this. The code is kept running online by <a href="https://uptimerobot.com/" rel="nofollow noreferrer">uptimerobot</a>, a free website which pings the repository on repl.it. When the robot pings the repository, the message variable is lost, so the loop would stop scanning my data in the larger project I am working on which is giving me this issue.</p>
|
<p>When using any <code>client.get_*</code> method the bot will try to grab the object <em>from the cache</em>, the <code>channel</code> global variable is defined <em>before</em> the bot actually runs (so the cache is empty). You should get the channel <em>inside</em> the loop function:</p>
<pre class="lang-py prettyprint-override"><code>@tasks.loop(count=1)
async def myloop(word):
channel = client.get_channel(CHANNEL_ID)
await channel.send(word)
</code></pre>
|
python|discord|discord.py|repl.it
| 3 |
1,902,394 | 62,787,025 |
Django Rest Framework Api View GET
|
<p>In my codes, I have a model Tweet, and in tweet_list_view, I want to show the list of tweets as API view.</p>
<pre><code>@api_view(['GET'])
def tweet_list_view(request, *args, **kwargs):
qs = Tweet.objects.all().order_by('-date_posted')
serializer = TweetSerializer(data=qs, many=True)
return Response(serializer.data)
</code></pre>
<p>This is what I got as a result.</p>
<pre><code>AssertionError at /tweets/
When a serializer is passed a `data` keyword argument you must call `.is_valid()` before attempting to access the serialized `.data` representation.
You should either call `.is_valid()` first, or access `.initial_data` instead.
</code></pre>
<p>So I called the .is_valid method like following:</p>
<pre><code>@api_view(['GET'])
def tweet_list_view(request, *args, **kwargs):
qs = Tweet.objects.all().order_by('-date_posted')
serializer = TweetSerializer(data=qs, many=True)
if serializer.is_valid():
return Response(serializer.data, status=201)
return Response({}, status=400)
</code></pre>
<p>Then I get:</p>
<pre><code>TemplateDoesNotExist at /tweets/
rest_framework/api.html
</code></pre>
<p>At serializers.py
class TweetSerializer(serializers.ModelSerializer):
class Meta:
model = Tweet
fields = ['content', 'date_posted', 'likes']</p>
<p>models.py</p>
<pre><code>class Tweet(models.Model):
content = models.TextField(blank=True, null=True)
image = models.FileField(upload_to='images/', blank=True, null=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
date_posted = models.DateTimeField(default=timezone.now)
likes = models.IntegerField(default=0)
def __str__(self):
return self.content
class Meta:
ordering = ['-date_posted']
</code></pre>
<p>It's looking for a template, but it's supposed to use the default Django template. Is there any way to fix this problem?</p>
|
<p><strong>Update:</strong></p>
<p>forgot the @ in front of the api_view. Added it. Also added the renderer_class (jsonrenderer) to make sure avoiding the error.</p>
<hr />
<p>You need to use the data attribute of the serializer only when you have a post, put or patch view. In your case just try it without the data attribute and it should be fine</p>
<pre><code>from rest_framework.renderers import JSONRenderer
@api_view(['GET'])
@renderer_classes([JSONRenderer])
def tweet_list_view(request, *args, **kwargs):
qs = Tweet.objects.all().order_by('-date_posted')
serializer = TweetSerializer(qs, many=True)
return Response(serializer.data)
</code></pre>
<p>Here you can see it in the tutorial example of the official <a href="https://www.django-rest-framework.org/tutorial/2-requests-and-responses/" rel="nofollow noreferrer">django rest framework docs</a></p>
|
python|django|django-rest-framework|django-views
| 2 |
1,902,395 | 60,674,123 |
Running Linux on Windows because of Python package incompatibility
|
<p>I need to install a Python <a href="https://github.com/HaseloffLab/CellModeller" rel="nofollow noreferrer">package</a> that I found on GitHub and it seems to be compatible only with Linux and MacOS. I have Windows 10 and the possibilities that I know of are:</p>
<ol>
<li>Cygwin - but will that solve my problem?</li>
<li>VirtualBox - but what do I need to do after installing it?</li>
<li>Dual boot - but it's my work laptop and I can't risk any accidents.</li>
</ol>
<p>What would be the best solution and what are the steps to run Linux on Windows 10 so that I can later install the package?</p>
|
<h1>WSL (Preferred)</h1>
<p>Have a look at WSL (Windows Subsystem for Linux)
<a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/windows/wsl/install-win10</a></p>
<p>After enabling WSL, you will be able to download and install ubuntu from the windows store and have cli access to it. You can then download python on it and then use it to install and run your package.</p>
<h1>Alternative</h1>
<p>Another alternative is using docker containers but since dockers share the kernel with the host, docker will have to create and run a linux kernel on your windows host which will run all your other docker images. This is not recommended because it may slow down your machine but docker has other advantages such as isolation.</p>
<p>In the end it just depends on your choice</p>
|
python|linux|windows|operating-system|package
| 2 |
1,902,396 | 60,446,221 |
list operations for getting common elements in python
|
<p>I have a scenario where I am trying to find out the common items in a list and append a value accordingly</p>
<pre><code>a_l = ['62', '63', '66', '67']
a_ls = ['66', '67']
</code></pre>
<p>now if there are common elements in a_ls from a_l then create a combined list with <code>status : 1</code> for the common items found and rest as <code>status : 0</code>.</p>
<p>This is what I have done.</p>
<pre><code>non_comn_list = [item for item in a_l if item not in a_ls]
com_list = [item for item in a_l if item not in non_comn_list]
list = [{'a_id': a, 'status': 1} for a in com_list]
[list.append(val) for val in [{'a_id': a, 'status': 0} for a in non_comn_list]]
</code></pre>
<p>Current output :</p>
<pre><code>[{'a_id': '62', 'status': 0}, {'a_id': '63', 'status': 0}, {'a_id': '66', 'status': 0}, {'a_id': '67', 'status': 0}]
</code></pre>
<p>desired output : </p>
<pre><code>[{'a_id': '62', 'status': 0}, {'a_id': '63', 'status': 0}, {'a_id': '66', 'status': 1}, {'a_id': '67', 'status': 1}]
</code></pre>
<p>What am I doing wrong here ? any help woud be great</p>
|
<pre><code>a_l = ['62', '63', '66', '67']
a_ls = ['66', '67']
</code></pre>
<p>What about iterating over a big list and checking membership in a small list like below:</p>
<pre><code>[{'a_id': el, 'status': 1 if el in a_ls else 0} for el in a_l]
</code></pre>
<p>and if the lists are big you can convert them to <code>sets</code> to optimize membership testing.</p>
<pre><code>a_ls_set = set(a_ls)
[{'a_id': el, 'status': 1 if el in a_ls else 0} for el in a_l]
</code></pre>
<p>What happens if <code>a_ls</code> is bigger than <code>a_l</code>? this will solve that problem:</p>
<pre><code>from collections import Counter
[{'a_id': a_id, 'status': 1 if count > 1 else 0}
for a_id, count in Counter(a_l + a_ls).items()]
</code></pre>
|
python|python-3.x
| 4 |
1,902,397 | 70,082,887 |
How can I add a search function to a treeview?
|
<p>I want to display a row that matches the entry from all of my entry boxes into the treeview. <a href="https://i.stack.imgur.com/zYiPc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zYiPc.png" alt="enter image description here" /></a> How can I get the values of the treeview and check if it matches the entry from one of the boxes and display the whole row. Here is my treeview code</p>
<pre><code>tree = ttk.Treeview()
books_data = pandas.read_csv("List of Books - Sheet1 (3).csv")
df_column = books_data.columns.values
print(len(df_column))
print(df_column)
tree["column"] = list(books_data.columns)
tree["show"] = "headings"
for column in tree['column']:
tree.heading(column,text=column)
df_rows = books_data.to_numpy().tolist()
for row in df_rows:
tree.insert("","end",values=row)
tree.grid(column=0,row=4,columnspan=8)
</code></pre>
|
<h1>The short solution</h1>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
import tkinter.ttk as ttk
import sys
import pandas
# https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv
df = pandas.read_csv('./iris.csv')
df.head()
class main_window:
def __init__(self, root):
self.root = root
root.title("Treeview Search Example")
# INITIALIZE TREEVIEW + SCROLLVIEW
self.tree = ttk.Treeview(root, columns=list(df.columns.values), show='headings')
self.tree.grid(row=1, column=0, sticky='nsew')
# https://stackoverflow.com/a/41880534/5210078
vsb = ttk.Scrollbar(root, orient="vertical", command=self.tree.yview)
vsb.grid(row=1, column=1, sticky='ns')
self.tree.configure(yscrollcommand=vsb.set)
for column in self.tree['column']:
self.tree.heading(column,text=column)
df_rows = df.to_numpy().tolist()
for row in df_rows:
self.tree.insert("","end",values=row)
# ADD SEARCH BOXES
search_frame = tk.Frame(root)
search_frame.grid(row=0, column=0, columnspan=2, sticky='nsew')
tk.Label(search_frame, text="sepal.length:").grid(row=0, column=0)
tk.Label(search_frame, text="sepal.width:").grid(row=0, column=2)
tk.Label(search_frame, text="petal.length:").grid(row=0, column=4)
tk.Label(search_frame, text="petal.width:").grid(row=0, column=6)
tk.Label(search_frame, text="variety:").grid(row=0, column=8)
# Add Search boxes
self.sepal_length_ent = tk.Entry(search_frame)
self.sepal_length_ent.grid(row=0, column=1)
self.sepal_width_ent = tk.Entry(search_frame)
self.sepal_width_ent.grid(row=0, column=3)
self.petal_length_ent = tk.Entry(search_frame)
self.petal_length_ent.grid(row=0, column=5)
self.petal_width_ent = tk.Entry(search_frame)
self.petal_width_ent.grid(row=0, column=7)
self.variety_ent = tk.Entry(search_frame)
self.variety_ent.grid(row=0, column=9)
tk.Button(search_frame, text="Search", command=self.search).grid(row=0, column=10)
def search(self):
# https://stackoverflow.com/a/27068344/5210078
self.tree.delete(*self.tree.get_children())
build_query = ""
# https://stackoverflow.com/a/56157729/5210078
if self.sepal_length_ent.get():
build_query += f'& {self.sepal_length_ent.get()} == `sepal.length` '
if self.sepal_width_ent.get():
build_query += f'& {self.sepal_width_ent.get()} == `sepal.width` '
if self.petal_length_ent.get():
build_query += f'& {self.petal_length_ent.get()} == `petal.length` '
if self.petal_width_ent.get():
build_query += f'& {self.petal_width_ent.get()} == `petal.width` '
if self.variety_ent.get():
build_query += f'& "{self.variety_ent.get()}" in `variety`'
if build_query:
print(build_query)
queried_df = df.query(build_query[1:])
else:
queried_df = df
df_rows = queried_df.to_numpy().tolist()
for row in df_rows:
self.tree.insert("","end",values=row)
if __name__ == '__main__':
main = tk.Tk()
main_window(main)
main.mainloop()
sys.exit()
</code></pre>
<h1>The explanation of the solution</h1>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
import tkinter.ttk as ttk
import sys
import pandas
</code></pre>
<p>Obviously importing all the needed programs.</p>
<pre class="lang-py prettyprint-override"><code># https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv
df = pandas.read_csv('./iris.csv')
df.head()
</code></pre>
<p>Loading the csv dataset. I used the IRIS dataset because it is easily accessible.</p>
<p>Jump ahead to:</p>
<pre class="lang-py prettyprint-override"><code>if __name__ == '__main__':
main = tk.Tk()
main_window(main)
main.mainloop()
sys.exit()
</code></pre>
<p>Here we load the <code>main_window</code> class into our main tkinter window (makes your code look neater)</p>
<p>The self-explanatory bit (added a ttk treeview with scrollbar):</p>
<pre class="lang-py prettyprint-override"><code>class main_window:
def __init__(self, root):
self.root = root
root.title("Treeview Search Example")
# INITIALIZE TREEVIEW + SCROLLVIEW
self.tree = ttk.Treeview(root, columns=list(df.columns.values), show='headings')
self.tree.grid(row=1, column=0, sticky='nsew')
# https://stackoverflow.com/a/41880534/5210078
vsb = ttk.Scrollbar(root, orient="vertical", command=self.tree.yview)
vsb.grid(row=1, column=1, sticky='ns')
self.tree.configure(yscrollcommand=vsb.set)
for column in self.tree['column']:
self.tree.heading(column,text=column)
df_rows = df.to_numpy().tolist()
for row in df_rows:
self.tree.insert("","end",values=row)
# ADD SEARCH BOXES
search_frame = tk.Frame(root)
search_frame.grid(row=0, column=0, columnspan=2, sticky='nsew')
tk.Label(search_frame, text="sepal.length:").grid(row=0, column=0)
tk.Label(search_frame, text="sepal.width:").grid(row=0, column=2)
tk.Label(search_frame, text="petal.length:").grid(row=0, column=4)
tk.Label(search_frame, text="petal.width:").grid(row=0, column=6)
tk.Label(search_frame, text="variety:").grid(row=0, column=8)
# Add Search boxes
self.sepal_length_ent = tk.Entry(search_frame)
self.sepal_length_ent.grid(row=0, column=1)
self.sepal_width_ent = tk.Entry(search_frame)
self.sepal_width_ent.grid(row=0, column=3)
self.petal_length_ent = tk.Entry(search_frame)
self.petal_length_ent.grid(row=0, column=5)
self.petal_width_ent = tk.Entry(search_frame)
self.petal_width_ent.grid(row=0, column=7)
self.variety_ent = tk.Entry(search_frame)
self.variety_ent.grid(row=0, column=9)
tk.Button(search_frame, text="Search", command=self.search).grid(row=0, column=10)
</code></pre>
<pre class="lang-py prettyprint-override"><code> def search(self):
# https://stackoverflow.com/a/27068344/5210078
self.tree.delete(*self.tree.get_children())
</code></pre>
<p>Delete all the rows in the table</p>
<pre class="lang-py prettyprint-override"><code> build_query = ""
# https://stackoverflow.com/a/56157729/5210078
if self.sepal_length_ent.get():
build_query += f'& {self.sepal_length_ent.get()} == `sepal.length` '
if self.sepal_width_ent.get():
build_query += f'& {self.sepal_width_ent.get()} == `sepal.width` '
if self.petal_length_ent.get():
build_query += f'& {self.petal_length_ent.get()} == `petal.length` '
if self.petal_width_ent.get():
build_query += f'& {self.petal_width_ent.get()} == `petal.width` '
if self.variety_ent.get():
build_query += f'& "{self.variety_ent.get()}" in `variety`'
</code></pre>
<p>Build a search query. Use <code>==</code> for integers/floats and use <code>in</code> when searching inside strings. If you want to read more about queries, read <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.query.html" rel="nofollow noreferrer">this</a>. If you wanted to do something wacky, like make one of your entries a "lower than" box for integers, you could even substitute in a <code><</code> or <code>></code>. It basically makes our life much easier here! Because we can do a query, based off a dynamically changing string!</p>
<pre><code> if build_query:
print(build_query)
queried_df = df.query(build_query[1:])
else:
queried_df = df
</code></pre>
<p>If there is no <code>build_query</code> (no inputs in entry boxes), just reload the table with the data from the <code>df</code>. (<code>if build_query:</code> is shorthand for <code>if build_query != '':</code>)
If there is query data, do a query with the query terms.</p>
<pre class="lang-py prettyprint-override"><code> df_rows = queried_df.to_numpy().tolist()
for row in df_rows:
self.tree.insert("","end",values=row)
</code></pre>
<p>Reload the <code>treeview</code> with the data from the "new" queried df!</p>
<p>If you wanted a solution relate to your actual <code>csv</code> and interface, I'd recommend sharing an example of your <code>csv</code> and the gui design.</p>
<h1>What the solution became</h1>
<pre class="lang-py prettyprint-override"><code> def search():
# clear the tree of data
tree.delete(*tree.get_children())
entries = [
title_entry,
author_entry,
subject_category_entry,
publication_date_entry
]
build_df = books_data
if entries[0].get():
build_df = build_df[build_df.TITLE.str.contains(entries[0].get())]
if entries[1].get():
build_df = build_df[build_df.AUTHOR.str.contains(entries[1].get())]
if entries[2].get():
build_df = build_df[build_df.SUBJECT_CATEGORY.str.contains(entries[2].get())]
if entries[3].get():
build_df = build_df[build_df.PUBLICATION_DATE == (entries[3].get())]
df_rows = build_df.to_numpy().tolist()
for row in df_rows:
tree.insert("","end",values=row)
</code></pre>
|
python|pandas|tkinter
| 1 |
1,902,398 | 70,148,547 |
WSL2 Pytorch - RuntimeError: No CUDA GPUs are available with RTX3080
|
<p>I have been struggling for day to make torch work on WSL2 using an RTX 3080.</p>
<p>I Installed the CUDA-toolkit version 11.3</p>
<p>Running <code>nvcc -V</code> returns this :</p>
<pre class="lang-sh prettyprint-override"><code>nvcc -V
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2021 NVIDIA Corporation
Built on Sun_Mar_21_19:15:46_PDT_2021
Cuda compilation tools, release 11.3, V11.3.58
Build cuda_11.3.r11.3/compiler.29745058_0
</code></pre>
<p><code>nvidia-smi</code> returns this</p>
<pre class="lang-sh prettyprint-override"><code>Mon Nov 29 00:38:26 2021
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 510.00 Driver Version: 510.06 CUDA Version: 11.6 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|===============================+======================+======================|
| 0 NVIDIA GeForce ... On | 00000000:01:00.0 On | N/A |
| N/A 52C P5 17W / N/A | 1082MiB / 16384MiB | N/A Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=============================================================================|
| No running processes found |
+-----------------------------------------------------------------------------+
</code></pre>
<p>I verified the installation of the toolkit with blackscholes</p>
<pre class="lang-sh prettyprint-override"><code>./BlackScholes
[./BlackScholes] - Starting...
GPU Device 0: "Ampere" with compute capability 8.6
Initializing data...
...allocating CPU memory for options.
...allocating GPU memory for options.
...generating input data in CPU mem.
...copying input data to GPU mem.
Data init done.
Executing Black-Scholes GPU kernel (512 iterations)...
Options count : 8000000
BlackScholesGPU() time : 0.242822 msec
Effective memory bandwidth: 329.459087 GB/s
Gigaoptions per second : 32.945909
BlackScholes, Throughput = 32.9459 GOptions/s, Time = 0.00024 s, Size = 8000000 options, NumDevsUsed = 1, Workgroup = 128
Reading back GPU results...
Checking the results...
...running CPU calculations.
Comparing the results...
L1 norm: 1.741792E-07
Max absolute error: 1.192093E-05
Shutting down...
...releasing GPU memory.
...releasing CPU memory.
Shutdown done.
[BlackScholes] - Test Summary
NOTE: The CUDA Samples are not meant for performance measurements. Results may vary when GPU Boost is enabled.
Test passed
</code></pre>
<p>And when I try to use torch, it doesn't find any GPU. Btw, I had to install torch==1.10.0+cu113 if I wanted to use torch with my RTX 3080 as the sm_ with the simple 1.10.0 version are not compatible with the rtx3080.</p>
<p>Running torch returns this :</p>
<pre class="lang-py prettyprint-override"><code>>>> import torch
>>> torch.version
<module 'torch.version' from '/home/snihar/miniconda3/envs/tscbasset/lib/python3.7/site-packages/torch/version.py'>
>>> torch.version.cuda
'11.3'
>>> torch.cuda.get_arch_list()
[]
>>> torch.cuda.device_count()
0
>>> torch.cuda.current_device()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/snihar/miniconda3/envs/tscbasset/lib/python3.7/site-packages/torch/cuda/__init__.py", line 479, in current_device
_lazy_init()
File "/home/snihar/miniconda3/envs/tscbasset/lib/python3.7/site-packages/torch/cuda/__init__.py", line 214, in _lazy_init
torch._C._cuda_init()
RuntimeError: No CUDA GPUs are available
</code></pre>
<p>At last, interestingly, I am completely able to run tensorflow-gpu on the same machine.</p>
<p>Installed pytorch like this : <code>conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch</code></p>
<p>Also, I managed to run pytorch in a docker container started from my WSL2 machine with this command :</p>
<pre><code>sudo docker run --gpus all -it --rm -v /home/...:/home/... nvcr.io/nvidia/pytorch:21.11-py3.
</code></pre>
<p>When running pytorch on the windows machine I am running the WSL from, it works too. Both return ['sm_37', 'sm_50', 'sm_60', 'sm_61', 'sm_70', 'sm_75', 'sm_80', 'sm_86', 'compute_37'] which says that the library is compatible with rtx 3080.</p>
|
<p>I've met the same one, solved by downgrade pytorch from 1.10 to 1.8.2LTS</p>
|
pytorch
| 3 |
1,902,399 | 70,650,581 |
Large wait time after concurrent.futures closes
|
<p>I have a list of URLs which I am trying to get JSON data from. I am going through a list of 10,000s items so speed is key for me. This took forever in serial processing so I opted for using sessions. I have not used it before, but I have been able to produce something that is fast enough.</p>
<pre><code>ar_list=['https//:www.foo.com',...,'https//:www.foo2.com']
adapter = HTTPAdapter(pool_connections=workers_num, pool_maxsize=workers_num)
data_list = []
with sessions.FuturesSession(max_workers=workers_num) as session:
session.mount('http://', adapter)
session.mount('https://', adapter)
futures = []
for idx, ar_url in enumerate(ar_list):
resp = session.get(ar_url,headers=headers)
futures.append(resp)
end_time = datetime.datetime.now()
time_delta=end_time-start_time
</code></pre>
<p>This works nicely and runs a query within about 70us (with 10,000 queries).
I unfortunately have a problem getting the data.
<code>futures.append(resp)</code> gives me a Future object, and I need to run <code>.result().json()</code> on this to actually get usable information out. However when I add these, I get extremely slow operation speeds at about 0.4s per query (much slower than 70us!)</p>
<p>I have tried running the FutureSession quickly (as the code shows above), and then performing actions on the futures list later using:</p>
<ol>
<li>for loop</li>
<li>list comprehension: <code>[item.result().json() for item in as_completed(futures)]</code></li>
<li>lambda list operation: <code>list(map(lambda i: func(futures, i), range(0, len(futures))))</code></li>
<li>finally trying another session to perform the operation:</li>
</ol>
<pre><code>data=[]
with concurrent.futures.ThreadPoolExecutor() as e:
fut = [e.submit(func, i) for i in futures]
for idx,r in enumerate(concurrent.futures.as_completed(fut)):
print(str(idx))
data.append(r.result())
</code></pre>
<p>Now this ThreadPoolExecutor works really well also, performing the task around 70us or so.
However, I am measuring at the start and end of <code>with</code> and notice that there is a large delay between these two <code>with</code> structures. It looks like this all together:</p>
<pre><code>
with sessions.FuturesSession(max_workers=workers_num) as session:
#some fast operations here
"""
A VERY LARGE DELAY (about 60 seconds)
"""
with concurrent.futures.ThreadPoolExecutor() as e:
#some fast operations here
</code></pre>
<p>Is there some cleanup of all of the sessions I create between the two <code>with</code> conditions that take a long time to resolve? I can see that there must be a better way of doing this than two sessions processes to just get some json data formatted correctly, but I can't seem to find the faster way.</p>
|
<p>After a lot of research reagrding this, I have discovered the big wait time that I experience is the <code>as_completed</code> call. As @Simon says, the large wait time is simply me waiting for the responses. If I remove <code>as_completed</code> it becomes as fast as ever, but of course the reponses are garbage or <code>None</code>.</p>
<p>I am looking into avoiding the use of <code>as_completed</code> with a callback to avoid the need to wait for <code>as_completed</code> to occur on the futures, and just get them from a completed list. Hopefully I return soon with a "work around"</p>
|
python|concurrent.futures
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.