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,903,600
71,051,964
Profiling in Odoo
<p>I am new to odoo and code profiling. I am using py-spy to profile my odoo code, as I need a flame graph as the output of profiling. Everything is working fine with py-spy, but the issue is, the py-spy needs to be stopped by pressing <strong>ctrl + C</strong> on the terminal where it is running or shutting the odoo server down. I can't stop or reset the odoo server neither I can do ** Ctrl + C** on the server.</p> <p>I had tried to create to do this To start py-spy</p> <pre><code>def start_pyflame(self): pyflame_started = self.return_py_spy_pid('py-spy') error = False if not pyflame_started: self.start_pyflame() else: error = 'PyFlame Graph process already created. Use Stop button if needed.' _logger.error(error) </code></pre> <p>which is working fine, the problem is with this one</p> <pre><code>def stop_pyflame_and_download_graph(self): pyflame_running = self.return_py_spy_pid('py-spy') if pyflame_running: subprocess.run([&quot;sudo&quot;, &quot;pkill&quot;, &quot;py-spy&quot;]) </code></pre> <p>Now the issue is when I am killing the process with pkill or kill it kills the process but along with this, it also terminates the py-spy, because of which, the output file is not generated.</p> <p>Is there any way to stop or soft kill py-spy so that the output file will be created.</p> <p>Thanks in advance for help</p>
<p>After some research, I came to know that all these kill commands are just killing the process whereas in this case, we need to stop the process.</p> <p>This thing I have achieved by</p> <pre><code>sudo kill -SIGINT &lt;pid&gt; </code></pre> <p>As it is clear from the name, this command is not killing/terminating the process, it is simply asking the process to stop working by passing an interrupt signal.</p> <p>This worked for me.</p>
python-3.x|odoo|profiling|odoo-14
0
1,903,601
70,998,883
geopandas looping with lambda function
<p>I have a geojson document 'streets' with a column &quot;geometry&quot; filled with data of type shapely Point. I have another geojson document 'quartiers' with a column 'geometry&quot; with data of type shapely Polygon and in same document I have another column called &quot;l_qu&quot;. What I am trying to achieve is looping through all streets['geometry] with a lambda in quartiers['geometry'] and assign the corresponding 'l_qu' match value in a new column 'matchquartier' in 'streets'. There are 150K lines in streets (the adresses) and 80 lines in quartiers (the neighboorhoods) The lambda for I built is :</p> <pre><code>def checkquartier(point): return quartiers[quartiers[&quot;geometry&quot;].apply(point.within)][&quot;l_qu&quot;] </code></pre> <p>When running some test fo the lambda, say: checkquartier(streets['geometry'][19]) , no issue, it returns:</p> <p>19 La Chapelle Name: l_qu, dtype: object</p> <p>which is the expected result. The problem is when I try to do it for my whole doc with</p> <pre><code>streets[&quot;matchquartier&quot;]=streets['geometry'].apply(lambda x: checkquartier(x)) </code></pre> <p>It returns the error: ValueError: Wrong number of items passed 80, placement implies 1</p> <p>I know this is a broader pandas issue but the other fixes/answers I found on SO do not work in this case so wondering if there is something from the GeoPandas side that I am doing wrong ? Thanks</p> <pre><code> import pandas as pd import geopandas import os import shapely from shapely.geometry import Polygon, LineString, Point,box import matplotlib.pyplot as plt from shapely import wkt quartiers = geopandas.read_file(&quot;https://parisdata.opendatasoft.com/explore/dataset/quartier_paris/download/?format=geojson&amp;timezone=Europe/Berlin&amp;lang=fr&quot;) streets=geopandas.read_file(&quot;https://opendata.paris.fr/explore/dataset/adresse_paris/download/?format=geojson&amp;timezone=Europe/Berlin&amp;lang=fr&quot;) def checkquartier(point): return quartiers[quartiers[&quot;geometry&quot;].apply(point.within)][&quot;l_qu&quot;] streets[&quot;matchquartier&quot;]=streets['geometry'].apply(lambda x: checkquartier(x)) </code></pre>
<p>IIUC, you can just use a spatial join. This is working for me.</p> <pre><code>import os import pandas as pd import geopandas as gpd import shapely from shapely import wkt from shapely.geometry import Polygon, LineString, Point, box, shape import json quartiers = gpd.read_file(&quot;quartier_paris.csv&quot;) streets=gpd.read_file(&quot;adresse_paris.csv&quot;) quartiers[&quot;geometry&quot;] = quartiers[&quot;geom&quot;].apply(lambda x: shape(json.loads(x))) streets[&quot;geometry&quot;] = streets[&quot;geom&quot;].apply(lambda x: shape(json.loads(x))) sj = gpd.sjoin(streets, quartiers) streets.join(sj[&quot;l_qu&quot;]) </code></pre>
pandas|geojson|geopandas|shapely
1
1,903,602
70,968,261
How does the complexity of work done in a thread impact the overall code performance
<p>Threads are used to reduce the execution time, wherever possible. Would using threads for complex works impact the performance of the overall code anyhow?</p>
<p>Multi-threading <strong>always</strong> comes with a certain overhead: additional CPU cycles are spent on managing the state of threads, context switching, etc, pp.</p> <p>Meaning: whether &quot;using more threads&quot; improves &quot;performance&quot; <strong>always</strong> depends on context. Example: threads become extremely helpful regarding latency/responsiveness when long-running IO operations are handled in separate threads. So thread A might wait for such an IO operation to complete, while thread B can continue to do something else. If there would only be one thread, the whole program would sit there, doing nothing but waiting.</p> <p>But if your code is mainly doing &quot;heavy computations&quot;, then adding threads might only <strong>cost</strong> you for no gain.</p> <p>And of course, remember that python has a <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow noreferrer">global lock</a> on thread anyway.</p>
python-3.x|python-multithreading
0
1,903,603
70,999,623
Remove the Index from Dataframe (stock data)
<p>I'm trying to remove the index on the left from the Table. I did:</p> <pre><code>import pandas as pd nv.to_csv('H:/XYZfile/nvidia.csv', index=False) </code></pre> <p>Then</p> <pre><code>nv.head() </code></pre> <p>and I still get the index: <img src="https://i.stack.imgur.com/SndTW.png" alt="1" /></p> <p>What did I do wrong?</p>
<p>that's your index , if you want to set another column as index , you can do:</p> <pre><code>nv.set_index('Date') </code></pre> <p>but thta's only in your dataframe , in your csv you won't see that since you are passing index = false</p>
python|pandas|dataframe|indexing
0
1,903,604
2,455,606
BasicHTTPServer, SimpleHTTPServer and concurrency
<p>I'm writing a small web server for testing purposes using python, BasicHTTPServer and SimpleHTTPServer. It looks like it's processing one request at a time. Is there any way to make it a little faster without messing around too deeply? Basicly my code looks as the following and I'd like to keep it this simple ;)</p> <pre><code>os.chdir(webroot) httpd = BaseHTTPServer.HTTPServer(("", port), SimpleHTTPServer.SimpleHTTPRequestHandler) print("Serving directory %s on port %i" %(webroot, port) ) try: httpd.serve_forever() except KeyboardInterrupt: print("Server stopped.") </code></pre>
<p>You can make your own threading or forking class with a mixin inheritance from <a href="http://docs.python.org/library/socketserver.html" rel="nofollow noreferrer">SocketServer</a>:</p> <pre><code>import SocketServer import BaseHTTPServer class ThreadingHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass </code></pre> <p>This has its limits as it doesn't use a thread pool, is limited by the GIT, etc, but it could help a little (with relatively little effort). Remember that requests will be served simultaneously by multiple threads, so be sure to put proper locking around accesses to global/shared data (unless such data's immutable after startup) done in the course of serving a request.</p> <p><a href="https://stackoverflow.com/questions/2398144/python-basehttpserver-httpserver-concurrency-threading">This SO question</a> covers the same ground (not particularly at length).</p>
python|concurrency|simplehttpserver
9
1,903,605
2,570,690
(Python) algorithm to randomly select a key based on proportionality/weight
<p>I'm a bit at a loss as to how to find a clean algorithm for doing the following:</p> <p>Suppose I have a dict k:</p> <pre><code>&gt;&gt;&gt; k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} </code></pre> <p>I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) amount of keys. </p> <pre><code>&gt;&gt;&gt; sum(k.values()) &gt;&gt;&gt; 274 </code></pre> <p>So that there's a </p> <pre><code>&gt;&gt;&gt; 68.0/274.0 &gt;&gt;&gt; 0.24817518248175183 </code></pre> <p>24.81% percent change that A is selected.</p> <p>How would you write an algorithm that takes care of this? In other words, that makes sure that on 10.000 random picks, A will be selected 2.481 times?</p>
<p>Here's a weighted choice function, with some code that exercises it.</p> <pre><code>import random def WeightedPick(d): r = random.uniform(0, sum(d.itervalues())) s = 0.0 for k, w in d.iteritems(): s += w if r &lt; s: return k return k def Test(): k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} results = {} for x in xrange(10000): p = WeightedPick(k) results[p] = results.get(p, 0) + 1 print results Test() </code></pre>
python
12
1,903,606
5,986,780
Unable to import FigureCanvasWxAgg from Matplotlib in Python
<p>I'm using Python x64 with everything installed, but I'm getting an unresolved import on FigureCanvasWxAgg. I can get up to matplotlib.backends.backend_wxagg but there's no FigureCanvasWxAgg to import from there. </p> <p>I've also tried <code>from matplotlib.backends.backend_wxagg import *</code> but it doesn't work either. </p> <p>EDIT: Problem solved. I took a peek at my backend_wxagg.py file and found it to be completely different than the one listed <a href="http://www.java2s.com/Open-Source/Python/Chart-Report/Matplotlib/matplotlib-0.99.1.1/lib/matplotlib/backends/backend_wxagg.py.htm" rel="nofollow">here</a>. So I copied that from version 0.99.1.1 into my 1.0.1 file. (I should probably just uninstall 1.0.1 matplotlib and use the older version.) Anyway, it got the examples working, so I'm happy.</p>
<p>What OS are you on, and how did you install matplotlib?</p> <p>Your solution is quite likely to break things... You need to build and install the wx backend as you normally would. I'm not sure about the wx backend, but several of the other backends are C extensions, not just a simple python file.</p> <p>The wx backend isn't built by default, so it's usually included as a separate package. (e.g. <code>python-matplotlib-wx</code> in the case of Suse) You'll need to install the wx backend through your package manager, as you normally would.</p> <p>If you're on an OS without a package manager (e.g. windows, osx), the installer may or may not have the wx backend built depending on who built it and how it was configured. I know absolutely nothing about non-linux or BSD oses, so you're on your own there. Try looking wherever you downloaded your matplotlib binary from and see if they have a separate installer for the wx backend.</p> <p>If you're building from source, you need to enable the wx backend and rebuild. To do this, edit the <code>site.cfg</code> file in your build directory. You may need to rename the default one (<code>site.cfg.default</code>, or something along those lines) to <code>site.cfg</code>, if you don't alread have a <code>site.cfg</code> file in your build directory. </p> <p>Hope that helps!</p>
python|wxpython|matplotlib|pydev
2
1,903,607
67,768,241
my code give an error if a enter a letter or a charcter different to a float or integer
<p>my purpose is to return a message if the user enter a letter or character different to an integer or float but if a enter a letter like &quot;jhdsjfhdhjd&quot; it give me an error</p> <pre><code> my_number = int(input(&quot;Please ,enter your number here !&quot;)) if my_number is not int: print(&quot;It is not a number a number !&quot;) else: my_num = int(my_number) if my_num == 0: while my_num &lt; 11 : print(&quot;Not there Yet , your number is &quot; + str(my_num) + &quot;.We continue increase your number to 10 !&quot;) my_num +=1 print(&quot;Good, increasing is Done , the number is 10&quot;) elif my_num &gt; 0: while my_num &gt; -1: if my_num == 0: print(&quot;Correct ,the decreasing is finished.The number is 0&quot;) print(&quot;Not there Yet , your number is &quot; + str(my_num)+ &quot;.We continue decrease your number to 0 !&quot;) my_num -=1 else: print(&quot;It isn't a number ,Please enter an integer&quot;) </code></pre>
<p>The input function captures the typed value as a <strong>string</strong>. You may coerce it to become an integer by using int() but if the entered value is a floating number then you will loose precision.</p> <p>There could be many ways to differentiate between a string, an integer and a float. You can use <a href="https://docs.python.org/3/library/re.html" rel="nofollow noreferrer">regular expression</a> to check if the string is an integer, float or string. Below is one of the possible solutions. Also in your code your are dealing with 0 and &gt; 0 but not dealing with &lt; 0 case ..may be you want to add that part as well. Also you need to modify the logic if the input number is a floating point number.</p> <pre class="lang-py prettyprint-override"><code>import re my_number = input(&quot;Please ,enter your number here !&quot;) if not re.fullmatch(r'^[+-]?[0-9]*[\.]?[0-9]*$', my_number): print(&quot;It is not a number a number !&quot;) else: if re.fullmatch(r'^[+-]?[0-9]*$', my_number):#The input string is an integer print(&quot;You entered an integer&quot;) my_num = int(my_number) else: #it is a float print(&quot;You entered a float&quot;) my_num = float(my_number) if my_num == 0.0: while my_num &lt; 11 : print(&quot;Not there Yet , your number is &quot; + str(my_num) + &quot;.We continue increase your number to 10 !&quot;) my_num +=1 print(&quot;Good, increasing is Done , the number is 10&quot;) elif my_num &gt; 0: while my_num &gt; -1: if my_num == 0: print(&quot;Correct ,the decreasing is finished.The number is 0&quot;) else: print(&quot;Not there Yet , your number is &quot; + str(my_num)+ &quot;.We continue decrease your number to 0 !&quot;) my_num -=1 </code></pre> <p>The output for a string is</p> <pre><code>Please ,enter your number here !abcdef It is not a number a number ! </code></pre> <p>The output for 0 is as below.</p> <pre class="lang-py prettyprint-override"><code>Please ,enter your number here !0 You entered an integer Not there Yet , your number is 0.We continue increase your number to 10 ! Not there Yet , your number is 1.We continue increase your number to 10 ! Not there Yet , your number is 2.We continue increase your number to 10 ! Not there Yet , your number is 3.We continue increase your number to 10 ! Not there Yet , your number is 4.We continue increase your number to 10 ! Not there Yet , your number is 5.We continue increase your number to 10 ! Not there Yet , your number is 6.We continue increase your number to 10 ! Not there Yet , your number is 7.We continue increase your number to 10 ! Not there Yet , your number is 8.We continue increase your number to 10 ! Not there Yet , your number is 9.We continue increase your number to 10 ! Not there Yet , your number is 10.We continue increase your number to 10 ! Good, increasing is Done , the number is 10 </code></pre> <p>The output for a positive integer is as below</p> <pre class="lang-py prettyprint-override"><code>Please ,enter your number here !8 You entered an integer Not there Yet , your number is 8.We continue decrease your number to 0 ! Not there Yet , your number is 7.We continue decrease your number to 0 ! Not there Yet , your number is 6.We continue decrease your number to 0 ! Not there Yet , your number is 5.We continue decrease your number to 0 ! Not there Yet , your number is 4.We continue decrease your number to 0 ! Not there Yet , your number is 3.We continue decrease your number to 0 ! Not there Yet , your number is 2.We continue decrease your number to 0 ! Not there Yet , your number is 1.We continue decrease your number to 0 ! Correct ,the decreasing is finished.The number is 0 </code></pre> <p>The output for a floating number is</p> <pre class="lang-py prettyprint-override"><code>Please ,enter your number here !6.5 You entered a float Not there Yet , your number is 6.5.We continue decrease your number to 0 ! Not there Yet , your number is 5.5.We continue decrease your number to 0 ! Not there Yet , your number is 4.5.We continue decrease your number to 0 ! Not there Yet , your number is 3.5.We continue decrease your number to 0 ! Not there Yet , your number is 2.5.We continue decrease your number to 0 ! Not there Yet , your number is 1.5.We continue decrease your number to 0 ! Not there Yet , your number is 0.5.We continue decrease your number to 0 ! Not there Yet , your number is -0.5.We continue decrease your number to 0 ! </code></pre> <p>All the best.</p>
python-3.x|loops|if-statement
0
1,903,608
30,617,589
Python Amazon MWS Api 400 Client Error Bad request
<p>Hi I am using this github code to link to amazon mws api to fetch current listed order. <a href="https://github.com/czpython/python-amazon-mws" rel="nofollow">Github python-amazon-aws</a>. <br> My Code is:</p> <pre><code>import mws auth = mws.Orders(access_key='AKIAJHSXMwdwdL4XJT7NVLAQ', secret_key='xbY5YTa4wwcqMD9dMJDOA0T3iRSL67vSYdRFz+Y4wGR', account_id='A3AZIT4DFSLU02M7', region='IN', domain='', uri="", version="", auth_token="") auth.list_orders(marketplaceids='A21TJRUUN4KGV', created_after='2015-06-01', created_before=None, lastupdatedafter=None, lastupdatedbefore=None, orderstatus=(), fulfillment_channels=(), payment_methods=(), buyer_email=None, seller_orderid=None, max_results='100') </code></pre> <p>Access Key, Secret Key and Account Id changed for security. the first two line of code works fine. On adding the 3rd line I am getting this error:</p> <pre><code>$python Orders.py Traceback (most recent call last): File "Orders.py", line 5, in &lt;module&gt; auth.list_orders(marketplaceids='A21TJRUUN4KGV', created_after='2015-06-01', created_before=None, lastupdatedafter=None, lastupdatedbefore=None, orderstatus=(), fulfillment_channels=(), payment_methods=(), buyer_email=None, seller_orderid=None, max_results='100') File "/usr/local/lib/python2.7/dist-packages/python_amazon_mws-0.6-py2.7.egg/mws/mws.py", line 421, in list_orders return self.make_request(data) File "/usr/local/lib/python2.7/dist-packages/python_amazon_mws-0.6-py2.7.egg/mws/mws.py", line 210, in make_request raise error mws.mws.MWSError: 400 Client Error: Bad Request </code></pre>
<p>I found the answer. I was passing the the marketplace_id as a string. The correct way is to pass marketplace_id as a list like </p> <pre><code>marketplaceids = ['A21TJRUUN4KGV',] </code></pre>
python|amazon-mws
0
1,903,609
30,506,746
Use regex backreferences to create array
<p>I'm not really sure of the best way to summarize this in one sentence for the title, so please edit it to make it clearer if necessary.</p> <p>I have a list of strings (parsed from a Web page) of the format</p> <pre class="lang-none prettyprint-override"><code>"\tLocation\tNext Available Appointment: Date\n" </code></pre> <p>I'd like to turn this into a list of lists, each with the format</p> <pre><code>["Location", "Date"] </code></pre> <p>I know what regular expression I would use, but I don't know how to use the results.</p> <p>(For reference, here's the regular expression that would find what I want.)</p> <pre><code>^\t(.*)\t.*: (.*)$ </code></pre> <p>I found how to match regexes against text, but not how to extract the results to something else. I am new to Python, though, so I acknowledge that I probably missed something while searching.</p>
<p>You can use <a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow"><code>re.findall()</code></a> function within a list comprehension :</p> <pre><code>import re [re.findall(r'^\t(.*)\t.*: (.*)$',i) for i in my_list] </code></pre> <p>For example :</p> <pre><code>&gt;&gt;&gt; my_list=["\tLocation\tNext Available Appointment: Date\n","\tLocation2\tNext Available Appointment: Date2\n"] &gt;&gt;&gt; [re.findall(r'^\t(.*)\t.*: (.*)$',i) for i in my_list] [[('Location', 'Date')], [('Location2', 'Date2')]] </code></pre> <p>You can also use <code>re.search()</code> with <code>groups()</code> method :</p> <pre><code>&gt;&gt;&gt; [re.search(r'^\t(.*)\t.*: (.*)$',i).groups() for i in my_list] [('Location', 'Date'), ('Location2', 'Date2')] </code></pre> <p>Note that the advantage of <code>re.search</code> here is that you'll get a list of tuples instead of list of list of tuples (with <code>findall()</code>).</p>
python|regex
4
1,903,610
64,056,674
Bad UDP performance in Golang vs. Python
<p>I want to send as many UDP packets as fast as possible. I tried different methods of sending UDP data in the <a href="https://golang.org/pkg/net/?m=all" rel="nofollow noreferrer">net</a> package, but ended up with the following;</p> <pre><code>func main() { for i := 0; i &lt; THREADS; i++ { go loopSendHello() } // Sleep forever &lt;-make(chan bool, 1) } func loopSendHello() { for { sendHello() } } func sendHello() { // Setup conn addr := net.UDPAddr{ IP: net.IP{192, 168, 1, xxx}, Port: 1337, } conn, err := net.ListenPacket(&quot;udp&quot;, &quot;&quot;) if err != nil { log.Fatal(&quot;Listen:&quot;, err) } n, err := conn.WriteTo([]byte(&quot;hello&quot;), &amp;addr) if err != nil { log.Fatal(&quot;Error while writing to conn! :&quot;, err) } conn.Close() } </code></pre> <p>THREADS is defined by runtime.NumCPU() btw. Benchmarking this using Wireshark gives these results: <a href="https://i.stack.imgur.com/UCpdX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UCpdX.jpg" alt="Golang benchmark" /></a> About 90ms delay (if I'm reading this right).</p> <p>While this is the situation in Python (this function is running in 4 threads):</p> <pre><code>def sendHello(): while True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) addr = (&quot;192.168.1.xxx&quot;, 1337) s.sendto(data, addr) except: print(&quot;error&quot;) </code></pre> <p>Benchmark using Wireshark: <a href="https://i.stack.imgur.com/dljOO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dljOO.jpg" alt="py bench" /></a>. This is from 1ms to about 10ms delay! Insane differences.</p> <p>How can I match python's speed in Go?</p>
<p>So I decided to very quickly create a simple benchmark of sending 200 000 UDP packets without any threads or bad programming techniques. The benchmark is between Go and Python. In addition I wanted a benchmark test to be concidered close to as fast as possible. I concidered using C, but as I'm on Windows it seemed easiest to use Rust.</p> <p>Rust code:</p> <pre><code>use std::time::{SystemTime}; use std::net::UdpSocket; const DATA: &amp;[u8] = &amp;[0; 1024]; fn main() { let time_start = SystemTime::now(); let socket = UdpSocket::bind(&quot;192.168.1.155:1339&quot;).unwrap(); for _ in 0..200000 { socket.send_to(DATA, &quot;192.168.1.122:80&quot;).unwrap(); } let elapsed = time_start.elapsed().unwrap(); println!(&quot;Time {} ms to send 200 000 packets&quot;, elapsed.as_millis()); } </code></pre> <p>Avg. result (built in --release mode): <code>Time 1863 ms to send 200 000 packets</code></p> <p>For the Go benchmark, this is essentially the code:</p> <pre><code>var buff = []byte(&quot;&quot;) func main() { buff = []byte(RandomString(1024)) conn, err := net.ListenUDP(&quot;udp&quot;, &amp;net.UDPAddr{}) if err != nil { log.Fatal(&quot;Listen:&quot;, err) } loopSendHello(*conn) conn.Close() } func loopSendHello(conn net.UDPConn) { timeStart := time.Now() for i:=0; i &lt; 200000; i++ { sendHelloEdited(&amp;conn) } timeStop := time.Now() timeDelta := timeStop.Sub(timeStart) fmt.Println(&quot;Took&quot;, timeDelta.Milliseconds(), &quot;ms to send 200 000 packets.&quot;) } // targetAddr is target address in form of net.UDPAddr func sendHelloEdited(conn *net.UDPConn) { _, err := conn.WriteToUDP(buff, &amp;targetAddr) if err != nil { log.Fatal(&quot;Error while writing to conn! :&quot;, err) } } </code></pre> <p>Go avg. result: <code>Took 1959 MS to send 200 000 packets.</code></p> <p>Now for the Python test, this is the code:</p> <pre><code>def main(): x = 0 data = random._urandom(1024) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) addr = (str(ip), int(port)) startTime = datetime.datetime.now() while x &lt; 200000: s.sendto(data, addr) x += 1 s.close() endTime = datetime.datetime.now() deltaTime = endTime - startTime print(&quot;Took&quot;, deltaTime, &quot;to send 200 000 packets&quot;) main() </code></pre> <p>Interestingly the python result was always quick, with an avg. output of: <code>Took 0:00:01.831531 to send 200 000 packets</code></p> <p>So it seems Go is indeed slowest, but only marginally.</p>
python|go|networking|udp
2
1,903,611
66,499,217
Python: How to get attributes and their type from a dataclass?
<p>I'd like to read all attributes <strong>and their types</strong> from a (data)class, as shown in this desired (pseudo)code:</p> <pre><code>from dataclasses import dataclass @dataclass class HelloWorld: name: str = 'Earth' is_planet: bool = True radius: int = 6371 if __name__ == '__main__': attrs = get_attributes(HelloWorld) for attr in attrs: print(attr.name, attr.type) # name, str </code></pre> <p>I checked several <a href="https://stackoverflow.com/questions/9058305/getting-attributes-of-a-class">answers</a>, but couldn't find what I need yet.</p> <p>Any idea? Thanks in advance!</p>
<p>For classes in general, you can access the <code>__annotations__</code>:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar: int ... baz: str ... &gt;&gt;&gt; Foo.__annotations__ {'bar': &lt;class 'int'&gt;, 'baz': &lt;class 'str'&gt;} </code></pre> <p>This returns a <code>dict</code> mapping attribute name to annotation.</p> <p>However, dataclasses have use <code>dataclass.field</code> objects to encapsulate a lot of this information. You can use <code>dataclasses.fields</code> on an instance or on the class:</p> <pre><code>&gt;&gt;&gt; import dataclasses &gt;&gt;&gt; @dataclasses.dataclass ... class Foo: ... bar: int ... baz: str ... &gt;&gt;&gt; dataclasses.fields(Foo) (Field(name='bar',type=&lt;class 'int'&gt;,default=&lt;dataclasses._MISSING_TYPE object at 0x7f806369bc10&gt;,default_factory=&lt;dataclasses._MISSING_TYPE object at 0x7f806369bc10&gt;,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD), Field(name='baz',type=&lt;class 'str'&gt;,default=&lt;dataclasses._MISSING_TYPE object at 0x7f806369bc10&gt;,default_factory=&lt;dataclasses._MISSING_TYPE object at 0x7f806369bc10&gt;,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)) </code></pre> <p>NOTE:</p> <p><a href="https://www.python.org/dev/peps/pep-0563/#enabling-the-future-behavior-in-python-3-7" rel="noreferrer">Starting in Python 3.7, the evaluation of annotations can be postponed</a>:</p> <pre><code>&gt;&gt;&gt; from __future__ import annotations &gt;&gt;&gt; class Foo: ... bar: int ... baz: str ... &gt;&gt;&gt; Foo.__annotations__ {'bar': 'int', 'baz': 'str'} </code></pre> <p>note, the annotation is kept as a <em>string</em>, this also affects <code>dataclasses</code> as well:</p> <pre><code>&gt;&gt;&gt; @dataclasses.dataclass ... class Foo: ... bar: int ... baz: str ... &gt;&gt;&gt; dataclasses.fields(Foo) (Field(name='bar',type='int',default=&lt;dataclasses._MISSING_TYPE object at 0x7f806369bc10&gt;,default_factory=&lt;dataclasses._MISSING_TYPE object at 0x7f806369bc10&gt;,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD), Field(name='baz',type='str',default=&lt;dataclasses._MISSING_TYPE object at 0x7f806369bc10&gt;,default_factory=&lt;dataclasses._MISSING_TYPE object at 0x7f806369bc10&gt;,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)) </code></pre> <p>So, just be aware, since this will become the standard behavior, code you write should probably use the <code>__future__</code> import and work under that assumption, because in Python 3.10, this will become the standard behavior.</p> <p>The motivation behind this behavior is that the following currently raises an error:</p> <pre><code>&gt;&gt;&gt; class Node: ... def foo(self) -&gt; Node: ... return Node() ... Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;&lt;stdin&gt;&quot;, line 2, in Node NameError: name 'Node' is not defined </code></pre> <p>But with the new behavior:</p> <pre><code>&gt;&gt;&gt; from __future__ import annotations &gt;&gt;&gt; class Node: ... def foo(self) -&gt; Node: ... return Node() ... &gt;&gt;&gt; </code></pre> <p>One way to handle this is to use the <code>typing.get_type_hints</code>, which I believe just basically <code>eval</code>'s the type hints:</p> <pre><code>&gt;&gt;&gt; import typing &gt;&gt;&gt; typing.get_type_hints(Node.foo) {'return': &lt;class '__main__.Node'&gt;} &gt;&gt;&gt; class Foo: ... bar: int ... baz: str ... &gt;&gt;&gt; Foo.__annotations__ {'bar': 'int', 'baz': 'str'} &gt;&gt;&gt; import typing &gt;&gt;&gt; typing.get_type_hints(Foo) {'bar': &lt;class 'int'&gt;, 'baz': &lt;class 'str'&gt;} </code></pre> <p>Not sure how reliable this function is, but basically, it handles getting the appropriate <code>globals</code> and <code>locals</code> of <em>where the class was defined</em>. So, consider:</p> <pre><code>(py38) juanarrivillaga@Juan-Arrivillaga-MacBook-Pro ~ % cat test.py from __future__ import annotations import typing class Node: next: Node (py38) juanarrivillaga@Juan-Arrivillaga-MacBook-Pro ~ % python Python 3.8.5 (default, Sep 4 2020, 02:22:02) [Clang 10.0.0 ] :: Anaconda, Inc. on darwin Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; import test &gt;&gt;&gt; test.Node &lt;class 'test.Node'&gt; &gt;&gt;&gt; import typing &gt;&gt;&gt; typing.get_type_hints(test.Node) {'next': &lt;class 'test.Node'&gt;} </code></pre> <p>Naively, you might try something like:</p> <pre><code>&gt;&gt;&gt; test.Node.__annotations__ {'next': 'Node'} &gt;&gt;&gt; eval(test.Node.__annotations__['next']) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;&lt;string&gt;&quot;, line 1, in &lt;module&gt; NameError: name 'Node' is not defined </code></pre> <p>You could hack together something like:</p> <pre><code>&gt;&gt;&gt; eval(test.Node.__annotations__['next'], vars(test)) &lt;class 'test.Node'&gt; </code></pre> <p>But it can get tricky</p>
python|oop|python-dataclasses
7
1,903,612
72,415,531
'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')))
<p>When using this code, the following error is generated:</p> <blockquote> <p>exchangelib.errors.TransportError: HTTPSConnectionPool(host='mail.rt.yu', port=443): Max retries exceeded with url: /EWS/Exchange.asmx (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')))</p> </blockquote> <p>How can I provide a local issuer certificate or otherwise solve the problem?</p> <pre><code>from exchangelib import Credentials,DELEGATE, IMPERSONATION, Account,Message, Mailbox, FileAttachment,Configuration credentials = Credentials(username=r'sinai\afgggn.t.auu', password='SSft@y155') config = Configuration(server='mail.te.eg', credentials=credentials) account = Account(primary_smtp_address='afgggn.t.auu', config=config, autodiscover=False, access_type=DELEGATE) for item in account.inbox.all().order_by('-datetime_received')[:100]: print(item.subject, item.sender, item.datetime_received) </code></pre> <p>update This is the solution to the problem after the trouble of searching for solutions download the domain validation certificate as *.crt or *pem file open the file in editor and copy it's content to clipboard find your cacert.pem location: from requests.utils import DEFAULT_CA_BUNDLE_PATH; print(DEFAULT_CA_BUNDLE_PATH) edit the cacert.pem file and paste your domain validation certificate at the end of the file. Save the file and enjoy requests!</p>
<p>exchangelib uses <code>requests</code> to do the actual HTTP requests. This means you can set the <code>REQUESTS_CA_BUNDLE</code> environment variable. See <a href="https://stackoverflow.com/questions/31448854/how-to-force-requests-use-the-certificates-on-my-ubuntu-system">How to force requests use the certificates on my ubuntu system</a></p>
python|exchangelib
0
1,903,613
65,649,525
Pandas table viewing help in vscode Mac
<p>I do the usual import pandas as pd and then add a file path for pandas to read. eg:</p> <pre><code>filename = 'vaccination_tweets.csv' df = pd.read_csv(filename) df </code></pre> <p>however, when I run this, nothing shows up. How can I see the table with all the columns in vscode version 1.52.1?</p>
<p>You need to call the print function on your df variable. print(df)</p> <p>Perhaps you are used to doing this in Jupyter Notebooks where you can simply call df and it will display the table.</p>
python|pandas|dataframe|visual-studio-code
1
1,903,614
50,713,109
Combine two pandas df's based on a partial match
<p>Sorry about the vague heading, it's difficult to explain. </p> <p>I have two <code>pandas df's</code> which contain related information. One contains data that displays timestamps on when an event should occur and the other displays data on when that event actually occurs. </p> <p>I want to determine the difference between these timestamps. The issue is the values that represent each where these events are vary slightly. They are similar but aren't identical. So it's hard to <code>merge</code> or <code>concatenate</code> on a identical value.</p> <p>The first <code>df</code> is when the events should occur:</p> <p>Example df:</p> <pre><code>Sched = pd.DataFrame({ 'E' : ['Home','Shops','Away','Shops','Home'], 'F' : ['10:00:00','11:00:00','12:00:00','13:00:00','14:00:00'], 'G' : ['No: 10', 'No: 2', 'No: 1','No: 3','No: 11'], }) </code></pre> <p>So the place where events occur are labelled in <code>Column E</code>. e.g. <code>Home, Shops, Away</code>.</p> <p>This df displays when the event actually occurs:</p> <pre><code>Meet = pd.DataFrame({ 'A' : ['10:00:05','11:00:05','12:00:05','13:00:05','14:00:05'], 'B' : ['HOME LOCK','AWAY HR','SHOPS JK','HOME LOCK','SHOPS JK'], 'C' : ['No:','No:','No:','No:','No:'], 'D' : ['10', '1', '2','11','3'], }) </code></pre> <p>So the data in <code>Column B</code> is at the same meeting (Home, Away, Shops) but theres a few differences. It's all in capital letters, there's a few additional strings to some too.</p> <p>I have considered trying to map the appropriate codes in using:</p> <pre><code>Code = pd.DataFrame({ 'H' : ['HOME LOCK','AWAY HR','SHOPS JK'], 'I' : ['Home','Away','Shops'], }) Meet['B'] = Meet['B'].map(Code.set_index('H')['I']) </code></pre> <p>That way I could merge the output with the <code>sched df</code>. The problem is theres hundreds of codes and they continuously change each day. </p> <p>Is there a way to do a partial match of values? As in, can values which are largely the same be merged?</p>
<p>I believe is possible use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.title.html" rel="nofollow noreferrer"><code>title</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> if first word match:</p> <pre><code>Meet['E'] = Meet.B.str.title().str.split().str[0] print (Meet) A B C D E 0 10:00:05 HOME LOCK No: 10 Home 1 11:00:05 AWAY HR No: 1 Away 2 12:00:05 SHOPS JK No: 2 Shops 3 13:00:05 HOME LOCK No: 11 Home 4 14:00:05 SHOPS JK No: 3 Shops </code></pre> <p>Another more general solution is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>extract</code></a> by possible words joined by <code>|</code> for regex OR:</p> <pre><code>Meet['E'] = Meet.B.str.title().str.extract('(Home|Away|Shops)') print (Meet) A B C D E 0 10:00:05 HOME LOCK No: 10 Home 1 11:00:05 AWAY HR No: 1 Away 2 12:00:05 SHOPS JK No: 2 Shops 3 13:00:05 HOME LOCK No: 11 Home 4 14:00:05 SHOPS JK No: 3 Shops </code></pre> <p>what should be more dynamic if create pattern by unique values of <code>E</code> column of <code>Sched</code> with <code>\b</code> for word boundary:</p> <pre><code>pat = '|'.join(r"\b{}\b".format(x) for x in Sched.E.unique()) print (pat) \bHome\b|\bShops\b|\bAway\b Meet['E'] = Meet.B.str.title().str.extract('(' + pat + ')') print (Meet) A B C D E 0 10:00:05 HOME LOCK No: 10 Home 1 11:00:05 AWAY HR No: 1 Away 2 12:00:05 SHOPS JK No: 2 Shops 3 13:00:05 HOME LOCK No: 11 Home 4 14:00:05 SHOPS JK No: 3 Shops </code></pre>
python|pandas|merge|concatenation
3
1,903,615
3,603,883
Can python's mechanize use localhost sites?
<p>Can Mechanize access sites being locally hosted by Apache?</p>
<p>How about trying it out? Well, seriously, I used <a href="http://twill.idyll.org/" rel="nofollow noreferrer">twill</a> (a wrapper around mechanize) on localhost, and it worked. It just wants to make a http connection without knowing where it is. Is this the answer you expected?</p>
python|mechanize
0
1,903,616
3,548,254
restrict movable area of qgraphicsitem
<p>Is there a way to restrict the area where a <code>QGraphicsItem</code> like <code>QRect</code> can be moved when <code>setFlag(ItemIsMovable)</code> is set?</p> <p>I'm new to pyqt and trying to find a way to move an item with the mouse, and the restrict it to only vertically/horizontally.</p>
<p>If you want to keep a limited area you can reimplement the ItemChanged() </p> <p><em><strong>Declare:</em></strong></p> <pre><code>#ifndef GRAPHIC_H #define GRAPHIC_H #include &lt;QGraphicsRectItem&gt; class Graphic : public QGraphicsRectItem { public: Graphic(const QRectF &amp; rect, QGraphicsItem * parent = 0); protected: virtual QVariant itemChange ( GraphicsItemChange change, const QVariant &amp; value ); }; #endif // GRAPHIC_H </code></pre> <p><em><strong>implementation</em></strong> : ItemSendsGeometryChanges flag is needed to capture the change in position of QGraphicsItem</p> <pre><code>#include "graphic.h" #include &lt;QGraphicsScene&gt; Graphic::Graphic(const QRectF &amp; rect, QGraphicsItem * parent ) :QGraphicsRectItem(rect,parent) { setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemSendsGeometryChanges); } QVariant Graphic::itemChange ( GraphicsItemChange change, const QVariant &amp; value ) { if (change == ItemPositionChange &amp;&amp; scene()) { // value is the new position. QPointF newPos = value.toPointF(); QRectF rect = scene()-&gt;sceneRect(); if (!rect.contains(newPos)) { // Keep the item inside the scene rect. newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left()))); newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top()))); return newPos; } } return QGraphicsItem::itemChange(change, value); } </code></pre> <p>Then we define the rectangle of the scene, in this case will be 300x300</p> <pre><code>MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QGraphicsView * view = new QGraphicsView(this); QGraphicsScene * scene = new QGraphicsScene(view); scene-&gt;setSceneRect(0,0,300,300); view-&gt;setScene(scene); setCentralWidget(view); resize(400,400); Graphic * graphic = new Graphic(QRectF(0,0,100,100)); scene-&gt;addItem(graphic); graphic-&gt;setPos(150,150); } </code></pre> <p>This is to keep the graph within an area, good luck</p>
python|pyqt|pyqt4|qgraphicsview|qgraphicsitem
5
1,903,617
35,245,122
Get order of letters in a string python
<p>I'm trying to figure out how to get the order number of characters in a string. It should also take into consideration when the letter first occurs as the first order For example:</p> <pre><code> 'abc' = 1,2,3 'dfe' = 1,3,2 'xef' = 3,1,2 'aba' = 1,3,2 'bba' =2,3,1 </code></pre> <p>Is there a easy way to do so?</p>
<p>Maybe something like:</p> <pre><code>def ranker(s): ranked = sorted(range(len(s)),key=lambda x: (s[x], x)) d = dict(zip(ranked, range(len(ranked)))) return [d[i]+1 for i in range(len(s))] </code></pre> <p>which gives me</p> <pre><code>&gt;&gt;&gt; ranker("abc") [1, 2, 3] &gt;&gt;&gt; ranker("dfe") [1, 3, 2] &gt;&gt;&gt; ranker("xef") [3, 1, 2] &gt;&gt;&gt; ranker("aba") [1, 3, 2] &gt;&gt;&gt; ranker("bba") [2, 3, 1] &gt;&gt;&gt; ranker("bbac") [2, 3, 1, 4] </code></pre>
python|string|sorting
3
1,903,618
56,792,323
Colored text in command prompt after "cls" but not before "cls"
<p>I have a python program where I am trying to print "Hello" in colored text using ANSI codes in command prompt. When I print in normally, it is not working, it just prints ? and text, but when I print it after clearing the command prompt it works fine. Can some one explain this weird nature. </p> <p>I searched for this but couldn't find anything about this nature. I am using Windows 10</p> <p>The below code outputs <code>[0;32mHello[0m</code></p> <pre class="lang-py prettyprint-override"><code>print('\x1b[0;32m' + "Hello" + '\033[0m') </code></pre> <p><a href="https://i.stack.imgur.com/V85M0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V85M0.png" alt="no color"></a></p> <p>whereas the below code outputs Hello in green color.</p> <pre class="lang-py prettyprint-override"><code>os.system("cls") print('\x1b[0;32m' + "Hello" + '\033[0m') </code></pre> <p>Right image is the output of the code shown above or in the left image <a href="https://i.stack.imgur.com/DoA5C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DoA5C.png" alt="enter image description here"></a> &nbsp;<a href="https://i.stack.imgur.com/Jo8HL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jo8HL.png" alt="enter image description here"></a></p> <p>My expectation was that is gives either ansii or colored text in both the above codes, but actual output is different in both the cases</p>
<p>try this: </p> <pre><code>os.system("") print('\x1b[0;32m' + "Hello" + '\033[0m') </code></pre>
python|windows-10|command-prompt|ansi-colors
0
1,903,619
45,066,153
Am i making a mistake using global variables like this?
<p>Im trying to use global variables in order to declare them at the start of my code just like you would in C# however when ever i edit them in a function and i try call it in another function it throws an error saying that the variable is not declared?</p> <p>This is where i declare the variables:</p> <pre><code>from tkinter import * import os global Name global Wmain global directory global Username global Password global Code </code></pre> <p>This is where i change the the directory variable:</p> <pre><code>def NameGet(): Name = NameEntry.get() directory = ('C:\\Users\\Bradley\\Desktop\\Log In system\\Members\\' + Name + '.txt') CheckFile(Name) </code></pre> <p>This is where i am getting the error:</p> <pre><code>def SignUpFinished(): with open(directory, W) as F: F.write(Username) F.write(Password) F.write(Code) F.close() </code></pre> <p>Now i feel im either making a really novice mistake or something isnt working right with my code. any ideas? </p>
<p>In order to use global variable you need to explicitly set it inside a method.</p> <p>For example:</p> <pre><code>a=4 def func(): global a print(a) func() </code></pre>
python|tkinter
0
1,903,620
18,239,030
Django Generic Relations error: "cannot resolve keyword 'content_object' into field"
<p>I'm using Django's Generic Relations to define Vote model for Question and Answer models. </p> <p>Here is my vote model: <br></p> <p><strong>models.py</strong></p> <pre><code>class Vote(models.Model): user_voted = models.ForeignKey(MyUser) is_upvote = models.BooleanField(default=True) # Generic foreign key content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') class Meta: unique_together = ('content_type', 'user_voted') </code></pre> <p><br> <br></p> <p><strong>views.py</strong></p> <pre><code> user_voted = MyUser.objects.get(id=request.user.id) object_type = request.POST.get('object_type') object = None; if object_type == 'question': object = get_object_or_404(Question, id=self.kwargs['pk']) elif object_type == 'answer': object = get_object_or_404(Answer, id=self.kwargs['pk']) # THIS LAST LINE GIVES ME THE ERROR vote, created = Vote.objects.get_or_create(user_voted=user_voted, content_object=object) </code></pre> <p><br><br> And then I get this error:</p> <pre><code>FieldError at /1/ Cannot resolve keyword 'content_object' into field. Choices are: answer, content_type, id, is_upvote, object_id, question, user_voted </code></pre> <p><br><br> When I print the "object" to Django console, it prints "Question 1" object. So I don't understand why the line "content_object=object" gives me the field error...</p> <p>Any ideas :(((???</p> <p>Thanks</p>
<p><code>content_object</code> is a sort of read-only attribute that will retrieve the object specified by fields <code>content_type</code> and <code>object_id</code>. You should replace your code by the following:</p> <pre><code>from django.contrib.contenttypes.models import ContentType type = ContentType.objects.get_for_model(object) vote, created = Vote.objects.get_or_create(user_voted=user_voted, content_type=type, object_id=object.id) </code></pre> <p><strong>Edit:</strong> Django <a href="https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#django.contrib.contenttypes.fields.GenericForeignKey" rel="nofollow noreferrer">documentation</a> explicitly remarks:</p> <blockquote> <p>Due to the way GenericForeignKey is implemented, you cannot use such fields directly with filters (filter() and exclude(), for example) via the database API. Because a GenericForeignKey isn’t a normal field object, these examples will not work:</p> </blockquote> <pre><code># This will fail &gt;&gt;&gt; TaggedItem.objects.filter(content_object=guido) # This will also fail &gt;&gt;&gt; TaggedItem.objects.get(content_object=guido) </code></pre>
python|django|django-class-based-views
15
1,903,621
71,549,195
unable to recognize package in python
<p>I created a package like this:</p> <pre><code>└─dd a.py b.py __init__.py </code></pre> <p><code>a.py</code> and <code>__init__.py</code> is <strong>empty</strong>.</p> <p><code>b.py</code> is:</p> <pre><code>from dd import a </code></pre> <p>When I run the <code>b.py</code>, I get the error message:</p> <pre><code>from dd import a ModuleNotFoundError: No module named 'dd' </code></pre> <p>Why the <code>dd</code> package can't be recognized ?</p> <p><strong>UPDATE1</strong></p> <p>The reason I do this is that after I published my package to PyPl, and then, I imported it, but it reports the error that it can't recognize the module which is in the same package.</p> <p>For example, if I do it like this:</p> <pre><code># b.py import a </code></pre> <p>then publish the <code>dd</code> package to PyPl</p> <p><code>pip install dd</code></p> <p>If I try <code>from dd import b</code>, it will report the error that it doesn't kown what is <code>a</code></p> <p>So, how to solve this problem ?</p>
<p>You should do this inside <code>b.py</code>:</p> <pre class="lang-py prettyprint-override"><code>import a # or from a import * </code></pre>
python
0
1,903,622
69,591,391
Pytorch: using CUDA prevents optimization from working
<p>I have a very simple optimization: a straight line. Here is the code:</p> <pre><code>use_gpu = torch.cuda.is_available() learning_rate = 0.05 loss_function = nn.MSELoss() train_inputs = torch.FloatTensor([1,2,3,4,5,6]).T.unsqueeze(0) y_truth = torch.FloatTensor([10, 15, 20, 25, 30, 35]).unsqueeze(0) W = torch.nn.Parameter(torch.rand(1), requires_grad=True) b = torch.nn.Parameter(torch.rand(1), requires_grad=True) optimizer = optim.Adam([b, W], lr=learning_rate) # if use_gpu: # y_truth = y_truth.cuda() # W = W.cuda() # b = b.cuda() # train_inputs = train_inputs.cuda() for epoch in range(1000): optimizer.zero_grad() y_preds = b + W * train_inputs loss = loss_function(y_truth, y_preds) loss.backward() optimizer.step() if epoch % 100 == 0: print(loss.data, W.data, b.data) </code></pre> <p>That code works fine if I do not put the data on the GPU. If I uncomment the <code>if use_gpu</code> bloc, the code runs, but does not minimize anything and the variables do not update.</p> <p>I would expect the code to work similarly on the GPU or not. Any idea what is happening?</p> <p>Thanks!</p>
<blockquote> <p>Any idea what is happening?</p> </blockquote> <p>Yes, the parameters you are training, <code>W</code> and <code>b</code> stayed on the host (CPU).</p> <p>When you did</p> <pre><code>W = W.cuda() b = b.cuda() </code></pre> <p>you just chose to ignore the actual parameters being optimized.</p> <hr /> <p>If you wish to use the GPU for this, you could try:</p> <pre><code>W = torch.nn.Parameter(torch.rand(1).cuda()) b = torch.nn.Parameter(torch.rand(1).cuda()) </code></pre> <p>instead.</p>
pytorch|gpu
3
1,903,623
55,495,441
django request distant database
<p>I'm trying to request, in a django project "FIRST", an existing database for an other django project "SECOND" witch are deployed in two differents machines. I need to get in app 1 the values of an attribute's modele in app5 (as explained below). I've search "how django requests distant database" but i didn't found an answer to my question</p> <p>Thank you,</p> <p>Machine 1 (192.xxx.xx.xx) :</p> <pre><code> ----- project FIRST ------APP1 ------APP2 </code></pre> <p>Machine 2 (192.yyy.yy.yy) :</p> <pre><code> ----- project SECOND ------APP3 ------APP4 ------APP5 </code></pre>
<p>You need a RESTful API.</p> <p>A big topic, and I actually just answered it for another person.</p> <p>I suggest you <a href="https://stackoverflow.com/questions/55500246/django-send-a-post-request-through-form-to-another-server/55502006#55502006">check it out here.</a></p> <p>Once you make your API's, you can make some admin actions that go fetch the data, and populate your new database with the values of the old.</p> <p>At least that's one way of doing it.</p>
python|django
0
1,903,624
54,097,789
Django - create CSV on the fly and save it to filesystem and model file field
<p>In my django app, I have a management command which I want to use to process some data and create a model instance as well as file in filesystem and save its path to above instance's file field.</p> <p>My management command:</p> <pre><code>import datetime import timy from django.core.management.base import BaseCommand import tempfile from core.models import Entry from np_web.models import Dump import calendar import csv class Command(BaseCommand): help = 'Create dump and file for current day' def handle(self, *args, **options): with timy.Timer() as timer: today = datetime.date.today() dump_title = '{}.{}.{}.csv'.format(today.day, today.month, today.year) entries = Entry.objects.all() dump = Dump.objects.create(all_entries=entries.count()) dump.save() print('Dump created with uuid:', dump.uuid) print('Now create data file for dump') with tempfile.NamedTemporaryFile() as temp_csv: writer = csv.writer(temp_csv) writer.writerow([ 'Column1', 'Column2', ]) for entry in entries: writer.writerow([ entry.first_name, entry.last_name ]) dump.file.save(dump_title, temp_csv) </code></pre> <p>My Dump model:</p> <pre><code>class Dump(BaseModel): created = models.DateField(auto_now_add=True) all_entries = models.PositiveIntegerField() file = models.FileField(verbose_name=_('Attachment'), upload_to=dump_file_upload_path, max_length=2048, storage=attachment_upload_storage, null=True, blank=True) </code></pre> <p>Anyway, it doesn't work. It is throwing an error:</p> <pre><code>TypeError: a bytes-like object is required, not 'str' </code></pre> <p>I am also not sure if using temporary file is a best solution out there.</p>
<p>A few comments to hopefully direct you to a solution.</p> <p>For starters, <a href="https://docs.python.org/2/library/tempfile.html" rel="nofollow noreferrer">"If delete is true (the default), the file is deleted as soon as it is closed."</a>, and assuming that the spacing you have is correct, you are closing the file prior to attempting to save the file. This would result in the file being empty.</p> <p>My suggestion would be to simply create the file like normal, and delete it afterwards. A simple approach (though there may be a better) would be to create the file, save it, and then remove the original (temp) copy. </p> <p>In addition, when saving the file, you want to save it using Django's File wrapper.</p> <p>So you could do something like the following:</p> <pre><code>from django.core.files import File import os with open(temp, 'rb') as f: doc_file = File(f) dump.file.save("filename", doc_file, True) dump_file.save() try: os.remove(temp) except Expection: print('Unable to remove temp file') </code></pre>
python|django
0
1,903,625
54,104,822
Basic Python Scraper with TypeError: object of type 'Response' has no len()
<p>I'm new to coding a webscraper with Python. I've done a few tutorials and now I am trying my first one. A really simple test here that yields the error I noted in the Subject line. </p> <pre><code>import requests from bs4 import BeautifulSoup url = "https://www.autotrader.ca/cars/mercedes-benz/ab/calgary/?rcp=15&amp;rcs=0&amp;srt=3&amp;prx=100&amp;prv=Alberta&amp;loc=T3P%200H2&amp;hprc=True&amp;wcp=True&amp;sts=Used&amp;adtype=Private&amp;showcpo=1&amp;inMarket=advancedSearch" user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' html = requests.get(url,headers={'User-Agent': user_agent}) soup = BeautifulSoup(html, "lxml") print(soup) </code></pre> <p>Please help me out with trying out this code. Any help is greatly appreciated!</p>
<p>Use <code>html.text</code> instead of <code>html</code>. It's a good practice to send the headers binded with user-agent inside the get() method. </p> <pre><code>import requests from bs4 import BeautifulSoup url = "https://www.autotrader.ca/cars/mercedes-benz/ab/calgary/?rcp=15&amp;rcs=0&amp;srt=3&amp;prx=100&amp;prv=Alberta&amp;loc=T3P%200H2&amp;hprc=True&amp;wcp=True&amp;sts=Used&amp;adtype=Private&amp;showcpo=1&amp;inMarket=advancedSearch" headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'} response = requests.get(url,headers=headers) soup = BeautifulSoup(response.text,"lxml") return soup </code></pre>
python|beautifulsoup
1
1,903,626
58,413,697
How do i make a function that returns amount of indexes that are the same
<p>I'm trying to make a number based Mastermind game. Trying to figure out a function that takes two lists as paramenters and if indexes in the lists are the same it should return the amount of indexes that are the same.</p> <p>PS. hope you understand what i mean ;P</p> <pre><code>generated_number_as_list = [1,1,1,1] guess_as_list = [1,2,1,2] correct = right_inrightplace(guess_as_list, generated_number_as_list) print(correct) output &gt;&gt; 2 </code></pre>
<p>You can use zip to compare values with corresponding indexes and then sum True which will be cast to 1</p> <pre><code>print(sum(x==y for x,y in zip(generated_number_as_list, guess_as_list))) #2 </code></pre>
python|python-3.x|list
3
1,903,627
58,229,885
Python string manipulation moving a character from one spot to another
<p>I'm not too sure why this is not working but it's supposed to move the C to the right if . is to the right of it. this does not seem to change the city string at all. </p> <pre><code>import time city = 'C................R..................' position = (city.index('C')) for i in city: time.sleep(1) if city[position+1] == '.': city[position].replace('C','.') city[position+1].replace('.','C') position = (city.index('C')) print(city) </code></pre>
<p>Yes, like @Ruzihm and @Mark Meyer have mentioned, a string's character can not be replaced as if it is a list. You must convert it to a list first.</p> <p>But going by the problem you are trying to solve, I am wondering why can't you simply write like this if all you are looking for is making any existence of 'C.' into '.C'. Or am I misunderstanding something?</p> <pre><code>city = 'C................R................C..C' city = city.replace('C.', '.C') print(city) # should output: .C...............R.................C.C </code></pre>
python|string
1
1,903,628
58,469,704
Delete content of existing file and write again the content
<p>experts, the problem is a common and I have tried based on the solutions and examples in SO but still have problem to write all of my devices print output into a file. I have test using several methods and most of the time I'm only got last line of output in my text file. The problem below almost same as mine...but no luck for me.</p> <p><a href="https://stackoverflow.com/questions/40009858/how-to-delete-the-contents-of-a-file-before-writing-into-it-in-a-python-script?noredirect=1&amp;lq=1">How to delete the contents of a file before writing into it in a python script?</a></p> <p>I test the script to run specific command based on the type of device. If devices A run command A, if devices B run command B, if device C run command c. List of devices in text file ( the list have type and ip address). When i use 'w' the file content only the last line but when I use 'a' it will save all the content of all the devices in the list but when I run again the script it will continue to write on the last pointer and thus I got duplicate content..it append and keep append.</p> <p>when use outFileName, "w" output content only take last line content</p> <pre><code>OUTPUT CONTENT for device type C IP 10.2.10.12 </code></pre> <p>when use outFileName, "a" output content first time run the script as follows</p> <pre><code>OUTPUT CONTENT for device type A IP 192.168.100.100 OUTPUT CONTENT for device type A IP 192.168.100.110 OUTPUT CONTENT for device type B IP 10.1.10.100 OUTPUT CONTENT for device type C IP 10.2.10.10 OUTPUT CONTENT for device type C IP 10.2.10.11 OUTPUT CONTENT for device type C IP 10.2.10.12 </code></pre> <p>when run script second time ...the file contains duplicates as follows</p> <pre><code>OUTPUT CONTENT for device type A IP 192.168.100.100 OUTPUT CONTENT for device type A IP 192.168.100.110 OUTPUT CONTENT for device type B IP 10.1.10.100 OUTPUT CONTENT for device type C IP 10.2.10.10 OUTPUT CONTENT for device type C IP 10.2.10.11 OUTPUT CONTENT for device type C IP 10.2.10.12 OUTPUT CONTENT for device type A IP 192.168.100.100 OUTPUT CONTENT for device type A IP 192.168.100.110 OUTPUT CONTENT for device type B IP 10.1.10.100 OUTPUT CONTENT for device type C IP 10.2.10.10 OUTPUT CONTENT for device type C IP 10.2.10.11 OUTPUT CONTENT for device type C IP 10.2.10.12 </code></pre> <p>The script as follows</p> <pre><code>#Define functions for each device_type def type_A(ip): return{ 'device_type': 'A', 'ip': ip, 'username': 'usr10', 'password': 'password', } def type_B(ip): return{ 'device_type': 'B', 'ip': ip, 'username': 'usr10', 'password': 'password', } def type_C(ip): return{ 'device_type': 'C', 'ip': ip, 'username': 'usr10', 'password': 'password', } #Function to create output text file def writeOutFile(outFileName, string): with open(outFileName, "w") as f: outfile = f.write(string) #Open Text file that contain device type and ip address deviceFile = open('devices.txt','r') #Create list llist for each line in the file. #The first item is the device type, #The second item is the IP address for line in deviceFile: llist = line.split() ipAd = llist[1] #Check the first item of the list to determine device type and set #variables if llist[0] == 'A': dvs = type_A(ipAd) sendCommand = 'command for device type A' elif llist[0] == 'B': dvs = type_B(ipAd) sendCommand = 'command for device type B' elif llist[0] == 'C': dvs = type_C(ipAd) sendCommand = 'command for device type c' else: print("no valid device type") break dvs_connect = ConnectHandler(**dvs) sendCommand = (dvs_connect.send_command(sendCommand)) #This print all the devices output on the terminal print(sendCommand) #Generate output file outFileName = "outputFile.txt" #function call to write the output string into a text file writeOutFile(outFileName, sendCommand) dvs_connect.disconnect() deviceFile.close() </code></pre> <p>devices.txt list</p> <pre><code>A 192.168.100.100 A 192.168.100.110 B 10.1.10.100 C 10.2.10.10 C 10.2.10.11 C 10.2.10.12 </code></pre> <p>outputFile.txt The file output just content the last line content ...the output content of A and B seems already overwrite.</p> <pre><code>OUTPUT CONTENT for device type C IP 10.2.10.12 </code></pre> <p>I expect how many time i run the script it will overwrite the existing content of text file but no duplicate...if I got 6 devices in my devices.txt list...meaning that I should have 6 device output in my text file output. The output file should be like below</p> <pre><code>OUTPUT CONTENT for device type A IP 192.168.100.100 OUTPUT CONTENT for device type A IP 192.168.100.110 OUTPUT CONTENT for device type B IP 10.1.10.100 OUTPUT CONTENT for device type C IP 10.2.10.10 OUTPUT CONTENT for device type C IP 10.2.10.11 OUTPUT CONTENT for device type C IP 10.2.10.12 </code></pre> <p>I really hope someone could help me.. please assist. Thank you.</p>
<p>Opening with mode <code>'w'</code> truncates the file if it exists, while mode <code>'a'</code> will append to it.</p> <p>Your issue is that you are <em>re-opening the file with mode <code>'w'</code> for each line of output.</em> Every time you re-open the file, you clobber the previous contents.</p> <p>There are two solutions to this problem:</p> <ol> <li>The preferred solution would be to open the file <em>once</em> in your script and use the existing file handle to write multiple lines to it, instead of opening a new file handle for each line of output.</li> <li>You could also open the file once with mode <code>'w'</code> at the beginning of your script, then use mode <code>'a'</code> from then on (but this is a hack).</li> </ol> <p>One way to implement the first option would be to open the file right before the main loop:</p> <pre><code>with open("outputFile.txt", "w") as f: for line in deviceFile: # ... # Replace this line: # writeOutFile(outFileName, sendCommand) # With this one: f.write(sendCommand) </code></pre> <p>You may need to append a newline (<code>"\n"</code>) to this string before writing it; I can't see how <code>dvs_connect.send_command()</code> formats its output.</p>
python|overwrite|file-writing|erase
1
1,903,629
22,714,288
String pattern Regular Expression python
<p>I am a novice in regular expressions. I have written the following regex to find <code>abababab9</code> in the given string. The regular expression returns two results, however I was expecting one result.</p> <pre><code>testing= re.findall(r'((ab)*[0-9])',temp); **Output**: [('abababab9', 'ab')] </code></pre> <p>According to my understanding, it should have returned only <code>abababab9</code>, why has it returned <code>ab</code> <strong>alone</strong>.</p>
<p>You didnt' read the <code>findall</code> documentation:</p> <blockquote> <p>Return a list of all non-overlapping matches in the string.</p> <p><strong>If one or more capturing groups are present in the pattern, return a list of groups;</strong> this will be a list of tuples if the pattern has more than one group.</p> <p>Empty matches are included in the result.</p> </blockquote> <p>And if you take a look at the <a href="http://docs.python.org/2/library/re.html" rel="nofollow"><code>re</code></a> module capturing groups are subpatterns enclosed in parenthesis like <code>(ab)</code>.</p> <p>If you want to only get the complete match you can use one of the following solutions:</p> <pre><code>re.findall(r'(?:ab)*[0-9]', temp) # use non-capturing groups [groups[0] for groups in re.findall(r'(ab)*[0-9]', temp)] # take the first group [match.group() for match in re.finditer(r'(ab)*[0-9]', temp)] # use finditer </code></pre>
python|regex
2
1,903,630
45,470,328
Pandas get days in a between two two dates from a particular month
<p>I have a <code>pandas</code> dataframe with three columns. A start and end date and a month. </p> <p>I would like to add a column for how many days within the month are between the two dates. I started doing something with <code>apply</code>, the <code>calendar</code> library and some math, but it started to get really complex. I bet <code>pandas</code> has a simple solution, but am struggling to find it.</p> <p>Input:</p> <pre><code>import pandas as pd df1 = pd.DataFrame(data=[['2017-01-01', '2017-06-01', '2016-01-01'], ['2015-03-02', '2016-02-10', '2016-02-01'], ['2011-01-02', '2018-02-10', '2016-03-01']], columns=['start date', 'end date date', 'Month']) </code></pre> <p>Desired Output:</p> <pre><code> start date end date date Month Days in Month 0 2017-01-01 2017-06-01 2016-01-01 0 1 2015-03-02 2016-02-10 2016-02-01 10 2 2011-01-02 2018-02-10 2016-03-01 31 </code></pre>
<p>There is a solution: get a date list by <code>pd.date_range</code> between <code>start</code> and <code>end</code> dates, and then check how many date has the same <code>year</code> and <code>month</code> with the target month.</p> <pre><code>def overlap(x): md = pd.to_datetime(x[2]) cand = [(ad.year, ad.month) for ad in pd.date_range(x[0], x[1])] return len([x for x in cand if x ==(md.year, md.month)]) df1["Days in Month"]= df1.apply(overlap, axis=1) </code></pre> <p>You'll get:</p> <pre><code> start date end date date Month Days in Month 0 2017-01-01 2017-06-01 2016-01-01 0 1 2015-03-02 2016-02-10 2016-02-01 10 2 2011-01-02 2018-02-10 2016-03-01 31 </code></pre>
python|python-2.7|pandas
3
1,903,631
14,575,161
How can I use Pyro with gevent?
<p>Is it possible to use Pyro and gevent together? How would I go about doing this?</p> <p>Pyro wants to have its own event loop, which underneath probably uses epoll etc. I am having trouble reconciling the two.</p> <p>Help would be appreciated.</p>
<p>I use <code>gevent.spawn(daemon.requestLoop)</code>. I can't say more without knowing more about the specifics.</p>
python|gevent|pyro
1
1,903,632
68,802,030
Porting python code to C++ / (Printing out arrays in c++)
<p>I am currently learning C++ and being quite proficient in python, I decided to try porting some of my python code to C++. Specifically I tried porting this generator I wrote that gives the fibonacci sequence up to a certain given stop value.</p> <pre><code>def yieldFib(stop): a = 0 b = 1 yield i for i in range(2): for i in range(stop-2): fib = a+b a = b b = fib yield fib fib = list(yieldFib(100)) print(fib) </code></pre> <p>to this</p> <pre><code>int* fib(int stopp){ int a = 0; int b = 1; int fibN; int fibb[10000000]; fibb[0] = 0; fibb[1] = 1; for(int i=2; i&lt;stopp-2; i++){ fibN = a+b; a = b; b = fibN; fibb[i] = fibN; } return fibb; } int main(){ int stop; cin &gt;&gt; stop; int* fibbb = fib(stop); cout &lt;&lt; fibbb; } </code></pre> <p>I admit the c++ is very crude, but this is just to aid my learning. for some reason the code just crashes and quits after it takes user input, I suspect it has something to do with the way i try to use the array, but I'm not quite sure what. Any help will be appreciated</p>
<p>An integer array of size 10000000 is generally too large to be allocated on the stack, which causes the crash. Instead, use a <code>std::vector&lt;int&gt;</code>. In addition to that:</p> <ul> <li>The variable <code>b</code> is unused.</li> <li><code>fibN</code> is not initialized. Its value will be indeterminate.</li> <li>Returning a pointer to stack memory will not work, as that pointer is no longer valid once the function has returned.</li> <li>The code would print the value of an <em>integer pointer</em> instead of the values of the array. Instead, iterate over the array and print the values one by one.</li> </ul> <p>On a side note: It seems that you are trying to learn C++ by trial-and-error, while it is best learned from the ground up using a book or course.</p>
python|c++
4
1,903,633
41,381,528
view index, sort results export, pivot table python pandas
<p>I created a dataframe, table, from a pivot table in pandas. </p> <pre><code>df = pd.DataFrame({'v1':[5,5,6,6,1,5], 'v2':['c','a','b','a','a','b']}) table=pd.pivot_table(df,index=["v2"],values=["v1"],aggfunc=max) table.sort_values(by='v1', ascending=True) </code></pre> <p>1) I would like to see also in the table the results of v2. <br></p> <p>2) In order to sort I used a new line, is that possible to do it direclty in the pd.pivot_table sentence? <br></p> <p>3) in real world some tables are too big to see in the console, what's the best way to export results, to better check them, exporting to .csv?</p> <p>What I see in the console (Ipyhton shell) is this: </p> <pre><code>v2 v1 c 5 a 6 b 6 </code></pre>
<p>Instead of <code>pivoting</code> the table, a more straight forward alternative is grouped aggregation for your problem; To see <code>v2</code> as a normal column instead of index, you can use <code>reset_index()</code>; the sort part has to be applied separately but you can chain the <code>sort_values</code> directly after other commands, if you prefer one liner; to see a big table in console, usually you can use <code>.head()</code> to view a few top rows of your table:</p> <pre><code>df.groupby('v2').max().reset_index().sort_values('v1', ascending=True) # v2 v1 #2 c 5 #0 a 6 #1 b 6 </code></pre>
python|pandas|pivot
1
1,903,634
41,306,387
isalnum() in python is testing for True for all strings from a list
<p>Here is a simple code block. I'd like to test each element in the list to see if it contains an Alpha Numeric character for further processing.</p> <pre><code>#!/usr/bin/python words = ["cyberpunk" ,"x10", "hacker" , "x15" , "animegirl" , "x20"] for x in words: print x + " / " + str(x.isalnum()) </code></pre> <p>Unforunately this gives me this output:</p> <pre><code>cyberpunk / True x10 / True hacker / True x15 / True animegirl / True x20 / True </code></pre> <p>However if I test it as lets say:</p> <pre><code>x = "x10" print x.isalnum() x = "this sucks" print x.isalnum() </code></pre> <p>I get the right result!</p> <pre><code>True False </code></pre> <p>What's the different between the List strings and the standalone strings?</p>
<p>You seem to think <code>isalnum</code> returns True if a string contains both letters and numbers. What it actually does is return True if the string is <em>only</em> letters or numbers. Your last example contains a space, which is not a letter or number.</p> <p>You can build up the functionality you want:</p> <pre><code>words = ["cyberpunk" ,"x10", "hacker" , "x15" , "animegirl" , "x20", "this sucks"] def hasdigit(word): return any(c for c in word if c.isdigit()) def hasalpha(word): return any(c for c in word if c.isalpha()) def hasalnum(word): return hasdigit(word) and hasalpha(word) for word in words: print word,'/',hasalnum(word) </code></pre> <p>Output:</p> <blockquote> <pre><code>cyberpunk / False x10 / True hacker / False x15 / True animegirl / False x20 / True this sucks / False </code></pre> </blockquote>
python|string
4
1,903,635
41,535,845
which higher layer abstraction to use for tensorflow
<p>I am looking for higher layer abstractions for my deep learning project.</p> <p>Few doubts lately.</p> <ol> <li><p>I am really confused about which is more actively maintained <a href="https://github.com/tflearn/tflearn" rel="nofollow noreferrer">tflearn</a>(<a href="http://tflearn.org" rel="nofollow noreferrer">docs</a>), or <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/learn/python/learn" rel="nofollow noreferrer">tensorflow.contrib.learn</a>. But projects are different and actively contributed on Github. I did not find why are people working this way, same goal, same name, but working differently.</p></li> <li><p>That was not enough, we also have <a href="https://github.com/tensorflow/skflow" rel="nofollow noreferrer">skflow</a>, why do we have this project separately, this aims to mimic scikit-learn like functionality for deep learning(just like <strong>tflearn</strong> do).</p></li> <li><p>There are more and more coming, which one choose, and which one will be maintained in future? </p></li> </ol> <p>Any ideas?</p> <p><strong>PS</strong>: I know this might get closed. but I would definitely want some answers first. Those wanting it closed, please care to drop a reason/hint/link in comments</p>
<p>What about keras (<a href="https://keras.io/" rel="nofollow noreferrer">https://keras.io/</a>)? It is easy to use. However you can do pretty much everything you want with it. It uses either theano or tensorflow as its backend. Kaggle contests are often solved using keras (e.g. <a href="https://github.com/EdwardTyantov/ultrasound-nerve-segmentation" rel="nofollow noreferrer">https://github.com/EdwardTyantov/ultrasound-nerve-segmentation</a>).</p> <p>Edit:</p> <p>Because you did not specify python I would also recommend matconvnet if you look for more abstraction. </p>
python|tensorflow|deep-learning|skflow|tflearn
1
1,903,636
6,997,197
BASIC to Python program
<p>I have created a small program to see if I'm as proficient in Python as I am in FreeBasic (and I'm not that good with FreeBasic). Obviously, I'm asking this question because the answer is no.</p> <p>So the this program is a small Dungeons and Dragons (2nd edition) combat generator. For some reason, many functions don't execute at all. They are simply skipped over. This is what happens with <code>attaque1()</code>, <code>attaque2()</code> and most likely with <code>calcInitiative()</code> (since the cnt variable is not incremented at all). I tried globalizing a lot of variables thinking this might be the issue (I think all variables are globalized by default with FreeBasic). Well, this doesn't seem to be the answer. The bug is still there and I have absolutely no idea what might cause it.</p> <p>(The code has some French in it.)</p> <pre><code>#-*- coding: iso8859_1 -*- import random ca1 = 10 ca2 = 10 taco = 20 pv1 = random.randint(1,10) pv1 = (pv1) pv2 = random.randint(1,10) pv2 = str(pv2) cnt = 0 pv1Depart = pv1 pv2Depart = pv2 ast = "*" * 7 d20_1 = random.randint(1,20) d8_1 = random.randint(1,8) d20_2 = random.randint(1,20) d8_2 = random.randint(1,8) def intro(): global ca1 global ca2 global pv1 global pv2 print "Imaginez deux guerriers de D&amp;D 2e édition qui se battent." print print "Guerrier 1: " + str(pv1) + " PV, épée longue (1-8 points de dégât), TACO de 20, CA de " + str(ca1) + "." print "Guerrier 2: " + str(pv2) + " PV, épée longue (1-8 points de dégât), TACO de 20, CA de " + str(ca2) + "." print "" def nouveauCombat(): global cnt print ast + "NOUVEAU COMBAT" + ast print while ((pv1 &lt;= 0) or (pv2 &lt;= 0)): cnt = cnt + 1 print ast + "ROUND " + str(cnt) + ast print calcInitiative() print print ast + "RESULTAT" + ast print resultat() def calcInitiative(): global pv1 global pv2 global initiative1 global initiative2 initiative1 = random.randint(1,10) initiative2 = random.randint(1,10) print "Le guerre 1 fait son jet d'initiative." print str(initiative1) + "!" print print "Le guerre 2 fait son jet d'initiative." print str(initiative2) + "!" print if initiative1 == initiative2: print "Les deux guerriers attaquent au même moment." print print ast + "ATTAQUE" + ast print attaque1() print attaque2() elif initiative1 &lt; initiative2: print "Le guerrier 1 attaque en premier." print print ast + "ATTAQUE" + ast print attaque1() print if pv2 &lt;= 0: print attaque2() else: print "Le guerrier 2 attaque en premier." print print ast + "ATTAQUE" + ast print attaque2() print if pv1 &lt;= 0: print attaque2() def attaque1(): global d20_1 global d8_1 global pv2 global ca2 global pv2dep print "Le guerrier 1 fait son jet de toucher." print str(d20_1) + "!" if d20_1 &gt;= ca2: print "Touché!" pv2 = pv2 - d8_1 print str(d8_1) + "points de dégât!" print "Le guerrier 2 est à " + str(pv2) + "/" + str(pv2dep) + " PV!" else: print "Raté!" def attaque2(): global d20_2 global d8_2 global pv1 global ca1 global pv1dep print "Le guerrier 2 fait son jet de toucher." print str(d20_2) + "!" if d20_2 &gt;= ca1: print "Touché!" pv1 = pv1 - d8_2 print str(d8_2) + "points de dégât!" print "Le guerrier 1 est à " + str(pv1) + "/" + str(pv1dep) + " PV!" else: print "Raté!" def resultat(): global cnt print "Le combat prend fin au round " + str(cnt) + "." print intro() nouveauCombat() </code></pre>
<p><code>attaque1()</code> and <code>attaque2()</code> are called from <code>calcInitiative()</code> so if it doesn't get called they won't either.</p> <p>Your <code>while</code> loop executes while <code>((pv1 &lt;= 0) or (pv2 &lt;= 0))</code></p> <p>but you've defined them to be </p> <pre><code>pv1 = random.randint(1,10) pv1 = (pv1) # this line does nothing pv2 = random.randint(1,10) pv2 = str(pv2) </code></pre> <p>So neither can ever be <code>&lt;= 0</code> so the while loop will never be entered, and <code>calcInitiative()</code> will never be called.</p> <p>You're writing your Python code like it were BASIC. You should go through the Python tutorial, and probably a general tutorial on object oriented programming, to learn about things like classes.</p> <p>A good test for yourself is you should be able to write that program without using <code>global</code>s at all.</p>
python|freebasic
2
1,903,637
54,053,849
AttributeError: 'str' object has no attribute 'mean_validation_score'
<p>This error occurs in my code: <code>AttributeError: 'str' object has no attribute 'mean_validation_score'</code>. What can I do to resolve it?</p> <pre><code>def report(grid_scores, n_top=3): top_scores = sorted(grid_scores, key=itemgetter(1), reverse=True)[:n_top] for i, score in enumerate(top_scores): print("Rank: {0}".format(i + 1)) print("Mean validation score: {0:.3f} (std: {1:.3f})".format( score.mean_validation_score, np.std(score.cv_validation_scores))) print("Parameters: {0}".format(score.parameters)) print("") report(clf.cv_results_) </code></pre>
<p>The error is quite clear: <code>AttributeError: 'str' object has no attribute 'mean_validation_score'</code></p> <p>There is only one place you use <code>mean_validation_score</code> and the object you use it on is a <code>string</code> - not what <em>you</em> think it is. <code>string</code> does not support the method you use on it - hence the error:</p> <blockquote> <pre><code> for i, score in enumerate(top_scores): # score from here print("Rank: {0}".format(i + 1)) print("Mean validation score: {0:.3f} (std: {1:.3f})".format( score.mean_validation_score, # usage here np.std(score.cv_validation_scores))) </code></pre> </blockquote> <p>Obviosly the <code>top_scores</code> is a iterable of type string - hence when you enumerate it</p> <blockquote> <pre><code>for i, score in enumerate(top_scores): </code></pre> </blockquote> <p>it produces indexes <code>i</code> and strings <code>score</code>.</p> <p>You can resolve it by debugging your code:</p> <blockquote> <pre><code>top_scores = sorted(grid_scores, key=itemgetter(1), reverse=True)[:n_top] </code></pre> </blockquote> <p>and see why there are strings in it - fix that so it contains the objects that have <code>.mean_validation_score</code> and the error vanishes.</p> <hr> <p>Helpful:</p> <ul> <li><a href="https://stackoverflow.com/questions/1623039/python-debugging-tips">Python debugging tips</a></li> <li><a href="https://wiki.python.org/moin/PythonDebuggingTools" rel="nofollow noreferrer">https://wiki.python.org/moin/PythonDebuggingTools</a></li> <li><a href="https://ericlippert.com/2014/03/05/how-to-debug-small-programs/" rel="nofollow noreferrer">How to debug small programs</a></li> </ul>
python|python-3.x
3
1,903,638
44,420,135
filter object becomes empty after iteration?
<p>I'm learning how to use the <code>filter</code> function.</p> <p>This is the code I've written:</p> <pre><code>people = [{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80}, {'name': 'Sam'}] people2 = filter(lambda x: "height" in x, people) </code></pre> <p>As you can see what I'm trying to do is to remove all the dictionaries that don't contain the <code>'height'</code> key.</p> <p>The code works properly, in fact if I do:</p> <pre><code>print(list(people2)) </code></pre> <p>I get:</p> <pre><code>[{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80}] </code></pre> <p>The problem is that if I do it twice:</p> <pre><code>print(list(people2)) print(list(people2)) </code></pre> <p>the second time, I get an empty list.</p> <p>Can you explain me why?</p>
<p>This is a classic python3 doh!.</p> <p>A filter is a special iterable object you can iterate over. However, much like a generator, you can iterate over it only once. So, by calling <code>list(people2)</code>, you are iterating over each element of the <code>filter</code> object to generate the <code>list</code>. At this point, you've reached the end of the iterable and nothing more to return. </p> <p>So, when you call <code>list(people2)</code> again, you get an empty list.</p> <p>Demo:</p> <pre><code>&gt;&gt;&gt; l = range(10) &gt;&gt;&gt; k = filter(lambda x: x &gt; 5, l) &gt;&gt;&gt; list(k) [6, 7, 8, 9] &gt;&gt;&gt; list(k) [] </code></pre> <p>I should mention that with python2, <code>filter</code> returns a list, so you don't run into this issue. The problem arises when you bring py3's lazy evaluation into the picture.</p>
python|python-3.x
21
1,903,639
61,639,638
Didn't show desired output
<p>Hello fellow programmer. I followed this tutorial <a href="https://www.youtube.com/watch?v=QihjI84Z2tQ" rel="nofollow noreferrer">https://www.youtube.com/watch?v=QihjI84Z2tQ</a> Those server and client has successfully connected but when i try build it did not show the desired output on the client-side terminal. The server-side terminal does not react anything.</p> <p>this is my code for server side:</p> <pre><code>import socket import numpy as np import encodings HOST = '192.168.0.177' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are &gt; 1023) def random_data(): # ANY DATA YOU WANT TO SEND WRITE YOUR SENSOR CODE HERE x1 = np.random.randint(0, 55, None) # Dummy temperature y1 = np.random.randint(0, 45, None) # Dummy humidigy my_sensor = "{},{}".format(x1,y1) return my_sensor # return data seperated by comma def my_server(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: print("Server Started waiting for client to connect ") s.bind((HOST, PORT)) s.listen(5) conn, addr = s.accept() with conn: print('Connected by', addr) while True: data = conn.recv(1024).decode('utf-8') if str(data) == "Data": print("Ok Sending data ") my_data = random_data() x_encoded_data = my_data.encode('utf-8') conn.sendall(x_encoded_data) elif str(data) == "Quit": print("shutting down server ") break if not data: break else: pass if __name__ == '__main__': while 1: my_server() </code></pre> <p>and this is my client code:</p> <pre><code>import socket import threading import time HOST = '192.168.0.177' # The server's hostname or IP address PORT = 65432 # The port used by the server def process_data_from_server(x): x1, y1 = x.split(",") return x1,y1 def my_client(): threading.Timer(11, my_client).start() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) my = input("Data") my_inp = my.encode('utf-8') s.sendall(my_inp) data = s.recv(1024).decode('utf-8') x_temperature,y_humidity = process_data_from_server(data) print("Temperature {}".format(x_temperature)) print("Humidity {}".format(y_humidity)) s.close() time.sleep(5) if __name__ == "__main__": while 1: my_client() </code></pre> <p>I have tried many solution by printing <code>"Data"</code> directly to the terminal. can anyone help me?</p>
<p>Ok, I have found the problem. I am using Sublime Text 3 when running the client.py script When i post in the build it doesnt response nothing. So I change my IDE to PYCharm and then it worked. I don't know why. I hope that's helpful to other people that have this problem. Thank you very much.</p>
python|sockets|raspberry-pi|port|host
0
1,903,640
61,829,056
LinkExtractor RegEx for Scrapy
<p>In Scrapy, I'm using a LinkExtractor to crawl Indeed.com.</p> <pre><code>import scrapy from indeed.items import IndeedItem from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class IndeedSpider(CrawlSpider): name = 'indeedSpider' allowed_domains = ['indeed.com'] start_urls = ['https://www.indeed.com/q-Finance-jobs.html'] base_url = 'https://www.indeed.com' rules = [Rule(LinkExtractor(allow=(r'.+/rc/clk/.+')), callback='parse_job', follow=True)] def parse_job(self, response): print(response.url) </code></pre> <p>The start_url has plenty of links that follow the pattern <code>https://www.indeed.com/rc/clk/...</code>, such as: <a href="https://www.indeed.com/rc/clk?jk=e60b87b9a928dfb6&amp;fccid=8067e3333ec64c76&amp;vjs=3" rel="nofollow noreferrer">https://www.indeed.com/rc/clk?jk=e60b87b9a928dfb6&amp;fccid=8067e3333ec64c76&amp;vjs=3</a></p> <p>For some reason, none of them are firing. No errors, but parse_job is never being called.</p>
<p>Simplifying your rule to the following worked just fine for me:</p> <pre class="lang-py prettyprint-override"><code> rules = ( Rule(LinkExtractor(allow=('rc/clk',)), callback='parse_job'), ) </code></pre> <p>Because of some redirecting the printed response-urls will be in the form of for example:<br> <a href="https://www.indeed.com/viewjob?jk=e5c790a8fd2310d9&amp;from=serp&amp;vjs=3" rel="nofollow noreferrer">https://www.indeed.com/viewjob?jk=e5c790a8fd2310d9&amp;from=serp&amp;vjs=3</a></p>
python|regex|scrapy
0
1,903,641
23,838,972
Can I somehow select a specific element from dropdown list on the page via splinter module in Python
<p>Can I somehow select a specific element from dropdown list on the page via splinter module in Python?</p> <p>I have the following HTML code:</p> <pre><code>&lt;select id="xyz"&gt; &lt;optgroup label="Group1"&gt; &lt;option value="1"&gt;pick1&lt;/option&gt; &lt;option value="2"&gt;pick2&lt;/option&gt; &lt;/optgroup&gt; &lt;optgroup label="Group2"&gt; &lt;option value="3"&gt;pick3&lt;/option&gt; &lt;option value="4"&gt;pick4&lt;/option&gt; &lt;/optgroup&gt; &lt;/select&gt; </code></pre> <p>Suppose that I need to select "pick3" option. How can I do it?</p>
<p>First find the <code>select</code> element using <a href="http://splinter.cobrateam.info/docs/api/driver-and-element-api.html#splinter.driver.DriverAPI.find_by_id" rel="noreferrer"><code>find_by_id()</code></a> and use <a href="http://splinter.cobrateam.info/docs/api/driver-and-element-api.html#splinter.driver.DriverAPI.select" rel="noreferrer"><code>select()</code></a> method to select an option:</p> <pre><code>element = browser.find_by_id('xyz').first element.select('3') </code></pre> <p>Alternative solution would be to use <a href="http://splinter.cobrateam.info/docs/api/driver-and-element-api.html#splinter.driver.DriverAPI.find_by_xpath" rel="noreferrer"><code>find_by_xpath()</code></a> and <a href="http://splinter.cobrateam.info/docs/api/driver-and-element-api.html#splinter.driver.ElementAPI.click" rel="noreferrer"><code>click()</code></a>:</p> <pre><code>element = browser.find_by_xpath('//select[@id="xyz"]//option[@value="3"]').first element.click() </code></pre>
python|html|testing|splinter
8
1,903,642
24,159,654
J's x-type variables: how are they stored internally?
<p>I'm coding some J bindings in Python (<a href="https://gist.github.com/Synthetica9/73def2ec09d6ac491c98">https://gist.github.com/Synthetica9/73def2ec09d6ac491c98</a>). However, I've run across a problem in handling arbitrary-precicion integers: the output doesn't make any sense. It's something different everytime (but in the same general magnitude). The relevant piece of code: </p> <pre><code>def JTypes(desc, master): newdesc = [item.contents.value for item in desc] type = newdesc[0] if debug: print type rank = newdesc[1] shape = ct.c_int.from_address(newdesc[2]).value adress = newdesc[3] #string if type == 2: charlist = (ct.c_char.from_address(adress+i) for i in range(shape)) return "".join((i.value for i in charlist)) #integer if type == 4: return ct.c_int.from_address(adress).value #arb-price int if type == 64: return ct.c_int.from_address(adress).value </code></pre> <p>and</p> <pre><code>class J(object): def __init__(self): self.JDll = ct.cdll.LoadLibrary(os.path.join(jDir, "j.dll")) self.JProc = self.JDll.JInit() def __call__(self, code): #Exec code, I suppose. self.JDll.JDo(self.JProc, "tmp=:"+code) return JTypes(self.deepvar("tmp"),self) </code></pre> <p>Any help would be apreciated.</p>
<p>Short answer: <strong>J's extended precision integers are stored in <a href="https://github.com/sblom/openj-core/blob/master/vx.h#L12" rel="noreferrer">base 10,000</a></strong>.</p> <p>More specifically: A single extended integer is stored as an array of machine integers, each in the range [0,1e4). Thus, an array of extended integers is stored as a <a href="https://github.com/sblom/openj-core/blob/master/jtype.h#L41" rel="noreferrer">recursive data structure</a>. The array of extended integers has type=64 ("extended integer"), and its elements, each itself (a pointer to) an array, have type=4 ("integer").</p> <p>So, conceptually (using J notation), the array of large integers:</p> <pre><code>123456 7890123 456789012x </code></pre> <p>is stored as a nested array of machine integers, each less than 10,000:</p> <pre><code> 1e4 #.^:_1&amp;.&gt; 123456 7890123 456789012x +-------+-------+-----------+ |12 3456|789 123|4 5678 9012| +-------+-------+-----------+ </code></pre> <p>So, to recover the original large numbers, you'd have to interpret these digits¹ in base 10,000:</p> <pre><code> 10000x #.&amp;&gt; 12 3456 ; 789 123 ; 4 5678 9012 123456 7890123 456789012 </code></pre> <p>The only other 'x-type variables' in J are rational numbers, which, unsurprisingly, are stored as pairs of extended precision integers (one for the numerator, the other for the denominator). So if you have an array whose header indicates type='rational' and count=3, its data segment will have 6 elements (2*3). Take these pairwise and you have your array of ratios. </p> <p>If you're trying to build a complete J-Python interface, you'll also have to handle boxed and sparse arrays, which are similarly nested. You can learn a lot by inspecting the binary and hexadecimal representations of J nouns using the <a href="http://www.jsoftware.com/help/dictionary/dx003.htm" rel="noreferrer">tools built in to J</a>.</p> <p>Oh, and if you're wondering why J stores bignums in base 10,000? It's because 10,000 is big enough to keep the nested arrays compact, and a power-of-10 representation <a href="http://www.jsoftware.com/pipermail/general/2006-June/027231.html" rel="noreferrer">makes it easy to format numbers in decimal</a>.</p> <hr> <p>¹ Take care to adjust for byte order (e.g. <code>4 5678 9012</code> may be represented in memory as <code>9012 5678 4</code>).</p>
python|data-structures|j
11
1,903,643
20,687,319
python string encoding issues
<p>Is there a function in python that is equivalent to prefixing a string by 'u'?</p> <p>Let's say I have a string:</p> <pre><code>a = 'C\xc3\xa9dric Roger' </code></pre> <p>and I want to convert it to:</p> <pre><code>b = u'C\xc3\xa9dric Roger' </code></pre> <p>so that I can compare it to other unicode objects. How can I do this? My first instinct was to try:</p> <pre><code>&gt;&gt;&gt;&gt; b = unicode(a) Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;fragment&gt; UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128) </code></pre> <p>But that seems to be trying to decode the string. Is there a function for casting to unicode without doing any kind of decoding? (Is that what the 'u' prefix does or have I misunderstood?)</p>
<p>You need to specify an encoding:</p> <pre><code>unicode(a, 'utf8') </code></pre> <p>or, using <code>str.decode()</code>:</p> <pre><code>a.decode('utf8') </code></pre> <p>but do pick the right codec for your input; you clearly have UTF-8 data here but that may not always be the case.</p> <p>To understand what this does, I urge you to read:</p> <ul> <li><p><a href="http://joelonsoftware.com/articles/Unicode.html">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a> by Joel Spolsky</p></li> <li><p>The <a href="http://docs.python.org/2/howto/unicode.html">Python Unicode HOWTO</a></p></li> <li><p><a href="http://nedbatchelder.com/text/unipain.html">Pragmatic Unicode</a> by Ned Batchelder</p></li> </ul>
python|string|unicode|encode
7
1,903,644
20,431,099
GAE: Modeling user Upvote/Downvote on entities
<p>I've read different docs on fan-out and big data modeling, but I'm still struggling to figure out how to properly model information that is contextual for a signed in user. Using reddit as an example, I'm trying to model the Upvote/Downvote of a post. So here are two of my entities:</p> <pre><code>class Score(ndb.Model): post = schema.KeyProperty(required=True) user = schema.KeyProperty(required=True) score_value = schema.IntegerProperty(default=0) class Post(ndb.Model): # ... Other Properties ... # def fetch_score_async(self, user): self._score_query = Score.qry().filter(Score.post==self.key, Score.user==user.key).get_async() @property def user_score(self): ret = self._score_query.get_result() return ret.score_value if ret else 0 </code></pre> <p>Then I iterate over the list of posts in my result and call <code>fetch_score_async</code>.</p> <pre><code>posts = Post.qry().filter(...).fetch_page(50) for post in posts: post.fetch_score_async() </code></pre> <p>Lastly, I iterate the post list again and build up JSON. The theory here is that the scores will be fetched in parallel and my endpoint will be as fast as the post query plus the slowest score, rather than the sum of the scores. </p> <p>But what's the right way to do this? This feels unconventional and wrong. I've seen people suggest using a tasklet and/or map/reduce approach, but in those cases they have keys and a one-to-one or a one-to-many hierarchy (<a href="https://developers.google.com/appengine/docs/python/ndb/async#tasklets" rel="nofollow">google dev guide</a>).</p>
<p>You wanna use sharding. There's some stuff about sharding in the GAE docs, I'm sure you can look it up for yourself. Here's an example of a voting system designed for the GAE datastore:</p> <p><a href="http://eatdev.tumblr.com/post/15093224320/handling-user-ratings-on-app-engine" rel="nofollow">http://eatdev.tumblr.com/post/15093224320/handling-user-ratings-on-app-engine</a></p>
python|google-app-engine|google-cloud-datastore
1
1,903,645
36,008,732
Setting up a scheduled / cron job with Django on Elastic Beanstalk with a Worker Tier
<p>I'm currently in the process of migrating a Django website from my own hosted server running Ubuntu to AWS Elastic Beanstalk.</p> <p>I've found the process somewhat straight-forward so far - until trying to set up a few scheduled jobs for my app. From what I can gather, I want to run a cron job on a worker tier environment using a <code>cron.yaml</code> file. I've read through the docs: <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features-managing-env-tiers.html#worker-periodictasks" rel="noreferrer">http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features-managing-env-tiers.html#worker-periodictasks</a></p> <p>And read the blog post: <a href="https://medium.com/@joelennon/running-cron-jobs-on-amazon-web-services-aws-elastic-beanstalk-a41d91d1c571#.mx7dq9ufo" rel="noreferrer">https://medium.com/@joelennon/running-cron-jobs-on-amazon-web-services-aws-elastic-beanstalk-a41d91d1c571#.mx7dq9ufo</a></p> <p>And various StackOverflow posts, but I feel like I'm still missing some fundamental concepts about what actually makes up my worker tier environment. On my own server I could simply set up a cron job to fit this need - so this concept is rather new to me. I also have a few Django apps running on Heroku that use web and worker dynos, async processing, Redis and Celery and scheduled jobs, but I can't work out how to translate this into the Elastic Beanstalk world.</p> <p>Basically, the concepts I want to understand are:</p> <ol> <li>What actually makes up my worker tier environment as far as code goes? Obviously more than just the cron.yaml file. Is this an exact clone of my web app, deployed to this environment as well? Or can this somehow reference the code from my web environment and run that way?</li> <li>Or is the worker app its own complete whole new app altogether? Do I need to create a separate full-blown Django / Flask app to do this?</li> <li>How does my worker app physically talk to my web app? How is the POST messages in the cron.yaml actually meant to execute jobs on the web app? If it's a standalone app, how are the worker and web environments actually linked?</li> </ol> <p>I essentially want to schedule some Django management commands. I've exposed methods as POST endpoints as well but can't figure out how to get the worker environment to talk to / execute jobs on the web app.</p> <p>Excuse my naivety, I would really appreciate any sort of advice and direction on how this concept all comes together.</p>
<p>So I ended up talking to a friend who's more familiar with the AWS services. He explained the concepts, and I got the scheduled jobs running by setting up the worker environment as follows:</p> <ul> <li>Built a separate standalone application to the web environment. I built a separate "worker" Django app, but this could be Flask or really any other framework or language</li> <li>Created an app called "cron" that had views to handle POST messages to different endpoints, which are essentially the scheduled jobs I wanted to execute. These endpoints are what the jobs in my <code>cron.yaml</code> file direct to</li> <li>As my jobs needed to make database changes to the web app, I set up the worker app to use the same database as the web app. This was as simple as adding RDS environment variables to my worker environment configuration. Eg. Set RDS_DB_NAME, RDS_HOSTNAME, RDS_USERNAME to point to the web environment database</li> </ul> <p>Et voila, the scheduled jobs executed on schedule and make the database changes as required.</p>
python|django|amazon-web-services|cron|amazon-elastic-beanstalk
4
1,903,646
36,010,999
Convert pandas datetime month to string representation
<p>I want to have a pandas DataFrame with a timestamp column and want to create a column with just the month. I want to have the month column with string representations of the month, not with integers. I have done something like this:</p> <pre><code>df['Dates'] = pd.to_datetime(df['Dates']) df['Month'] = df.Dates.dt.month df['Month'] = df.Month.apply(lambda x: datetime.strptime(str(x), '%m').strftime('%b')) </code></pre> <p>However, this is some kind of a brute force approach and not very performant. Is there a more elegant way to convert the integer representation of the month into a string representation?</p>
<p>use vectorised <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="noreferrer"><code>dt.strftime</code></a> on your datetimes:</p> <pre><code>In [43]: df = pd.DataFrame({'dates':pd.date_range(dt.datetime(2016,1,1), dt.datetime(2017,2,1), freq='M')}) df Out[43]: dates 0 2016-01-31 1 2016-02-29 2 2016-03-31 3 2016-04-30 4 2016-05-31 5 2016-06-30 6 2016-07-31 7 2016-08-31 8 2016-09-30 9 2016-10-31 10 2016-11-30 11 2016-12-31 12 2017-01-31 In [44]: df['month'] = df['dates'].dt.strftime('%b') df Out[44]: dates month 0 2016-01-31 Jan 1 2016-02-29 Feb 2 2016-03-31 Mar 3 2016-04-30 Apr 4 2016-05-31 May 5 2016-06-30 Jun 6 2016-07-31 Jul 7 2016-08-31 Aug 8 2016-09-30 Sep 9 2016-10-31 Oct 10 2016-11-30 Nov 11 2016-12-31 Dec 12 2017-01-31 Jan </code></pre>
python|pandas|python-datetime
16
1,903,647
35,788,037
Installing a python package from source using ansible
<p>I have the following ansible playbook:</p> <pre><code>- hosts: all gather_facts: false sudo: true tasks: - name: Pull sources from the repository. git: repo=https://github.com/mongodb-labs/mongo-connector.git dest=/srv/checkout/mongo-connector - hosts: all sudo: true tasks: - name: copy local config.json to remote if exists local_action: stat path="./config.json" register: file ignore_errors: True - name: copy file if it exists copy: src=./config.json dest=/srv/checkout/mongo-connector/config.json force=yes when: file.stat.exists - hosts: all sudo: true tasks: - name: copy local install_mc.sh to remote if exists local_action: stat path="./install_mc.sh" register: file ignore_errors: True - name: copy installation scripts copy: src=./install_mc.sh dest=/srv/checkout/mongo-connector/install_mc.sh mode=755 when: file.stat.exists - name: Execute script script: /srv/checkout/mongo-connector/install_mc.sh </code></pre> <p>Here I pull a repository from github, then I copy a <code>config.json</code> to the folder I cloned the git repository. After that I need to run <code>python setup.py install</code> to install the package and then <code>python setup.py install_service</code> in the same directory.</p> <p>I put both the installation commands in a shell file <code>install_mc.sh</code> and the copied the file to the same directory where I cloned the repository.</p> <p>The git repository is cloned in <code>/srv/checkout/mongo-connector/</code>. </p> <p>Following is the directory layout:</p> <pre><code>vagrant@vagrant-ubuntu-trusty-64:/srv/checkout/mongo-connector$ pwd /srv/checkout/mongo-connector vagrant@vagrant-ubuntu-trusty-64:/srv/checkout/mongo-connector$ ls CHANGELOG.rst config.json ez_setup.py install_mc.sh LICENSE mongo_connector README.rst scripts setup.cfg setup.py tests </code></pre> <p>But then I run the ansible script using vagrant I get the followin error during the execution of <code>install_mc.sh</code>:</p> <pre><code>==&gt; connector: TASK [Execute script] ********************************************************** ==&gt; connector: task path: /vagrant/provisioning/mc_playbook.yml:36 ==&gt; connector: fatal: [127.0.0.1]: FAILED! =&gt; {"changed": true, "failed": true, "rc": 2, "stderr": "chmod: cannot access ‘./setup.py’: No such file or directory\npython: can't open file './setup.py': [Errno 2] No such file or directory\npython: can't open file './setup.py': [Errno 2] No such file or directory\n", "stdout": "", "stdout_lines": []} ==&gt; connector: ==&gt; connector: NO MORE HOSTS LEFT ************************************************************* ==&gt; connector: to retry, use: --limit @mc_playbook.retry ==&gt; connector: ==&gt; connector: PLAY RECAP ********************************************************************* ==&gt; connector: 127.0.0.1 : ok=10 changed=4 unreachable=0 failed=1 </code></pre> <p>Content of <code>install_mc.sh</code> is:</p> <pre><code>#!/usr/bin/env bash chmod +x ./setup.py python ./setup.py install python ./setup.py install_service </code></pre> <p>How should I correct this issue?</p>
<p>I think the problem is that you're assuming that the <code>install_mc</code> script is being executed from the directory that you copied it to, but the <a href="http://docs.ansible.com/ansible/script_module.html" rel="nofollow"><code>script</code></a> module actually reads from your local machine, and executes the script in the home directory of the remote node.</p> <blockquote> <p>The script module takes the script name followed by a list of space-delimited arguments. The local script at path will be transferred to the remote node and then executed. The given script will be processed through the shell environment on the remote node. This module does not require python on the remote system, much like the raw module.</p> </blockquote> <p>As DeHaan later suggests, you'll probably have better luck with just running your two setup.py commands with the <a href="http://docs.ansible.com/ansible/command_module.html" rel="nofollow"><code>command</code></a> module. That one allows you to specify a directory (with the <code>chdir</code> option).</p> <p>The chmod is probably unnecessary because 1) you're calling the script with the python binary, and 2) the mongo maintainers likely established the appropriate permissions in their git repository.</p>
python|shell|ansible
2
1,903,648
15,141,538
Python-Twitter API GetLocation
<p>I am trying to get the location information from Twitter profiles using the python-twitter API (<a href="http://code.google.com/p/python-twitter/" rel="nofollow">http://code.google.com/p/python-twitter/</a>). The documentation (<a href="http://static.unto.net/python-twitter/0.5/doc/twitter.html" rel="nofollow">http://static.unto.net/python-twitter/0.5/doc/twitter.html</a>) states that there is a GetLocation call, but I can't seem to get it to work.</p>
<p>With the <a href="https://github.com/ryanmcgrath/twython" rel="nofollow">Twython Library</a> you can get the location information for a user with a specific user name as follows:</p> <pre><code>from twython import Twython twitter = Twython(APP_KEY, APP_SECRET,OAUTH_TOKEN, OAUTH_TOKEN_SECRET) print twitter.show_user(screen_name=USER_NAME)["location"] </code></pre> <p>It should be similar for other libraries.</p> <p>I hope this helps.</p>
python|twitter
2
1,903,649
15,438,586
Can Python avoid reevaluation in a statement?
<p>I have the following statement in Python, where ori is a string</p> <pre> [ori[ori.rfind(' ') + 1:], ori[:ori.rfind(' ')]] </pre> <p>We can see ori.rfind(' ') is called twice, is the interpreter smart enough to just evaluate the function only once?</p> <p>We could do the following:</p> <pre> s = ori.rfind(' ') return [ori[s+1:], ori[:s]] </pre> <p>But this uses two lines. I intend to use this statement in a list comprehension over list of strings and hope this function is one line. </p> <p>In this case, it is actually easier for the interpreter to figure out, since string is an immutable. My guess is perhaps interpreter can be smart to avoid reevaluation. In general, if the object is an immutable, could the interpreter be smart enough?</p>
<p>I don't think you can count on the interpreter evaluating the function only once, however here is an equivalent alternative to your current code which is shorter and similar in efficiency to the two line method:</p> <pre><code>ori.rsplit(' ', 1)[::-1] </code></pre> <p>Example and timing comparison:</p> <pre><code>In [1]: ori = 'foo bar baz' In [2]: [ori[ori.rfind(' ') + 1:], ori[:ori.rfind(' ')]] Out[2]: ['baz', 'foo bar'] In [3]: ori.rsplit(' ', 1)[::-1] Out[3]: ['baz', 'foo bar'] In [4]: %timeit [ori[ori.rfind(' ') + 1:], ori[:ori.rfind(' ')]] 1000000 loops, best of 3: 732 ns per loop In [5]: %timeit ori.rsplit(' ', 1)[::-1] 1000000 loops, best of 3: 514 ns per loop In [6]: %timeit s = ori.rfind(' '); [ori[s+1:], ori[:s]] 1000000 loops, best of 3: 490 ns per loop </code></pre>
python
5
1,903,650
29,682,897
How to convert neo4j return types to python types
<p>I am using py2neo and I would like to extract the information from query returns so that I can do stuff with it in python. For example, I have a DB containing three "Person" nodes:</p> <p><code>for num in graph.cypher.execute("MATCH (p:Person) RETURN count(*)"): print num</code></p> <p>outputs:</p> <p><code>&gt;&gt; count(*)</code></p> <p><code>3</code></p> <p>Sorry for shitty formatting, it looks essentially the same as a mysql output. However, I would like to use the number 3 for computations, but it has type <code>py2neo.cypher.core.Record</code>. How can I convert this to a python int so that I can use it? In a more general sense, how should I go about processing cypher queries so that the data I get back can be used in Python?</p>
<p>can you int(), float() str() on the <code>__str__()</code> method that looks to be outputting the value you want in your example?</p>
python|neo4j|type-conversion|py2neo
0
1,903,651
46,546,946
date can not be serialized
<p>I am getting an error while trying to save the dataframe as a file.</p> <pre><code>from fastparquet import write write('profile_dtl.parq', df) </code></pre> <p>The error is related to "date" and the error message looks like this...</p> <pre><code>ValueError: Can't infer object conversion type: 0 1990-01-01 1 1954-01-01 2 1981-11-15 3 1993-01-21 4 1948-01-01 5 1977-01-01 6 1968-04-28 7 1969-01-01 8 1989-01-01 9 1985-01-01 Name: dob, dtype: object </code></pre> <p>I have checked that the column is "object" just like any other column that can be serialized without any problem. If I remove the "dob" column from the dataframe, then this line will work. This will also work if there is date+time. </p> <p>Only dates are not accepted by fast-parquet?</p>
<p>Try changing <code>dob</code> to <code>datetime64</code> dtype:</p> <pre><code>import pandas as pd dob = pd.Series(['1954-01-01', '1981-11-15', '1993-01-21', '1948-01-01', '1977-01-01', '1968-04-28', '1969-01-01', '1989-01-01', '1985-01-01'], name='dob') Out: 0 1954-01-01 1 1981-11-15 2 1993-01-21 3 1948-01-01 4 1977-01-01 5 1968-04-28 6 1969-01-01 7 1989-01-01 8 1985-01-01 Name: dob, dtype: object </code></pre> <p>Note the dtype that results:</p> <pre><code>pd.to_datetime(dob) Out: 0 1954-01-01 1 1981-11-15 2 1993-01-21 3 1948-01-01 4 1977-01-01 5 1968-04-28 6 1969-01-01 7 1989-01-01 8 1985-01-01 dtype: datetime64[ns] </code></pre> <p>Using this Series as an index in a DataFrame:</p> <pre><code>baz = list(range(9)) foo = pd.DataFrame(baz, index=pd.to_datetime(dob), columns=['dob']) </code></pre> <p>You should be able to save your Parquet file now.</p> <pre><code>from fastparquet import write write('foo.parquet', foo) </code></pre> <p></p> <pre><code>$ls -l foo.parquet -rw-r--r-- 1 moi admin 854 Oct 13 16:44 foo.parquet </code></pre> <p><hr> Your <code>dob</code> Series has an object dtype and you left unchanged the <code>object_encoding='infer'</code> argument to <code>fastparquet.write</code>. So, from the <a href="http://fastparquet.readthedocs.io/en/latest/api.html#fastparquet.write" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>"The special value 'infer' will cause the type to be guessed from the first ten non-null values."</p> </blockquote> <p>Fastparquet does not <a href="http://fastparquet.readthedocs.io/en/latest/_modules/fastparquet/writer.html?highlight=find_type" rel="nofollow noreferrer">try to infer</a> a date value from what it expects to be one of <code>bytes|utf8|json|bson|bool|int|float</code>.</p>
pandas|parquet|fastparquet
2
1,903,652
49,393,132
Python Regex Multiline, finds lines starting with 00, but not 20
<p>I have a python script(below) that is supposed to find lines in a text file starting with 00 and 20, then output the lines to two separate files, one for 00, and one for 20. It works just fine on output1, but produces an empty tuple for output2. What am I doing wrong? The lines in the text file are all the same, no special characters, and it either starts with a 00 or 20.</p> <pre><code>import sys import re import glob import os listfiles = glob.glob('*.txt') def DataExtract(inputfilename): myfilename1 = open('00 extract ' + inputfilename,'w') myfilename2 = open('20 extract ' + inputfilename,'w') with open(inputfilename, 'r') as f: output1 = re.findall(r'^00.*', f.read(), re.MULTILINE) output2 = re.findall(r'^20.*', f.read(), re.MULTILINE) wout1 = "\n".join(output1) wout2 = "\n".join(output2) print (wout2) print (output2) myfilename1.write(wout1) myfilename2.write(wout2) myfilename1.close myfilename2.close for n in listfiles: DataExtract(n) </code></pre> <p>Please help! Thank you.</p>
<p>When you call <code>f.read()</code> the second time, there is nothing more to read as the first <code>f.read()</code> alread consumed the file stream. Thus, you might solve the issue if you read the file into a variable and then used it instead of the <code>f.read()</code>, but since you are working with literal texts, you might just as well read the file line by line and use a <code>str.startswith()</code> check:</p> <pre><code>def DataExtract(inputfilename): myfilename1 = open('00 extract ' + inputfilename,'w') myfilename2 = open('20 extract ' + inputfilename,'w') with open(inputfilename, 'r') as f: for line in f: if line.startswith('00'): myfilename1.write(line) elif line.startswith('20'): myfilename2.write(line) myfilename1.close() myfilename2.close() </code></pre>
regex|python-3.x|multiline
2
1,903,653
70,364,727
How to check OS variables and use them with same name as Python variable from a list
<p>hopefully i can explain right what i am trying to do. I want to check if variables giving from a list, exists in OS, if so, use the same OS variable name and value in python.</p> <p>This is how am i doing it right now but i think it is a lot of code and if want more os variables i would be bigger. So what could be a good starting to do this smarter and more efficient?</p> <p>OS (linux) variables</p> <pre class="lang-sh prettyprint-override"><code>export WEB_URL=&quot;https://google.com&quot; export WEB_USERNAME=&quot;Foo&quot; export WEB_PASSWORD=&quot;Bar&quot; </code></pre> <pre class="lang-py prettyprint-override"><code># Check os env variables if &quot;WEB_URL&quot; in os.environ: web_url = os.environ.get(&quot;WEB_URL&quot;) else: logger.error(&quot;No URL os env find please check&quot;) if &quot;WEB_USERNAME&quot; in os.environ: web_username = os.environ.get(&quot;WEB_USERNAME&quot;) else: logger.error(&quot;No USERNAME os env find please check&quot;) if &quot;WEB_PASSWORD&quot; in os.environ: web_password = os.environ.get(&quot;WEB_PASSWORD&quot;) else: logger.error(&quot;No PASSWORD os env find please check&quot;) </code></pre> <p>must be somthing like this to start with?</p> <pre class="lang-py prettyprint-override"><code>os_variables = [&quot;WEB_URL&quot;, &quot;WEB_USERNAME&quot;, &quot;WEB_PASSWORD&quot;] for var in os_variables: if var in os.environ: print(var.lower(), &quot;=&quot;, os.environ.get(f&quot;{var}&quot;)) </code></pre> <p>result:</p> <pre><code>web_url = https://google.com web_username = Foo web_password = Bar </code></pre> <p>so what is printed here above should literally be the variable, just to show what i mean</p>
<p>as a compromise I finally came up with this as a solution</p> <pre class="lang-py prettyprint-override"><code>env_variables = ('WEB_URL', 'WEB_USERNAME', 'WEB_PASSWORD') def check_env(var): for var in env_variables: if var in os.environ: if os.environ[var] == &quot;&quot;: logging.error(f'{var} is empty, please set a value') sys.exit() else: logging.error( f'{var} does not exist, please setup this env variable') sys.exit() check_env(env_variables) </code></pre>
python|python-3.x|environment-variables
0
1,903,654
70,358,372
Given a rod of length N , you need to cut it into R pieces , such that each piece's length is positive, how many ways are there to do so?
<p><strong>Description:</strong></p> <p>Given two positive integers N and R, how many different ways are there to cut a rod of length N into R pieces, such that the length of each piece is a positive integer? Output this answer modulo 1,000,000,007.</p> <p><strong>Example:</strong></p> <p>With N = 7 and R = 3, there are 15 ways to cut a rod of length 7 into 3 pieces: (1,1,5) , (1,5,1), (5,1,1) , (1,2,4) , (1,4,2) (2,1,4), (2,4,1) , (4,1,2), (4,2,1) , (1,3,3), (3,1,3), (3,3,1), (2,2,3), (2,3,2), (3,2,2).</p> <p><strong>Constraints:</strong></p> <pre><code>1 &lt;= R &lt;= N &lt;= 200,000 </code></pre> <p><strong>Testcases:</strong></p> <pre><code> N R Output 7 3 15 36 6 324632 81 66 770289477 96 88 550930798 </code></pre> <p><strong>My approach:</strong></p> <p>I know that the answer is <code>(N-1 choose R-1) mod 1000000007</code>. I have tried all different ways to calculate it, but always 7 out of 10 test cases went time limit exceeded. Here is my code, can anyone tell me what other approach I can use to make it in <code>O(1)</code> time complexity.</p> <pre class="lang-py prettyprint-override"><code>from math import factorial def new(n, r): D = factorial(n - 1) // (factorial(r - 1) * factorial(n - r)) return (D % 1000000007) if __name__ == '__main__': N = [7, 36, 81, 96] R = [3, 6, 66, 88] answer = [new(n, r) for n,r in zip(N,R)] print(answer) </code></pre>
<p>I think there's two big optimizations that the problem is looking for you to exploit. The first being to cache intermediate values of <code>factorial()</code> to save computational effort across large batches (large <code>T</code>). The second optimization being to reduce your value mod <code>1000000007</code> incrementally, so your numbers stay small, and multiplication stays a constant-time. I've updated the below example to precompute a factorial table using a custom function and <code>itertools.accumulate</code>, instead of merely caching the calls in a recursive implementation (which will eliminate the issues with recursion depth you were seeing).</p> <pre class="lang-py prettyprint-override"><code>from itertools import accumulate MOD_BASE = 1000000007 N_BOUND = 200000 def modmul(m): def mul(x, y): return x * y % m return mul FACTORIALS = [1] + list(accumulate(range(1, N_BOUND+1), modmul(MOD_BASE))) def nck(n, k, m): numerator = FACTORIALS[n] denominator = FACTORIALS[k] * FACTORIALS[n-k] return numerator * pow(denominator, -1, m) % m def solve(n, k): return nck(n-1, k-1, MOD_BASE) </code></pre> <p>Running this against the example:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; pairs = [(36, 6), (81, 66), (96, 88)] &gt;&gt;&gt; print([solve(n, k) for n, k in pairs]) [324632, 770289477, 550930798] </code></pre>
python|math|combinations|dynamic-programming|permutation
3
1,903,655
54,893,336
Numerical Quadrature of scalar valued function with vector input using scipy
<p>I have been trying to use <code>scipy.integrate.quadrature</code> for integrating a scalar-valued function that takes as input a vector of fixed dimension. However, despite the claim of <code>scipy.integrate.quadrature</code> that it can take functions with vector inputs, I cannot for the life of me understand how to make this work.</p> <p>It is possible that I am misunderstanding the documentation for <code>scipy.integrate.quadrature</code> and that when it says the function can take vector inputs it simply means that it is able to evaluate the function at multiple points simultaneously (which is not equivalent to my problem). </p> <p>More specifically I am trying to integrate over a function, f(<strong>x</strong>), where <strong>x</strong> is a vector and f() maps <strong>x</strong> to a scalar. If its true that my initial interpretation of <code>scipy.integrate.quadrature</code> is false, does anyone know of any packages (written in <code>python</code>) that can compute an integral in the way that I have mentioned ? I know there is something called <code>scipy.integrate.nquad</code> which perhaps is what I'm looking for? Any guidance or insight here would be awesome. </p>
<p>If your function takes a vector-valued <code>x</code> as input, it means its domain some subset of the n-dimensional space. For quadrature, that makes it an entirely different beast which is why you're having problems.</p> <p>What's your domain of integration? A rectangle in 3D? A ball in 4D? A prism? Perhaps the entire nD space with a weight function like <code>exp(-norm(x)^2)</code>? (See picture below for an graphical representation of integration rule in 3D.) Depending on that, there are different integration rules. Check out <a href="https://github.com/nschloe/quadpy" rel="nofollow noreferrer">quadpy</a> (a Python package of mine).</p> <p><a href="https://i.stack.imgur.com/24uCb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/24uCb.png" alt="enter image description here"></a></p>
tensorflow|scipy|numerical-integration
0
1,903,656
33,146,245
How to send command to receipt printers from Django app?
<p>I have created a simple POS application. I now have to send a command to the receipt printer to print the receipt. I don't have any code related to this problem as I don't know where to start even. My questions are:</p> <p>1) Is Windows a good choice for working with receipt printers as every shop I went to use a desktop application on Windows for POS?</p> <p>2) Is it possible to control the receipt printer and cash register/drawer from a web app?</p> <p>3) Is there a good reading material for developing POS systems by myself?</p>
<p>For a web app to use a device on the client, it has to go through the browser. I may be wrong, but I seriously doubt this is a built-in feature for receipt printers. I see three options:</p> <p>1) Find/make a normal printer driver that works with your receipt printer, put it on the client box, and just use the normal print js commands.</p> <p>2) Find/make a browser plugin that talks to the printer and exposes an API.</p> <p>3) Find/make a simple web app that talks to a server-connected receipt printer (probably via native code execution or script call), and install it on each POS, with CORS to allow remote origin; then just post to that on <code>127.0.0.1:whatever</code> from the webapp client script.</p> <p>Side note: I seriously discourage connecting a POS to anything resembling a network any more than absolutely necessary. Every outbound network request or trusted network peer is a potential attack vector. In short, I would never use django or any other web app for physical POS software.</p>
python|django|printing|receipt
0
1,903,657
33,192,631
Can someone help me with my code? (python)
<p>So I get this error message:</p> <pre><code>Traceback (most recent call last): File "C:/Users/Ethan/Documents/Coding/test2.py", line 3, in &lt;module&gt; buy = input("Marijuana plants cost 200$ ea, opium seeds cost 300$") File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'm' is not defined </code></pre> <p>I bet it will be obvious but, I'm new to python and need some help.</p> <p>code:</p> <pre><code>balance = 2500 FinalPrice = 0 buy = input("Marijuana plants cost 200$ ea, opium seeds cost 300$") while (buy != "o") and (buy != "m"): buy = input("That's not on the market! type 'm' if you want to buy Marijuana and 'o' if you want opium!") if buy =="o": o = input("How many opium seeds? Press c to cancel") if o=="0": o = input("invalid number, input again") elif o =="c": input("You cancelled the trade. Type in a command to do something else") oprice = (o*300) print(oprice) FinalPrice-=FinalPrice FinalPrice+=oprice obuy = input("This is the final price, press b to buy or c to cancel") if obuy =="c": input("You cancelled the trade. Type in a command to do something else") elif obuy =="b": if oprice &gt; balance: print("Not enough money! Sell more drugs to earn more money.") elif oprice &lt; balance: print("you bought", o , "Opium seeds for", oprice , "$") input("What do you want to do next?") elif buy =="m": m = input("How many Marijuana plants? Press c to cancel") if m=="0": m = input("invalid number, input again") elif m =="c": input("You cancelled the trade. Type in a command to do something else") mprice = (m*200) print(mprice) FinalPrice-=FinalPrice FinalPrice+=mprice mbuy = input("This is the final price, press b to buy or c to cancel") if mbuy =="c": input("You cancelled the trade. Type in a command to do something else") elif mbuy =="b": if mprice &gt; balance: print("Not enough money! Sell more drugs to earn more money.") elif mprice &lt; balance: print("you bought", m , "Marijuana plants for", mprice , "$") input("What do you want to do next?") </code></pre> <p>Any help will be greatly appreciated. I got the m to work, but then I implemented o and it didn't work.</p>
<p>This code is supposed to work on python 3.</p> <p>If you are using python 2, then wherever you want your input to be of integer type, use</p> <p>int(raw_input()) </p> <p>to accept the input. Whenever you want it to be a string, simply use</p> <p>raw_input()</p>
python|python-3.x
0
1,903,658
12,861,091
Understanding Zope Component Architecture and Component Dependency
<p>It's quite difficult to have a good title of my question. From what I understand, the Adapter is to add more services to the components without changing it. The adapter can extends services from multiple components.</p> <p>But what about the dependency between component? How can I set the dependency between the component A (Person) and the component B (Task) like this normal Python code</p> <pre><code>class Person: pass class Task: def __init__(self, person): self.owner = person </code></pre> <p>If I implements the 2 classes</p> <pre><code>from zope.interface import Interface from zope.interface import implements class IPerson(Interface): pass class Person(object): implements(IPerson) class ITask(Interface): pass class Task(object): implements(ITask) def __init__(self, person): self.owner = person </code></pre> <p>Is it a good implementation?</p>
<p>The point is that with the ZCA, you <em>don't</em> set a dependency to a concrete object. You use utilities instead.</p> <p>Object A would implement an interface, and you look up the interface in B to find a concrete implementation, which <em>could</em> be A, but that depends on the register.</p> <p>Note that the ZCA is meant to allow you to plug different implementations for a given interface, and is not always needed.</p> <p>If your Task object expects a specific type, then document that. Using the ZCA is not a requirement here. At most, you can try to adapt the passed in value to <code>IPerson</code>; if the passed in object already implements that interface, that action is a no-op:</p> <pre><code>class Task(object): implements(ITask) def __init__(self, owner): self.owner = IPerson(owner) </code></pre> <p>That would allow you the flexibility of passing in something else later, something that is <em>not</em> a Person itself, but could be adapted to that interface.</p>
python|zope|zope.component
1
1,903,659
21,896,030
NumPy Array Copy-On-Write
<p>I have a class that returns large NumPy arrays. These arrays are cached within the class. I would like the returned arrays to be copy-on-write arrays. If the caller ends up just reading from the array, no copy is ever made. This will case no extra memory will be used. However, the array is "modifiable", but does not modify the internal cached arrays.</p> <p>My solution at the moment is to make any cached arrays readonly <code>(a.flags.writeable = False)</code>. This means that if the caller of the function may have to make their own copy of the array if they want to modify it. Of course, if the source was not from cache and the array was already writable, then they would duplicate the data unnecessarily.</p> <p>So, optimally I would love something like <code>a.view(flag=copy_on_write)</code>. There seems to be a flag for the reverse of this <code>UPDATEIFCOPY</code> which causes a copy to update the original once deallocated.</p> <p>Thanks!</p>
<p>Copy-on-write is a nice concept, but explicit copying seems to be "the NumPy philosophy". So personally I would keep the "readonly" solution if it isn't too clumsy.</p> <p>But I admit having written my own copy-on-write wrapper class. I don't try to detect write access to the array. Instead the class has a method "get_array(readonly)" returning its (otherwise private) numpy array. The first time you call it with "readonly=False" it makes a copy. This is very explicit, easy to read and quickly understood.</p> <p>If your copy-on-write numpy array looks like a classical numpy array, the reader of your code (possibly you in 2 years) may have a hard time.</p>
python|numpy|copy-on-write
5
1,903,660
41,134,235
Why doesn't this print 0
<p>I'm trying to make a function where it checks to see if a number gets repeated 2 times and 3 times and when it does it will return either 0 (no repeats detected) or 1 (both arguments entered have repeats). But for someone reason, 1 always prints even when there are no repeats. Is there an easier way to do this or a way to fix my code? Also ignore the print('t'), print("w"), and print("x"). Those were just a way to check what was going on.</p> <pre><code>def triple_double(num1, num2): num1 = str(num1) num2 = str(num2) if ('111') or ('222') or ('333') or ('444') or ('555') or ('666') or ('777') or ('888') or ('999') in num1: if ('11') or ('22') or ('33') or ('44') or ('55') or ('66') or ('77') or ('88') or ('99') in num2: print('t') print(1) else: print("w") print(0) else: print("x") print(0) triple_double(0, 0) </code></pre>
<p>It should be:</p> <pre><code>def triple_double(num1, num2): num1 = str(num1) num2 = str(num2) if ('111') in num1 or ('222') in num1 or ('333') in num1 or ('444') in num1 or ('555') in num1 or ('666') in num1 or ('777') in num1 or ('888') in num1 or ('999') in num1: if ('11') in num2 or ('22') in num2 or ('33') in num2 or ('44') in num2 or ('55') in num2 or ('66') in num2 or ('77') in num2 or ('88') in num2 or ('99') in num2: print('t') print(1) else: print("w") print(0) else: print("x") print(0) triple_double(0, 0) </code></pre> <p>Otherwise the if conditions will always evaluate to True.</p>
python
0
1,903,661
40,792,223
How to convert data to 10-point range scale in Python?
<p>The disease severity levels in plants is given within the range 0 (no disease) to 10 (severe disease). For example, some 12 plants have their disease levels as: </p> <p>(1.7, 3.7, 5.3, 7.3, 2.3, 3.7, 5.7, 7.3, 1, 4, 5.7, 6.7)</p> <p>Using another method the same plants are assigned the following values:</p> <p>(186.6377, 207.7993, 179.8552, 225.7226, 212.0066, 215.8321, 218.337, 199.9707, 179.5959, 203.2275, 212.2286, 212.5489)</p> <p>How can I convert the second set of values to the 0 to 10 scale in order to compare the values assigned to each plant? The closest I have seen is <a href="http://scikit-learn.org/stable/modules/preprocessing.html" rel="nofollow noreferrer">the scale function. Unfortunately, it deals with ranges of 0 to 1</a> </p>
<p>You could make a conversion function:</p> <pre><code>def convert(x,a,b,c=0,d=1): """converts values in the range [a,b] to values in the range [c,d]""" return c + float(x-a)*float(d-c)/(b-a) </code></pre> <p>For example: </p> <pre><code>&gt;&gt;&gt; convert(215.8321,170,230,0,10) 7.638683333333333 </code></pre> <p>(replace <code>170</code> and <code>230</code> by the min/max values, which are not given in your problem description).</p>
python
4
1,903,662
38,093,361
Python 2.7 regular expression match issue
<p>Suppose I am using the following regular expression to match, logically the regular expression means match anything with prefix <code>foo:</code> and ends with <strong>anything</strong> which is not a space. Match group will be the parts exclude prefix <code>foo</code></p> <p>My question is what exactly means <strong>anything</strong> in Python 2.7? Any ASCII or? If anyone could share some document, it will be great. Thanks.</p> <pre><code>a = re.compile('foo:([^ ]+)') </code></pre> <p>thanks in advance, Lin</p>
<p>Try:</p> <pre><code>a = re.compile('foo:\S*') </code></pre> <p>\S means anything but whitespace.</p> <p>I recommend you check out <a href="http://pythex.org" rel="nofollow">http://pythex.org</a>. It's really good for testing out regular expresions and has a decent cheat-sheet.</p> <p><strong>UPDATE:</strong></p> <p>Anything (.) matches anything, all unicode/UTF-8 characters.</p>
python|regex|python-2.7
3
1,903,663
30,827,316
How to find the relative path between two directories?
<p>I would like to find the relative path between two directories on my system.</p> <p><strong>Example:</strong></p> <p>If I have <code>pathA == &lt;pathA&gt;</code> and <code>pathB == &lt;pathA&gt;/dir1/dir2</code>, the relative path between them will be <code>dir1/dir2</code>.</p> <p>How could I find it in python? Is there a tool I could use?</p> <p>If <strong>pathB</strong> is contained in <strong>pathA</strong>, I could just do <code>pathB.replace(pathA, '')</code> to get this relative path, but what if <strong>pathB</strong> isn't contained in <strong>pathA</strong>?</p>
<p><code>os.path.relpath(path1, path2) # that's it</code></p>
python
14
1,903,664
51,969,610
python OOP class method retaining variable. Weird scoping thing
<p>I have two classes, a main class which creates instances of my other class.</p> <pre><code>class Builder: def __init__(self, id): self.id = id def build_thing(self, main_ftr, main_attr, attrs = {}): # note the main ftr/attrs gets added to attrs no matter what attrs[main_ftr] = attrs.get(main_ftr, []) + [main_attr] return Thing(main_ftr, main_attr, attrs) class Thing: def __init__(self, main_ftr, main_attr, attrs): self.main_ftr = main_ftr self.main_attr = main_attr self.attrs = attrs </code></pre> <p>The issue I'm having has to do with the <code>attrs</code> dictionary that gets passed to the <code>Thing</code> class. The problem is that each time I use the <code>Builder</code> class to create a <code>Thing</code> class, the attrs argument retains it's previous values</p> <pre><code>b = Builder('123') t = b.build_thing('name', 'john') print(t.attrs) # {'name': ['john'] } # Goal is this creates a new "Thing" with only attrs = {'name':['mike']} t2 = b.build_thing('name', 'mike') print(t2.attrs) # {'name': ['john', 'mike']} </code></pre> <p>My Question is 2 part:</p> <p>Why is this happening?</p> <p>How do I fix it?</p>
<p>Functions' optional arguments are initialized once. Since <code>attrs</code> is mutable, each time you call the function, you add new key-value pair to this dictionary and it is kept for further calls. If you need a mutable data structure as a default parameter, use something like:</p> <pre><code>def build_thing(self, main_ftr, main_attr, attrs=None): if attrs is None: attrs = {} attrs[main_ftr] = attrs.get(main_ftr, []) + [main_attr] return Thing(main_ftr, main_attr, attrs) </code></pre>
python|class|oop|dictionary|scope
3
1,903,665
51,951,358
Keras: how to get top-k accuracy
<p>I would like to get the top-k accuracy for my model in keras.</p> <p>I have found a post here:<a href="https://stackoverflow.com/questions/42327006/how-to-calculate-top5-accuracy-in-keras">How to calculate top5 accuracy in keras?</a> suggesting the following:</p> <pre><code>from keras import backend as K import tensorflow as tf top_values, top_indices = K.get_session().run(tf.nn.top_k(_pred_test, k=5)) </code></pre> <p>The output just gives me two arrays:</p> <p>top_values:</p> <pre><code>array([[1., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], ..., [1., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], [1., 0., 0., 0., 0.]], dtype=float32) </code></pre> <p>top_indices:</p> <pre><code>array([[12, 0, 1, 2, 3], [13, 0, 1, 2, 3], [15, 0, 1, 2, 3], ..., [12, 0, 1, 2, 3], [17, 0, 1, 2, 3], [18, 0, 1, 2, 3]]) </code></pre> <p>How would I calculate the actual score from these values?</p>
<p>Ok here is the code that works for me, in case someone else stumbles upon similar issues - the missing link for me was using ".evaluate":</p> <pre><code>import functools top3_acc = functools.partial(keras.metrics.top_k_categorical_accuracy, k=3) top3_acc.__name__ = 'top3_acc' model.compile(Adam(lr=.001),# optimizers.RMSprop(lr=2e-5), loss='categorical_crossentropy', metrics=['accuracy','top_k_categorical_accuracy',top3_acc]) model.evaluate(X_test, y_test) </code></pre> <p>where 'top_k_categorical_accuracy' gives me the score for k=5 (standard) and top3_acc can be adjusted by changing k=3 in the function call.</p>
python|keras
10
1,903,666
68,904,784
How do I run terminal commands in a script?
<p>I am currently running an Raspberry Pi 4b with an <a href="https://wiki.geekworm.com/X728#User_manual" rel="nofollow noreferrer">x728 UPS</a>. I am trying to make a script so that when power gets cut off from the UPS, it would run a shut down script.</p> <p>Currently, I have this -</p> <pre><code>import RPi.GPIO as GPIO import subprocess GPIO.setmode(GPIO.BCM) GPIO.setup(6, GPIO.IN) while: if GPIO.input(6) == 1: subprocess.call(['shutdown', '-h', 'now'], shell=False) </code></pre> <p>This works in shutting down the Pi when power gets cut off, however, the UPS doesnt turn off, and in turn, I cant use the device's auto-turn on feature when the power comes back on.</p> <p>In their <a href="https://wiki.geekworm.com/X728-Software" rel="nofollow noreferrer">wiki</a>, they have a command <code>x728off</code> that you can run in the terminal to shutdown both the Pi and the UPS. It works great if I just typed it directly into terminal, however, I dunno how to put it in my code.</p>
<p>To run the command as it is use.</p> <pre class="lang-py prettyprint-override"><code>import os os.system(&quot;x728off&quot;) </code></pre> <p>or if you want to use subprocess module, use</p> <pre class="lang-py prettyprint-override"><code>import subprocess subprocess.call([&quot;x728off&quot;], shell=False) </code></pre>
python|linux|terminal|raspberry-pi
0
1,903,667
69,242,841
How to create attributes to the groups and access them in hdf5 file system?
<p>I want to create two groups in the hdf5 file. First group /h5md <a href="https://nongnu.org/h5md/h5md.html#h5md-metadata" rel="nofollow noreferrer">group description</a> and the /particles/lipids group <a href="https://nongnu.org/h5md/h5md.html#particles-group" rel="nofollow noreferrer">group2 description</a>. The former consists only of a direct attribute 'version' (=1.0) and two groups creator and author with their attributes, so there are no datasets here.</p> <p>In the /particles/lipids group, the only missing bit is the box group <a href="https://nongnu.org/h5md/h5md.html#simulation-box" rel="nofollow noreferrer">box group description</a>. The minimal information are two attributes: dimension (=3) and the boundary conditions, e.g, the string array (&quot;none&quot;, &quot;none&quot;, &quot;none&quot;). In our case, we have actually periodic boundaries, so the string array should be (&quot;periodic&quot;, &quot;periodic&quot;, &quot;periodic&quot;) and the <em>dataset</em> 'edges' must be provided. The box size is given in the <a href="https://www.dropbox.com/s/np4zddobttbtjq0/com?dl=0" rel="nofollow noreferrer">File</a> file in the last line of each frame, it is something like 61.42836 61.42836 8.47704 and changes slightly in the course of the simulation. This means that the edges dataset is time-dependent as well, i.e., it has maxshape=(None, 3).</p> <p>I guess the problem is defined clearly. I need to create these two groups according to the description. I have create the first and second group, see the code below! And given attribute to the version group in /h5md, the code works fine but when I try to access the attribute it shows nothing in there!</p> <pre class="lang-py prettyprint-override"><code>import struct import numpy as np import h5py import re # First part generate convert the .gro -&gt; .h5 . csv_file = 'com' fmtstring = '7s 8s 5s 7s 7s 7s' fieldstruct = struct.Struct(fmtstring) parse = fieldstruct.unpack_from #define a np.dtype for gro array/dataset (hard-coded for now) gro_dt = np.dtype([('col1', 'S7'), ('col2', 'S8'), ('col3', int), ('col4', float), ('col5', float), ('col6', float)]) with open(csv_file, 'r') as f, \ h5py.File('xaa.h5', 'w') as hdf: # open group for position data particles_grp = hdf.require_group('particles/lipids/positions') h5md_grp = hdf.require_group('h5md/version/author/creator') h5md_grp.attrs['version'] = 1.0 # datasets with known sizes ds_time = particles_grp.create_dataset('time', dtype=&quot;f&quot;, shape=(0,), maxshape=(None,), compression='gzip', shuffle=True) ds_step = particles_grp.create_dataset('step', dtype=np.uint64, shape=(0,), maxshape=(None,), compression='gzip', shuffle=True) ds_value = None step = 0 while True: header = f.readline() m = re.search(&quot;t= *(.*)$&quot;, header) if m: time = float(m.group(1)) else: print(&quot;End Of File&quot;) break # get number of data rows, i.e., number of particles nparticles = int(f.readline()) # read data lines and store in array arr = np.empty(shape=(nparticles, 3), dtype=np.float32) for row in range(nparticles): fields = parse( f.readline().encode('utf-8') ) # arr[row]['col1'] = fields[0].strip() # arr[row]['col2'] = fields[1].strip() # arr[row]['col3'] = int(fields[2]) arr[row] = np.array((float(fields[3]), float(fields[4]), float(fields[5]))) if nparticles &gt; 0: # create a resizable dataset upon the first iteration if not ds_value: ds_value = particles_grp.create_dataset('value', dtype=np.float32, shape=(0, nparticles, 3), maxshape=(None, nparticles, 3), chunks=(1, nparticles, 3), compression='gzip', shuffle=True) # append this sample to the datasets ds_time.resize(step + 1, axis=0) ds_step.resize(step + 1, axis=0) ds_value.resize(step + 1, axis=0) ds_time[step] = time ds_step[step] = step ds_value[step] = arr #particles_grp[f'dataset_{step:04}'] = ds #ds= hdf.create_dataset(f'dataset_{step:04}', data=arr,compression='gzip') #create attributes for this dataset / time step # hdr_tokens = header.split() #particles_grp['ds'] = ds #particles_grp[f'dataset_{step:04}'] = ds # ds.attrs['raw_header'] = header #ds.attrs['Generated by'] = hdr_tokens[2] #ds.attrs['P/L'] = hdr_tokens[4].split('=')[1] # ds.attrs['Time'] = hdr_tokens[6] footer = f.readline() step += 1 #============================================================================= </code></pre> <p>The code for reading the hdf5 file</p> <pre class="lang-py prettyprint-override"><code>with h5py.File('xaa.h5', 'r') as ff: base_items = list(ff.keys()) print('Items in the base directory: ', base_items) value = ff.get('h5md/version') #dataset = np.array(value) #print(&quot;The shape of the value&quot;, value.shape) print(value.get_id('h5md/version/')) #print(list(ff.attrs.keys())) </code></pre>
<p>You need to use the same group and attribute names as when you created them. Simple code to print the attribute based on your code:</p> <pre><code>with h5py.File('xaa.h5', 'r') as ff: h5md_grp = ff['h5md/version/author/creator'] print(h5md_grp.attrs['version']) </code></pre> <p>Code to add the &quot;file version&quot; as a global attribute to the h5py file object then retrieve and print:</p> <pre><code>with h5py.File('xaa.h5', 'w') as ff: .... ff.attrs['version'] = 1.0 .... with h5py.File('xaa.h5', 'r') as ff: print(ff.attrs['version']) </code></pre>
python|hdf5|h5py
2
1,903,668
22,356,489
Django admin serving uploaded image
<p>I am new to Django I'm stuck with regards to how I can fix this issue.</p> <p>I have a a model which contains an ImageField as follows</p> <pre><code>name = models.CharField(max_length=100) description = models.CharField(max_length=1000) file = models.ImageField(upload_to='img') </code></pre> <p>and then in my settings.py I have </p> <pre><code>STATIC_ROOT = os.path.join(PROJECT_PATH, "static") STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media') MEDIA_URL = 'media/' </code></pre> <p>and I have the following url pattern to handle this</p> <pre><code> url(r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, 'show_indexes' : True }) </code></pre> <p>In the admin pages I am able to upload the image perfectly fine to the expected location in the media folder, and I am able to access this by loading 127.0.0.1:8000/media/img/my_image.jpg. The problem is that in the standard admin panel the link which shows the currently uploaded image for the object simply appends media/img/my_img.jpg to the end of the current URL and therefore receives a 404.</p> <p>I am not sure what the best way to fix this issue is, I Hope this makes sense and please let me know if more information is needed.</p> <p>Thanks.</p>
<p>Change</p> <pre><code>MEDIA_URL = 'media/' </code></pre> <p>to</p> <pre><code>MEDIA_URL = '/media/' </code></pre> <p>and it should stop appending to the URL and replace it instead.</p>
python|django|django-admin|django-file-upload|django-media
0
1,903,669
43,710,282
Call blender's function bpy.ops.import_mesh.stl(filepath = output_file) through a thread
<p>I try to import an stl mesh through a thread with bpy.ops.import_mesh.stl(filepath = output_file) but blender crashes randomly. I suppose that mesh import through a thread is not supported (thread-safe) so can you suggest a better way to implement this task?</p> <p>Here is the code </p> <pre><code>def processData(Data, objcounter): SaveDataIntoSpecificFormat("File.data", Data) os.system("/externalexe FileData -o File%d.stl" %d objcounter) bpy.ops.import_mesh.stl(filepath = "File%d.stl" %d objcounter) for objcounter in range(len(current_list_objs)): t = threading.Thread(target=processData, args=(current_list_objs[objcounter], objcounter,)) t.start() </code></pre>
<p>It seems you are using the same<code>filename FileData</code> for all threads.</p> <p>Make it unique using <code>objcounter</code>.</p>
python|multithreading|import|blender|mesh
0
1,903,670
43,484,160
Add model in tree order with unlimited depth from a list
<p>I have the following Category model:</p> <pre><code>class Category(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) </code></pre> <p>As you can see, the category can have parent categories and subcategories via ForeignKey.</p> <p>Now suppose I have this list:</p> <pre><code>Magazines Magazines/Tech Magazines/Tech/Network Magazines/Tech/Programming Magazines/Tech/Programming/Python Courses Courses/Design Courses/Design/Photoshop Courses/Tech Courses/Tech/Programming </code></pre> <p>I need to save each individual category related to it's parent category. Please note that only checking the first parent category isn't enough since <code>../Tech/Programming</code> can be found twice, for example. Also, there's not a maximum depth for the tree.</p>
<p>I also have a field where I store the full path of each category. Eg.: <code>Magazines/Tech/Programming </code></p> <p>So, using that, I loop through the list and check if there's a category with the same fullpath. If there's not, store it with the parent. The revelant code is basically this:</p> <pre><code>def AddCategory(channel, category): channel = Channel.objects.get(name='Walmart') if len(category)&gt; 1: # If it's not a root category try: categoria = Category.objects.get(fullpath=category[0] + "/" + category[1]) print(categoria.name) except ObjectDoesNotExist: parent = Category.objects.get(fullpath=category[0]) new_category = Category.objects.create(name=category[1], channel=channel, parent=parent) print(new_category.fullpath) else: # If it's a root category try: categoria = Category.objects.get(fullpath=category[0]) except ObjectDoesNotExist: new_category = Category.objects.create(name=category[0], channel=channel) print(new_category) </code></pre> <p>I still feel there should be a more elegant way, so feel free to contribute. Thanks!</p>
python|django|logic
0
1,903,671
43,522,358
checking if a loop returned a value
<p>I am trying to figure out how to test my list if it ever give any result at all then give the ok to run an other list. Do i have to make a new 'for' statement that run my list again? sry for bad english</p> <p>I found these statement but im trying to figure out how i can apply them to my code.</p> <p><strong>But how do I check if my loop never ran at all?</strong> </p> <p>The easiest way to check if a for loop never executed is to use None as a sentinel value:</p> <pre><code>x = None for x in data: ... # process x if x is None: raise ValueError("Empty data iterable: {!r:100}".format(data)) If None is a legitimate data value, then a custom sentinel object can be used instead: </code></pre> <hr> <pre><code>x = _empty = object() for x in data: ... # process x if x is _empty: raise ValueError("Empty data iterable: {!r:100}".format(data)) </code></pre> <hr> <p><strong>My usecase:</strong></p> <pre><code>message = ["potato:23", "orange:", "apple:22"] for i in message: parts = i.split(":") gauche = parts[0].strip() droite = parts[1] try: droite = int(droite) if not gauche.isalpha(): print("La ligne '", i, "' n'est pas correctement formaté.") break except ValueError: print("La ligne '", i, "' n'est pas correctement formaté.") break </code></pre> <hr> <pre><code># following code runs if no error was raised in the for loop message2 = sorted(ligne(texte)) for j in message2: print(j) sys.exit() </code></pre>
<blockquote> <p><strong>Question</strong>: I would like to execute this like of code if that for didnt raise any error </p> </blockquote> <p>As you want to continue your programm, you couldn't use <code>raise</code>.<br> For instance, I <code>append</code> all <code>gauche</code> if <code>int(droite)</code> <strong>didn't</strong> <code>raise ValueError</code> and <code>gauche.isalpha</code>.<br> Sort this list of fruits and <code>print</code> it. </p> <pre><code>ligne = [] for i in message: parts = i.split(":") gauche = parts[0].strip() droite = parts[1] try: droite = int(droite) if not gauche.isalpha(): #raise Exception("La ligne {!r:2} n'est pas correctement formaté.".format(i)) print("La ligne {!r:2} n'est pas correctement formaté.".format(i)) else: # Append only if isalpha ligne.append((gauche)) except ValueError: #raise Exception("La ligne {!r:2} n'est pas correctement formaté.".format(i)) print("La ligne {!r:2} n'est pas correctement formaté.".format(i)) message2 = sorted(ligne) for fruit in message2: print(fruit) </code></pre> <blockquote> <p><strong>Output</strong>:<br> La ligne 'orange:' n'est pas correctement formaté.<br> apple<br> potato </p> </blockquote> <hr> <p>Tried your code, it's working for me. I get the following output:</p> <pre><code>La ligne ' orange: ' n'est pas correctement formaté. </code></pre> <blockquote> <p><strong>Question</strong>:I found these statement but im trying to figure out how i can apply them to my code </p> </blockquote> <p>You can use it for instance: </p> <pre><code>try: droite = int(droite) if not gauche.isalpha(): raise Exception("La ligne {!r:2} n'est pas correctement formaté.".format(i)) except ValueError: raise Exception("La ligne {!r:2} n'est pas correctement formaté.".format(i)) </code></pre>
python
1
1,903,672
43,882,105
i can't install caffe on anaconda CPU-only windows 10
<p>I'm getting this error while install caffe !:</p> <p>...........................................................................</p> <pre><code> The system cannot find the drive specified. The system cannot find the drive specified. INFO: ============================================================ INFO: Summary: INFO: ============================================================ INFO: MSVC_VERSION = 14 INFO: WITH_NINJA = 1 INFO: CMAKE_GENERATOR = "Ninja" INFO: CPU_ONLY = 1 INFO: CUDA_ARCH_NAME = Auto INFO: CMAKE_CONFIG = Release INFO: USE_NCCL = 0 INFO: CMAKE_BUILD_SHARED_LIBS = 0 INFO: PYTHON_VERSION = 2 INFO: BUILD_PYTHON = 1 INFO: BUILD_PYTHON_LAYER = 1 INFO: BUILD_MATLAB = 0 INFO: PYTHON_EXE = "python" INFO: RUN_TESTS = 0 INFO: RUN_LINT = 0 INFO: RUN_INSTALL = 0 INFO: ============================================================ The system cannot find the path specified. -- The C compiler identification is unknown -- The CXX compiler identification is unknown CMake Error at CMakeLists.txt:18 (project): No CMAKE_C_COMPILER could be found. Tell CMake where to find the compiler by setting either the environment variable "CC" or the CMake cache entry CMAKE_C_COMPILER to the full path to the compiler, or to the compiler name if it is in the PATH. CMake Error at CMakeLists.txt:18 (project): No CMAKE_CXX_COMPILER could be found. Tell CMake where to find the compiler by setting either the environment variable "CXX" or the CMake cache entry CMAKE_CXX_COMPILER to the full path to the compiler, or to the compiler name if it is in the PATH. -- Configuring incomplete, errors occurred! See also "C:/Projects/caffe/build/CMakeFiles/CMakeError.log". ERROR: Configure failed </code></pre> <p>............................................................................</p> <p>system info: i'm using windows 10 64-bit OS</p> <p>installed : anaconda python 2.7 and python 3.6 i don't have GPU so just CPU-only </p> <p>if any one can help me with this i'll appreciate that > </p>
<p>You need to set to set <code>CMAKE_C_COMPILER</code> and <code>CMAKE_CXX_COMPILER</code>. This can be done by editing <code>scripts/build_win.cmd</code> to provide the correct path to your C and C++ compilers when running cmake (roughly around line 160)</p> <p>Eg.</p> <pre><code>cmake -G"!CMAKE_GENERATOR!" ^ ... -DCMAKE_C_COMPILER="C:/Program Files (x86)/Microsoft Visual Studio 12.0/VC/bin/amd64/cl.exe" ^ -DCMAKE_CXX_COMPILER="C:/Program Files (x86)/Microsoft Visual Studio 12.0/VC/bin/amd64/cl.exe" ^ ... </code></pre>
python|cmake|deep-learning|anaconda|caffe
0
1,903,673
71,134,779
How to access a variable outside a class and function?
<p>I would like to call a variable defined in a function within a class. Here is what I have</p> <pre><code>class StatePDFs: def __init__(self): example = &quot;test test&quot; def ca_form(self, data): #...other code... self.template='original_forms/state/CA/2021-541-k-1.pdf' self.data = { start_date:data['start'], end_date:data['end'] #... } statePDF = StatePDFs() ca_forms = statePDF.ca_form(data) ca_data = ca_forms.data ca_template = ca_forms.template out_file = 'ca_test.pdf' generated_pdf = pypdftk.fill_form(ca_template, ca_data, out_file=out_file, flatten=True) </code></pre> <p>When I do this I get the following error:</p> <pre><code>AttributeError: 'NoneType' object has no attribute 'data' </code></pre> <p>This is a simple example of what I am trying to do. In my actual code, the function retrieves data from MySQL and other sources. But I would like to have nested objects/variables like in the example above and call them from that function. I hope this makes sense. What am I doing wrong here?</p> <p>Here is a snipe</p>
<p>I figured it out. I don't think I was clear in my questions but what I needed was to return multiple values from my function.</p> <p>I added:</p> <p><code>return self.template, self.data</code></p> <p>then when calling the function I defined my variables in tuples:</p> <p><code>ca_template, ca_data = statePDF.ca_form(data)</code></p>
python
1
1,903,674
9,306,717
Malformed environment variables detection in python
<p>I am trying to source a bash script containing some environment variables in python. I followed one other thread to do it. But, there seems that one of the variable is malformed, as can be seen in the given snippet.</p> <pre><code>COLORTERM=gnome-terminal mc=() { . /usr/share/mc/mc-wrapper.sh } _=/usr/bin/env </code></pre> <p>I am using the following code to set up the current environment.</p> <pre><code>import os import pprint import subprocess command = ['bash', '-c', 'source init_env &amp;&amp; env'] proc = subprocess.Popen(command, stdout = subprocess.PIPE) for line in proc.stdout: (key, _, value) = line.partition("=") os.environ[key] = value proc.communicate() </code></pre> <p>'</p> <p>If I change the above code a little like putting a condition:</p> <pre><code>for line in proc.stdout: (key, _, value) = line.partition("=") if not value: continue os.environ[key] = value </code></pre> <p>then things are working but the environment is corrupted because of one missing bracket as can be seen from the snippet of environment variable that the bracket is appearing on new line. Because of this corruption, If I run some other command like</p> <pre><code>os.system("ls -l") </code></pre> <p>it gives me the following error</p> <pre><code>sh: mc: line 1: syntax error: unexpected end of file sh: error importing function definition for `mc' </code></pre> <p>What could be the possible solutions for this problem?</p> <p>Thanks alot</p>
<p>Probably the best way to do this is to create a separate program that writes out the environment variables in a way that is easily and unambiguously processed by your own program; then call <em>that</em> program instead of <code>env</code>. Using <a href="http://docs.python.org/library/pickle.html" rel="nofollow">the standard <code>pickle</code> module</a>, that separate program can be as simple as this:</p> <pre><code>import os import sys import pickle pickle.dump(os.environ, sys.stdout) </code></pre> <p>which you can either save into its own <code>.py</code> file, or else put directly in a Bash command:</p> <pre><code>python -c 'import os, sys, pickle; pickle.dump(os.environ, sys.stdout)' </code></pre> <p>In either case, you can process its output like this:</p> <pre><code>import os import pprint import subprocess import pickle command = [ 'bash', '-c', 'source init_env &amp;&amp; ' + 'python -c "import os, sys, pickle; ' + 'pickle.dump(os.environ, sys.stdout)"' ] proc = subprocess.Popen(command, stdout = subprocess.PIPE) for k, v in pickle.load(proc.stdout).iteritems(): os.environ[k] = v proc.communicate() </code></pre>
python|linux|bash|environment-variables
1
1,903,675
52,855,310
pipenv: packaging.specifiers.InvalidSpecifier: Invalid specifier
<p>I'm getting this error when recreating Pipfile.lock:</p> <pre><code>packaging.specifiers.InvalidSpecifier: Invalid specifier '==0.5.2-auto' </code></pre> <p>I think it has something to do with the <code>-auto</code> suffix, but it works on a different computer for some reason.</p> <p>The traceback seems to be truncated for some reason, here's all I see in the console:</p> <pre><code>pipenv/vendor/requirementslib/models/requirements.py", line 1008, in get_version return parse_version(self.get_specifier().version) File "/home/johneye/.local/share/virtualenvs/python-microservice-scaffolding-ylP1urgf/lib/python3.6/site-packages/pipenv/vendor/requirementslib/models/requirements.py", line 1005, in get_specifier return Specifier(self.specifiers) File "/home/johneye/.local/share/virtualenvs/python-microservice-scaffolding-ylP1urgf/lib/python3.6/site-packages/pipenv/vendor/packaging/specifiers.py", line 85, in __init__ raise InvalidSpecifier("Invalid specifier: '{0}'".format(spec)) packaging.specifiers.InvalidSpecifier: Invalid specifier '==0.5.2-auto' </code></pre>
<p>I'm posting a partial answer since I only got three results on Google when looking for the precise error message.</p> <p>From looking at the code and modifying it, it became clear that there are at least two kinds of specifiers - a legacy specifier which could contain just about anything and a standard specifier, which conforms to PEP 440.</p> <p>When the dependencies are being locked, the specifiers are checked against a regex to see if they are valid or not. I saw that they are sometimes being checked against the legacy specifier and sometimes against the normal one. At this point, I abandoned the search for the root cause and decided that it will be better to fix my code to conform to both specifiers, so I changed it to <code>==0.5.2-dev1</code>, which fixed the problem.</p>
python|pipenv|pipfile
1
1,903,676
47,855,577
Class Attributes VALUES to a list
<p>I have a simple python class that consists of some attributes and some methods.What i need is to make a list out of the class attributes ( only ! )</p> <pre><code>Class A(): def __init__(self, a=50, b="ship"): a = a b = b def method1(): ..... </code></pre> <p>I want to have a list : </p> <p>[50, "ship"]</p>
<p>Another solution, possibly more generic, is:</p> <pre><code>def asList(self): [value for value in self.__dict__.values()] </code></pre> <p>Full example with correct syntax:</p> <pre><code>class A: def __init__(self, a=50, b="ship"): self.a = a self.b = b def as_list(self): return [value for value in self.__dict__.values()] a = A() print a.as_list() </code></pre> <p>output:</p> <pre><code>[50, 'ship'] </code></pre>
python|python-2.7
3
1,903,677
7,520,031
Pointing to another object's attributes and adding your own
<p>Suppose I have a class:</p> <pre><code>class Car(object): def __init__(self, name, tank_size=10, mpg=30): self.name = name self.tank_size = tank_size self.mpg = mpg </code></pre> <p>I put together a list of the cars I'm looking at:</p> <pre><code>cars = [] cars.append(Car("Toyota", 11, 29)) cars.append(Car("Ford", 15, 12)) cars.append(Car("Honda", 12, 25)) </code></pre> <p>If I assign a name to my current favorite (a "pointer" into the list, if you will):</p> <pre><code>my_current_fav = cars[1] </code></pre> <p>I can easily access the attributes of my current favorite:</p> <pre><code>my_current_fav.name # Returns "Ford" my_current_fav.tank_size # Returns 15 my_current_fav.mpg # Returns 12 </code></pre> <p>Here's where I start getting foggy. I would like to provide additional "computed" attributes only for my current favorite (let's assume these attributes are too "expensive" to store in the original list and are easier to just compute):</p> <pre><code>my_current_fav.range # Would return tank_size * mpg = 180 # (if pointing to "Ford") </code></pre> <p>In my case, I just capitulated and added 'range' as an attribute of Car(). But what if storing 'range' in each Car() instance was expensive but calculating it was cheap?</p> <p>I considered making 'my_current_fav' a sub-class of Car(), but I couldn't figure out a way to do that and still maintain my ability to simply "point" 'my_current_favorite' to an entry in the 'cars' list.</p> <p>I also considered using decorators to compute and return 'range', but couldn't figure out a way to also provide access to the attributes 'name', 'mpg', etc.</p> <p>Is there an elegant way to point to any item in the list 'cars', provide access to the attributes of the instance being pointed to as well as provide additional attributes not found in the class Car?</p> <p><strong>Additional information:</strong><br> After reading many of your answers, I see there is background information I should have put into the original question. Rather than comment on many answers individually, I'll put the additional info here.</p> <p>This question is a simplification of a more complicated issue. The original problem involves modifications to an existing library. While making range a method call rather than an attribute is a good way to go, changing</p> <pre><code>some_var = my_current_favorite.range </code></pre> <p>to</p> <pre><code>some_var = my_current_favorite.range() </code></pre> <p>in many existing user scripts would be expensive. Heck, <em>tracking down</em> those user scripts would be expensive.</p> <p>Likewise, my current approach of computing range for every car isn't "expensive" in Python terms, but <em>is</em> expensive in run-time because the real-world analog requires slow calls to the (embedded) OS. While Python itself isn't slow, those calls are, so I am seeking to minimize them.</p>
<p>This is easiest to do for your example, without changing <code>Car</code>, and changing as little else as possible, with <code>__getattr__</code>:</p> <pre><code>class Car(object): def __init__(self, name, tank_size=10, mpg=30): self.name = name self.tank_size = tank_size self.mpg = mpg class Favorite(object): def __init__(self, car): self.car = car def __getattr__(self, attr): return getattr(self.car, attr) @property def range(self): return self.mpg * self.tank_size cars = [] cars.append(Car("Toyota", 11, 29)) cars.append(Car("Ford", 15, 12)) cars.append(Car("Honda", 12, 25)) my_current_fav = Favorite(cars[1]) print my_current_fav.range </code></pre> <p>Any attribute not found on an instance of <code>Favorite</code> will be looked up on the <code>Favorite</code> instances <code>car</code> attribute, which you set when you make the <code>Favorite</code>.</p> <p>Your example of <code>range</code> isn't a particularly good one for something to add to <code>Favorite</code>, because it should just be a <code>property</code> of car, but I used it for simplicity.</p> <p><strong>Edit</strong>: Note that a benefit of this method is if you change your favorite car, and you've not stored anything car-specific on <code>Favorite</code>, you can change the existing favorite to a different car with:</p> <pre><code>my_current_fav.car = cars[0] # or Car('whatever') </code></pre>
python|oop|design-patterns
6
1,903,678
16,268,927
prime factor python nightmare
<p>I've been trying to get python to find the highest prime factor of a number and, 11 days of banging my obviously dumb head later, I'm ready to ask for help. </p> <p>Any idea why this won't return the highest prime factor? It either takes so long I quit the program manually, or complains that <code>python int to large to convert to C long</code>. </p> <p>Any help or suggestions would be very much appreciated! Thank you!</p> <pre><code>def primeCheck(value): for x in range(2, int(value / 2) + 1): if value % x &lt; 0.1: return False return True val = int(raw_input('What number would you like the highest prime factor of?')) pc = 2 for x in xrange(pc, int((val / pc) + 1)): if primeCheck(x) and val % x &lt; 0.1: val = val / x pc = x print pc </code></pre>
<p>Strange, as I was just reading a lovely solution to this today - here you go:</p> <p><strong><a href="https://stackoverflow.com/a/412942/1179880">Tryptych's answer</a></strong></p> <pre><code>def prime_factors(n): "Returns all the prime factors of a positive integer" factors = [] d = 2 while (n &gt; 1): while (n%d==0): factors.append(d) n /= d d = d + 1 return factors pfs = prime_factors(1000) largest_prime_factor = pfs[-1] # The largest (last) element in the prime factor array </code></pre>
python|numbers|generator
1
1,903,679
16,171,688
Python: Add to Include Path on the Command Line
<p>Is there a way to add include paths to python on the command line? What I am trying to do is run a unit test that uses a some code in a lib directory:</p> <p>$ python -I lib/ test/my-test.py</p> <p>but this fails. I can append to my path in my-test.py but that seems less than optimal since its path dependent. Any suggestions?</p>
<p>Use the <a href="http://docs.python.org/2/using/cmdline.html#environment-variables" rel="nofollow"><code>PYTHONPATH</code> environment variable</a>:</p> <pre><code>PYTHONPATH=lib/ python test/my-test.py </code></pre>
python|unit-testing|include|include-path
2
1,903,680
38,745,738
Return value using button
<p>I'm trying to return a value using a button, but i just can't get it to work. What i want is the button to return a value which later on can be used to check is the function was used or not. The code that I'm using is the following:</p> <pre><code>from Tkinter import * master = Tk() master.geometry("200x100") def bla(): return 1 Button(master, command = bla, text = 'OK').pack() if bla == 1: print('1') mainloop() </code></pre> <p>I've also tried to do this using lambda but i could not figure that one out too.</p>
<p>Try taking a look at this link <a href="https://stackoverflow.com/a/11907627/3110529">https://stackoverflow.com/a/11907627/3110529</a> as it addresses the issues you're having.</p> <p>The main concern is that callbacks are designed to just be a behaviour that happens in response to an event and therefore it doesn't entirely make sense for them to return a value. In your program, when you say </p> <p><code>if bla == 1: print('1')</code></p> <p>you're asking if the function pointer (or reference?) is equal to <code>1</code> which it obviously will never be.</p> <p>You might be tempted to use global variables to cover this (i.e. store a 'blah' variable, then have the call back set its value) but this is generally considered bad practice. Instead, as in the link, try converting it to a class which will allow you to use member variables to store the results and responses of callbacks in a more organised manner.</p>
python|button|tkinter|return
3
1,903,681
38,734,209
Python File I/O issue: Bypassing For Loop?
<pre><code>def findWord(word): f = open("words.txt", "r") given_line = f.readlines() for line in f: if str(word) in line: part = line[0] ## print(line+"\n"+str(word)+" is a "+part) return True else: return False print("fail") f.close() def partSpeech(inX): f = open("words.txt", "a") inX = inX.split() for i in inX: i = i.lower() if(findWord(i) == False): if "ify" in i[-3:] or "ate" in i[-3:] or "ize" in i[-3:] or "ing" in i[-3:] or "en" in i[-2:] or "ed" in i[-2:]: f.write("\nV"+i) elif "ment" in i[-4:] or "ion" in i[-3:] or "acy" in i[-3:] or "ism" in i[-3:] or "ist" in i[-3:] or "ness" in i[-3:] or "ity" in i[-3:] or "or" in i[-2:] or "y" in i[-1:]: f.write("\nN"+i) elif "ly" in i[-2:]: f.write("\nD"+i) else: print(i+" was already in the database.") </code></pre> <p>Essentially, my issue with the above happens at "for line in f:". The problem is that, after putting numerous markers (prints to determine where it's getting) throughout the code, the for loop isn't even ran! I don't understand, really, whether or not it's just that line or f aren't being counted or what, but.</p> <p>The goal is to, in this snippet, take a bunch of words, loop them through a system that checks whether or not they're already in the given text file (the part I'm having issues with) and then, if they're not, append them with a part of speech tag.</p> <p>EDIT: I'm not getting an error at all, it's just that it's not running the For Loop like it should. Every function is called at some point or another, partSpeech is called toward the end with a small list of words.</p> <p>EDIT 2: PROGRESS! Sort of. The text file was empty, so it wasn't reading any line whatsoever. Now, however, it's not taking into account whether or not the words are already there. It just skips over them.</p>
<p>First off, delete this line:</p> <pre><code>given_line = f.readlines() </code></pre> <p>This is reading the contents of the file into an unused <code>given_line</code> variable and leaving <code>f</code> positioned at the end of the file. Your <code>for</code> loop therefore has nothing to loop over.</p> <hr> <p>Your <code>findWord()</code> function is doing a number of odd/problematic things, any of which might be causing the behavior you're assuming means the for loop isn't even running. Here's a possible re-implementation:</p> <pre><code>def findWord(word): # it seems odd to pass a "word" parameter that isn't a str, but if you must handle that # case you only need to do the cast once word = str(word) # always use the with statement to handle resources like files # see https://www.python.org/dev/peps/pep-0343/ with open("words.txt", "r") as f: for line in f: if word in line: return True return False # only return False after the loop; once we've looked at every line # no need to call f.close(), the with statement does it for us </code></pre>
python|io
0
1,903,682
38,831,006
Extract subarray from collection of 2D coordinates?
<p>In Python, I have a large 2D array containing data, and another Mx2 2D array containing a collection of M 2D coordinates of interest, e.g.</p> <pre><code>coords=[[150, 123], [151, 123], [152, 124], [153, 125]] </code></pre> <p>I would like to extract the Mx1 array containing the values of the data array at these coordinates (indices) locations. Obviously, <code>data[coords]</code> does not work.</p> <p>I suspect there is an easy way to do that, but stackoverflow failed me up to now. Thanks in advance for your help.</p> <p>EDIT: An example would be</p> <pre><code>data=[[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 2, 1, 0, 0], [0, 0, 0, 1, 23, 40, 0, 0], [0, 0, 0, 1, 1, 2, 0, 0], [0, 0, 3, 2, 0, 0, 0, 0], [0, 0, 4, 5, 6, 2, 1, 0], [0, 0, 0, 0, 1, 20, 0, 0], [0, 0, 0, 3, 1, 2, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] coords=[[1,4],[2,4],[2,5],[5,3],[6,5]] </code></pre> <p>and the desired output would be</p> <pre><code>out=[2,23,40,5,20] </code></pre>
<p>You could use a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p> <pre><code>In [73]: [data[i][j] for i,j in coords] Out[73]: [2, 23, 40, 5, 20] </code></pre> <p>The result returned by the list comprehension is equivalent to</p> <pre><code>result = [] for i,j in coords: result.append(data[i][j]) </code></pre>
python|arrays
2
1,903,683
40,440,692
Running multiple sockets at the same time in python
<p>I am trying to listen and send data to several sockets at the same time. When I run the program I get en error saying:</p> <pre><code> File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 704, in __init__ if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: </code></pre> <p>OSError: [Errno 9] Bad file descriptor</p> <p>The first socket starts up correctly, but once I try to start a new one I get the error.</p> <pre><code>class bot: def __init__(self, host, port): self.host = host self.port = port sock = socket.socket() s = None def connect_to_server(self): self.s = ssl.wrap_socket(self.sock) self.s.connect((self.host, self.port)) </code></pre> <p>Above is the class and then I'm running several instances.</p> <pre><code>def run_bots(bots): for bot in bots: try: threading.Thread(target=bot.connect_to_server()).start() except: print(bot.host) print("Error: unable to start thread") bots = [] b = bot('hostname.com', 1234) b1 = bot('hostname1.com', 1234) bots.append(b) bots.append(b1) run_bots(bots) </code></pre> <p>I don't know what to do. Anyone have an idea of what could be the problem?</p>
<p>You are using the same socket. Create one for each bot:</p> <pre><code>class bot: def __init__(self, host, port): self.host = host self.port = port self.s = None def connect_to_server(self): sock = socket.socket() self.s = ssl.wrap_socket(sock) self.s.connect((self.host, self.port)) </code></pre>
python|python-3.x|sockets
1
1,903,684
26,079,040
Flask - got multiple values for keyword argument 'eventid' - Decorators
<p>I'm currently running a Python Flask application that makes use of the following decorator:</p> <pre><code>def login_required(fn): @wraps(fn) def wrapper(*args, **kwargs): if 'phone' in session: user = User.query.filter_by(phone = session['phone']).first() if user: return fn(user, *args, **kwargs) else: return redirect(url_for('login')) return wrapper </code></pre> <p>I have the following view:</p> <pre><code>@app.route('/delete/&lt;eventid&gt;') @login_required def delete(eventid): </code></pre> <p>That is being called by the following line:</p> <pre><code>url_for('delete', eventid=event.uid) </code></pre> <p>This produces the following error:</p> <pre><code>delete() got multiple values for keyword argument 'eventid' </code></pre> <p>The delete() function works when the decorator is NOT used. The decorator works when it is NOT used with the delete() function.</p> <p>How do I go about solving this problem?</p>
<p>Your wrapper function passes an additional argument <code>user</code> to the decorated function (in this case <code>delete</code>)</p> <pre><code>return fn(user, *args, **kwargs) </code></pre> <p>But your <code>delete</code> function only takes a single arg called <code>eventid</code>. Python interprets the first arg (user) as the eventid arg, but then gets another keyword argument for the same name, hence the odd error message.</p> <p>It's essentially like this:</p> <pre><code>&gt;&gt;&gt; def delete(eventid): print eventid &gt;&gt;&gt; delete('user', eventid='test') Traceback (most recent call last): File "&lt;pyshell#3&gt;", line 1, in &lt;module&gt; delete('user', eventid='test') TypeError: delete() got multiple values for keyword argument 'eventid' </code></pre> <p>So it works without the decorator because no user arg is passed in. Just add the user as the first arg to the delete function.</p>
python|flask
7
1,903,685
25,945,257
Python: return true if obj has exactly type t
<p>given a function:</p> <pre><code>def my_func(obj, t) </code></pre> <p>My job is to write the function so that it will return true if <strong>obj</strong> has exactly type <strong>t</strong>. It is different from isinstance. Like, isinstance always true when my_func is true, but the converse is false.</p> <pre><code>For example: isinstance(True, int) = True; myFunc(True, int) = False; </code></pre> <p>My code so far is:</p> <pre><code>def my_func(obj, t): return obj.__class__ == t </code></pre> <p>My question is that: is that right for all objects and types? if it fails, can you show me in what case it fail?(my instructor never give anything so simple) Thanks a lot!</p>
<p>Note that the style of classes you are using is relevant here. Python 3 uses new-style classes and Python 2 is capable of old-style classes and new-style classes. Some relevant expressions in the Python 2 interpreter are shown below:</p> <pre><code>&gt;&gt;&gt; class A: pass; # old-style class (default style in py2) ... &gt;&gt;&gt; class B(object): pass; # new-style class (default style in py3) ... &gt;&gt;&gt; type(A()) &lt;type 'instance'&gt; &gt;&gt;&gt; A().__class__ &lt;class __main__.A at 0x01DC97A0&gt; &gt;&gt;&gt; type(B()) &lt;class '__main__.B'&gt; &gt;&gt;&gt; B().__class__ &lt;class '__main__.B'&gt; </code></pre> <p>The key point to note here is that for new-style classes, using <code>.__class__</code> is indeed equivalent to built-in <code>type</code> function, but for old-style classes, <code>type(A()) != A().__class__</code>. This is because <code>A().__class__ == A</code> is <code>True</code> while <code>type(A()) == A</code> is <code>False</code> for old-style classes.</p> <p>If you are using Python 2, I would recommend using <code>.__class__</code> instead of <code>type()</code> so you can handle custom-made types. If you are using Python 3, you can go with either method, since new-style classes are the default there.</p>
python
1
1,903,686
2,021,764
how to make fillable forms with reportlab in python
<p>can anyone please help me with creating forms in python using the reportlab lib. i am totally new to this and i would appreciate sample code thanks</p>
<p>Apparently reportlab does not support creating fillable pdf forms. The only thing I found about it being present in the API dates from 2003, afterwards all statements clearly say no.</p> <p>I'm answering this so late because this is one of the highest hits when you enter 'reportlab forms' in google. I do agree with Travis you should google easy questions yourself, but this isn't really clearly answered anywhere.</p>
python|pdf-generation|reportlab
7
1,903,687
1,855,477
how to access sys.argv (or any string variable) in raw mode?
<p>I'm having difficulties parsing filepaths sent as arguments:</p> <p>If I type:</p> <pre><code>os.path.normpath('D:\Data2\090925') </code></pre> <p>I get</p> <pre><code>'D:\\Data2\x0090925' </code></pre> <p>Obviously the \0 in the folder name is upsetting the formatting. I can correct it with the following:</p> <pre><code>os.path.normpath(r'D:\Data2\090925') </code></pre> <p>which gives</p> <pre><code>'D:\\Data2\\090925' </code></pre> <p>My problem is, how do I achieve the same result with sys.argv? Namely:</p> <pre><code>os.path.normpath(sys.argv[1]) </code></pre> <p>I can't find a way for feeding sys.argv in a raw mode into os.path.normpath() to avoid issues with folders starting with zero! </p> <p>Also, I'm aware that I could feed the script with <code>python script.py D:/Data2/090925</code> , and it would work perfectly, but unfortunately the windows system stubbornly supplies me with the '\', not the '/', so I really need to solve this issue instead of avoiding it.</p> <p><strong>UPDATE1</strong> to complement: if I use the script test.py: </p> <pre><code>import os, sys if __name__ == '__main__': print 'arg 1: ',sys.argv[1] print 'arg 1 (normpath): ',os.path.normpath(sys.argv[1]) print 'os.path.dirname :', os.path.dirname(os.path.normpath(sys.argv[1])) </code></pre> <p>I get the following:</p> <pre><code>C:\Python&gt;python test.py D:\Data2\091002\ arg 1: D:\Data2\091002\ arg 1 (normpath): D:\Data2\091002 os.path.dirname : D:\Data2 </code></pre> <p>i.e.: I've lost 091002...</p> <p><strong>UPDATE2</strong>: as the comments below informed me, the problem is solved for the example I gave when normpath is removed:</p> <pre><code>import os, sys if __name__ == '__main__': print 'arg 1: ',sys.argv[1] print 'os.path.dirname :', os.path.dirname(sys.argv[1]) print 'os.path.split(sys.argv[1])):', os.path.split(sys.argv[1]) </code></pre> <p>Which gives:</p> <pre><code> C:\Python&gt;python test.py D:\Data2\091002\ arg 1: D:\Data2\091002\ os.path.dirname : D:\Data2\091002 os.path.split : ('D:\\Data2\\090925', '') </code></pre> <p>And if I use D:\Data2\091002 :</p> <pre><code> C:\Python&gt;python test.py D:\Data2\091002 arg 1: D:\Data2\091002 os.path.dirname : D:\Data2 os.path.split : ('D:\\Data2', '090925') </code></pre> <p>Which is something I can work with: Thanks!</p>
<p>"Losing" the last part of your path is nothing to do with escaping (or lack of it) in <code>sys.argv</code>.</p> <p>It is the expected behaviour if you use <code>os.path.normpath()</code> and then <code>os.path.dirname()</code>.</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.normpath("c:/foo/bar/") 'c:\\foo\\bar' &gt;&gt;&gt; os.path.dirname('c:\\foo\\bar') 'c:\\foo' </code></pre>
python|string-literals
5
1,903,688
63,115,389
How can i open closed window in tkinter?
<p>I am trying to create an application that can open another .py file(Tkinter application). I had tried the below code and it works for first time(it opens another application for the first time) but if i close that app and try to open it again by clicking on the open button then it doesn't open for second time.</p> <p>Main Application:</p> <pre><code>from tkinter import * root=Tk() def ope(): import SecondApp Open_1=Button(root,text=&quot;Open&quot;,command=ope) Open_1.pack() root.mainloop() </code></pre> <p>SecondApp:</p> <pre><code>from tkinter import * root1=Tk() Label=Label(root1,text=&quot;Hey welcome in second app&quot;) Label.pack() root1.mainloop() </code></pre> <p>If i click the <code>Open_1 button</code> for first time from mainapp then it open second app in that time but if i try again then in second time it doesn't do anything. And in last I want to open the second window using <code>import SecondApp</code> Please Help me as soon as possible. Thanks for everyone who tried to solve my problem</p>
<p>You can use <code>Toplevel()</code> to create a second window</p> <p>Try this code:</p> <pre><code>from tkinter import * root=Tk() def ope(): root1 = Toplevel() Label1 = Label(root1,text=&quot;Hey welcome in second app&quot;) Label1.pack() root1.mainloop() Open_1=Button(root,text=&quot;Open&quot;,command=ope) Open_1.pack() root.mainloop() </code></pre>
python|tkinter
0
1,903,689
32,719,578
Operation on 2d array columns
<p>I'd like to know if it's possible to apply a function (or juste an operation, such as replacing values) to column in a python 2d array, without using for loops. </p> <p>I'm sorry if the question has already been asked, but I couldn't find anything specific about my problem.</p> <p>I'd like to do something like :</p> <pre><code>array[:][2] = 1 </code></pre> <p>Which would mean <em>put 1 for each value at the third column</em>, or</p> <pre><code>func(array[:][2]) </code></pre> <p>Which would mean <em>apply <code>func()</code> to the third column of array</em>.</p> <p>Is there any magic python-way to do it ?</p> <p>EDIT : The truth has been spoken. I forgot to say that I didn't want to avoid <code>for()</code> statement to improve performance, but just because I don't wan to add multiples lines for this precise instance. We got 2 answers here, one in a native way, and two more with the help of Numpy. Thanks a lot for your answers !</p>
<p>Without numpy it can be done like this:</p> <pre><code>map(lambda x: x[:2] + [1] + x[3:], array) map(lambda x: x[:2] + my_func(x[2]) + x[3:], array) </code></pre>
python|arrays|2d
7
1,903,690
34,758,779
Manually install pip into virutalenv
<p>I am trying to create a virtualenv in which I will run an older version of Django (1.4.2) and a specific version of Python (2.7.8) on OSX El Capitan. Here are the steps I went through:</p> <p>I downloaded and compiled Python 2.7.8 using this workflow: <a href="https://stackoverflow.com/questions/5506110/is-it-possible-to-install-another-version-of-python-to-virtualenv">Is it possible to install another version of Python to Virtualenv?</a></p> <p>When I try to create a new virtualenv with --python flag pointed to my newly compiled Python2.7.8, I get an error message that looks like this:</p> <pre><code> Complete output from command /Users/luka/xxx/virtu...y2_7_8/bin/python2.7 -c "import sys, pip; sys...d\"] + sys.argv[1:]))" setuptools pip wheel: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.7/site-packages/virtualenv-13.1.2-py2.7.egg/virtualenv_support/pip-7.1.2-py2.py3-none-any.whl/pip/__init__.py", line 15, in &lt;module&gt; File "/Library/Python/2.7/site-packages/virtualenv-13.1.2-py2.7.egg/virtualenv_support/pip-7.1.2-py2.py3-none-any.whl/pip/vcs/subversion.py", line 9, in &lt;module&gt; File "/Library/Python/2.7/site-packages/virtualenv-13.1.2-py2.7.egg/virtualenv_support/pip-7.1.2-py2.py3-none-any.whl/pip/index.py", line 30, in &lt;module&gt; File "/Library/Python/2.7/site-packages/virtualenv-13.1.2-py2.7.egg/virtualenv_support/pip-7.1.2-py2.py3-none-any.whl/pip/wheel.py", line 35, in &lt;module&gt; File "/Library/Python/2.7/site-packages/virtualenv-13.1.2-py2.7.egg/virtualenv_support/pip-7.1.2-py2.py3-none-any.whl/pip/_vendor/distlib/scripts.py", line 14, in &lt;module&gt; File "/Library/Python/2.7/site-packages/virtualenv-13.1.2-py2.7.egg/virtualenv_support/pip-7.1.2-py2.py3-none-any.whl/pip/_vendor/distlib/compat.py", line 31, in &lt;module&gt; ImportError: cannot import name HTTPSHandler </code></pre> <p>If I rerun the same command with --no-setuptools flag, everything works properly, I get access to the Python version I need, but I don't have pip and setuptools in the site-package directory, which is a problem because now I can't install a specific version of Django inside my virtualenv. Can I simply copy existing system-wide pip installation into my virtualenv or install pip in some other way inside of it?</p> <p>Thanks! Luka</p>
<p>You can just install <code>pip</code> in the new virtualenv <a href="https://pip.pypa.io/en/stable/installing/#install-pip" rel="nofollow">using the <code>get-pip.py</code> script</a>:</p> <ol> <li>Download <code>get-pip.py</code>, e.g. using wget or curl</li> <li>Run it with the virtualenv's python, i.e. activate the virtualenv and then run <code>python get-pip.py</code></li> </ol>
python|pip|virtualenv
1
1,903,691
34,607,093
transfer data between databases - influx-python
<p>I am trying to write points that been taken from one database to another (influxdb-python), I have created a list of dict, and I am using write_points('list of dicts'). I even tried to simplify things by getting only 2 points.</p> <p>here is my code and the errors, pls help</p> <pre><code>rs = cli.query("""SELECT * FROM cpu_value WHERE time &gt; now() - 2s""") points = rs.get_points() a=next(points) b=next(points) temp=[] temp.append(a) temp.append(b) client = InfluxDBClient(database='test') client.write_points(temp) </code></pre> <p><a href="https://i.stack.imgur.com/eRUIb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eRUIb.png" alt="enter image description here"></a></p>
<p>It's easier to use the <a href="https://docs.influxdata.com/influxdb/v0.9/query_language/data_exploration/#the-into-clause" rel="nofollow">INTO clause</a> to write from one database to another, rather than exporting and importing the points via an external library.</p>
python|influxdb
0
1,903,692
27,113,495
Creating a leaderboard for offline game in Python
<p>For a school project, I'm creating a game that has a score system, and I would like to create some sort of leaderboard. Once finished, the teachers will upload it to a shared server where other students can download a copy of the game, but unfortunately students can't save to that server; if we could, leaderboards would be a piece of cake. There would at most be a few hundred scores to keep track of, and all the computers have access to the internet.</p> <p>I don't know much about servers or hosting, and I don't know java, html, or any other language commonly used in web development, so other related questions don't really help. My game prints the scoring information to a text file, and from there I don't know how to get it somewhere online that everyone can access. </p> <p>Is there a way to accomplish such a task with just python?</p> <p>Here I have the code for updating a leaderboard file (assuming it would just be a text file) once I have the scores. This would assume that I had a copy of the leaderboard and the score file in the same place.</p> <p>This is the format of my mock-leaderboard (Leaderboards.txt):</p> <pre><code>Leaderboards 1) JOE 10001 2) ANA 10000 3) JAK 8400 4) AAA 4000 5) ABC 3999 </code></pre> <p>This is what the log-file would print - the initials and score (log.txt):</p> <pre><code>ABC 3999 </code></pre> <p>Code (works for both python 2.7 and 3.3):</p> <pre><code>def extract_log_info(log_file = "log.txt"): with open(log_file, 'r') as log_info: new_name, new_score = [i.strip('\n') for i in log_info.readlines()[:2]] new_score = int(new_score) return new_name, new_score def update_leaderboards(new_name, new_score, lb_file = "Leaderboards.txt"): cur_index = None with open(lb_file, 'r') as lb_info: lb_lines = lb_info.readlines() lb_lines_cp = list(lb_lines) # Make a copy for iterating over for line in lb_lines_cp: if 'Leaderboards' in line or line == '\n': continue # Now we're at the numbers position, name, score = [ i for i in line.split() ] if new_score &gt; int(score): cur_index = lb_lines.index(line) cur_place = int(position.strip(')')) break # If you have reached the bottom of the leaderboard, and there # are no scores lower than yours if cur_index is None: # last_place essentially gets the number of entries thus far last_place = int(lb_lines[-1].split()[0].strip(')')) entry = "{}) {}\t{}\n".format((last_place+1), new_name, new_score) lb_lines.append(entry) else: # You've found a score you've beaten entry = "{}) {}\t{}\n".format(cur_place, new_name, new_score) lb_lines.insert(cur_index, entry) lb_lines_cp = list(lb_lines) # Make a copy for iterating over for line in lb_lines_cp[cur_index+1:]: position, entry_info = line.split(')', 1) new_entry_info = str(int(position)+1) + ')' + entry_info lb_lines[lb_lines.index(line)] = new_entry_info with open(lb_file, 'w') as lb_file_o: lb_file_o.writelines(lb_lines) if __name__ == '__main__': name, score = extract_log_info() update_leaderboards(name, score) </code></pre> <p>Some more info:</p> <ul> <li>The score would be less than 1 000 000</li> <li>Ideally, the solution would just be some code external to the game, so that I would just make an executable that the user would run after they've finished</li> <li>I know it doesn't sound very secure - and it isn't - but that's ok, it's doesn't need to be hackproof</li> </ul>
<p>The easiest is probably to just use MongoDB or something (MongoDB is a NoSQL type database that allows you to save dictionary data easily...)</p> <p>You can use the free account at <a href="https://mongolab.com" rel="nofollow noreferrer">https://mongolab.com</a> (that should give you plenty of space).</p> <p>You will need pymongo as well <code>pip install pymongo</code>.</p> <p>Then you can simply save records there:</p> <pre><code>from pymongo import MongoClient, DESCENDING uri = &quot;mongodb://test1:test1@ds051990.mongolab.com:51990/joran1&quot; my_db_cli = MongoClient(uri) db = my_db_cli.joran1 # select the database ... my_scores = db.scores # this will be created if it doesn't exist! # add a new score my_scores.insert({&quot;user_name&quot;: &quot;Leeeeroy Jenkins&quot;, &quot;score&quot;: 124, &quot;time&quot;: &quot;11/24/2014 13:43:22&quot;}) my_scores.insert({&quot;user_name&quot;: &quot;bob smith&quot;, &quot;score&quot;: 88, &quot;time&quot;: &quot;11/24/2014 13:43:22&quot;}) # get a list of high scores (from best to worst) print(list(my_scores.find().sort(&quot;score&quot;, DESCENDING))) </code></pre> <p>Those credentials will actually work if you want to test the system (keep in mind I added leeroy a few times).</p>
python|leaderboard
2
1,903,693
12,093,971
How to filter the output of pexpect
<p>In python pexpect, I want to filter the oupt. For example, in the below code I want only the date to be printed.</p> <pre><code>#!/usr/bin/env python import pexpect,time p=pexpect.spawn('ssh myusername@192.168.151.80') p.expect('Password:') p.sendline('mypassword') time.sleep(2) p.sendline('date') p.expect('IST') current_date = p.before print 'the current date in remote server is: %s' % current_date </code></pre> <p><strong>Actual output:</strong></p> <pre><code>the current date in remote server is: Last login: Thu Aug 23 22:58:02 2012 from solaris3 Sun Microsystems Inc. SunOS 5.10 Generic January 2005 You have new mail. welcome -bash-3.00$ date Thu Aug 23 23:03:10 </code></pre> <p><strong>Expected output:</strong></p> <pre><code>the current date in remote server is: Thu Aug 23 23:03:10 </code></pre>
<p><code>before</code> will give you everything since the previous <code>expect</code> call.</p> <p>You could split the output on newline: </p> <pre><code>current_date = p.before.split('\n')[-1] </code></pre> <p>However it would be better to expect the prompt instead of sleeping 2 seconds:</p> <pre><code>p.sendline('mypassword') p.expect('[#\$] ') p.sendline('date') </code></pre>
python|pexpect
2
1,903,694
12,212,636
SQL Alchemy overriding ==
<p>I am creating SQLAlchemy class that represents user credentials.</p> <p>I want to have field <code>password</code> that stores hashed value of password. Therefore I would like to override its behavior the following way:</p> <ol> <li><p>When assigned <code>credentials.password = value</code> it actually stores hash of the value</p></li> <li><p>When comparing <code>credentials.password == value</code> it actually compares with hash of the value</p></li> </ol> <p>I have read the following part of SQLAlchemy documentation <a href="http://docs.sqlalchemy.org/en/rel_0_7/orm/mapper_config.html#using-descriptors-and-hybrids" rel="nofollow">http://docs.sqlalchemy.org/en/rel_0_7/orm/mapper_config.html#using-descriptors-and-hybrids</a></p> <p>And I think I do understand how to solve the issue number 1.</p> <p>I am however unsure, how to do second point. Is there a way to do it the safe way (without breaking SQLAlchemy)?</p> <p>Here is the example model:</p> <pre><code>class Credentials(Base): __tablename__ = 'credentials' id = Column(Integer, primary_key=True) _password = Column('password', String) @hybrid_property def password(self): return self._password @password.setter(self): self._password = hash(self._password) </code></pre>
<p>For comparing, since you can't un-hash the password, you would need to create a custom type for the Column class, that over-rides the eq operator:</p> <pre><code>class MyPasswordType(String): class comparator_factory(String.Comparator): def __eq__(self, other): return self.operate(operators.eq, hash(other)) </code></pre> <p>Have a look at: <a href="http://docs.sqlalchemy.org/en/latest/core/types.html#types-operators" rel="nofollow">http://docs.sqlalchemy.org/en/latest/core/types.html#types-operators</a></p> <p>And <a href="http://docs.sqlalchemy.org/en/latest/core/types.html#sqlalchemy.types.TypeEngine.comparator_factory" rel="nofollow">http://docs.sqlalchemy.org/en/latest/core/types.html#sqlalchemy.types.TypeEngine.comparator_factory</a></p> <p>To set you just need to pass in the value:</p> <pre><code>@password.setter def password(self, value): self._password = hash(value) </code></pre>
python|sqlalchemy
2
1,903,695
23,342,532
Using dynamic lists in query in Pandas
<p>Say, for the sake of an example, that I have several columns encoding different types of rates (<code>"annual rate"</code>, <code>"1/2 annual rate"</code>, etc.). I want to use <code>query</code> on my dataframe to find entries where <strong>any</strong> of these rates is above <code>1</code>.</p> <p>First I find the columns that I want to use in my query:</p> <pre><code>cols = [x for ix, x in enumerate(df.columns) if 'rate' in x] </code></pre> <p>where, say, <code>cols</code> contains:</p> <pre><code>["annual rate", "1/2 annual rate", "monthly rate"] </code></pre> <p>I then want to do something like:</p> <pre><code>df.query('any of my cols &gt; 1') </code></pre> <p>How can I format this for <code>query</code>?</p>
<p><code>query</code> performs a full parse of a Python <em>expression</em> (with some limits, e.g., you can't use <code>lambda</code> expressions or ternary <code>if</code>/<code>else</code> expressions). This means that any columns that you refer to in your query string <strong>must</strong> be a valid Python identifier (a more formal word for "variable name"). One way to check this is to use the <code>Name</code> pattern lurking in the <code>tokenize</code> module:</p> <pre><code>In [156]: tokenize.Name Out[156]: '[a-zA-Z_]\\w*' In [157]: def isidentifier(x): .....: return re.match(tokenize.Name, x) is not None .....: In [158]: isidentifier('adsf') Out[158]: True In [159]: isidentifier('1adsf') Out[159]: False </code></pre> <p>Now since your column names have spaces, each word separated by spaces will be evaluated as separate identifier so you'll have something like</p> <pre><code>df.query("annual rate &gt; 1") </code></pre> <p>which is invalid Python syntax. Try typing <code>annual rate</code> into a Python interpreter and you'll get a <code>SyntaxError</code> exception.</p> <p>Take home message: rename your columns to be valid variable names. You won't be able to do this programmatically (at least, easily) unless your columns follow some kind of structure. In your case you could do</p> <pre><code>In [166]: cols Out[166]: ['annual rate', '1/2 annual rate', 'monthly rate'] In [167]: list(map(lambda x: '_'.join(x.split()).replace('1/2', 'half'), cols)) Out[167]: ['annual_rate', 'half_annual_rate', 'monthly_rate'] </code></pre> <p>Then you can format the query string similar to @acushner's example</p> <pre><code>In [173]: newcols Out[173]: ['annual_rate', 'half_annual_rate', 'monthly_rate'] In [174]: ' or '.join('%s &gt; 1' % c for c in newcols) Out[174]: 'annual_rate &gt; 1 or half_annual_rate &gt; 1 or monthly_rate &gt; 1' </code></pre> <h3>Note: You don't actually <em>need</em> to use <code>query</code> here:</h3> <pre><code>In [180]: df = DataFrame(randn(10, 3), columns=cols) In [181]: df Out[181]: annual rate 1/2 annual rate monthly rate 0 -0.6980 0.6322 2.5695 1 -0.1413 -0.3285 -0.9856 2 0.8189 0.7166 -1.4302 3 1.3300 -0.9596 -0.8934 4 -1.7545 -0.9635 2.8515 5 -1.1389 0.1055 0.5423 6 0.2788 -1.3973 -0.9073 7 -1.8570 1.3781 0.0501 8 -0.6842 -0.2012 -0.5083 9 -0.3270 -1.5280 0.2251 [10 rows x 3 columns] In [182]: df.gt(1).any(1) Out[182]: 0 True 1 False 2 False 3 True 4 True 5 False 6 False 7 True 8 False 9 False dtype: bool In [183]: df[df.gt(1).any(1)] Out[183]: annual rate 1/2 annual rate monthly rate 0 -0.6980 0.6322 2.5695 3 1.3300 -0.9596 -0.8934 4 -1.7545 -0.9635 2.8515 7 -1.8570 1.3781 0.0501 [4 rows x 3 columns] </code></pre> <p>As @Jeff noted in the comments you <em>can</em> refer to non-identifier column names, albeit in a clunky way:</p> <pre><code>pd.eval('df[df["annual rate"]&gt;0]') </code></pre> <p>I wouldn't recommended writing code like this if you want to save the lives of kittens.</p>
python|pandas
5
1,903,696
22,951,442
How to make python's argparse generate Non-English text?
<p>The <strong>argparse</strong> module "automatically generates help and usage messages". I can give Non-English names to the arguments and provide Non-English help texts; but the help output then becomes a mixture of at least two languages, because terms like <code>usage</code>, <code>positional arguments</code>, <code>optional arguments</code> and <code>show this help message and exit</code> are automatically generated in English.</p> <p>How can I replace this English output with translations?</p> <p>Preferably, I would like to provide the translations within the script, so that the script generates the same output wherever it is started.</p> <p><strong>Edit:</strong> Based on the answer by Jon-Eric, here an example with his solution:</p> <pre><code>import gettext def Übersetzung(Text): Text = Text.replace("usage", "Verwendung") Text = Text.replace("show this help message and exit", "zeige diese Hilfe an und tue nichts weiteres") Text = Text.replace("error:", "Fehler:") Text = Text.replace("the following arguments are required:", "Die folgenden Argumente müssen angegeben werden:") return Text gettext.gettext = Übersetzung import argparse Parser = argparse.ArgumentParser() Parser.add_argument("Eingabe") Argumente = Parser.parse_args() print(Argumente.Eingabe) </code></pre> <p>saved as <code>Beispiel.py</code> gives with <code>python3 Beispiel.py -h</code> the following help output:</p> <pre><code>Verwendung: Beispiel.py [-h] Eingabe positional arguments: Eingabe optional arguments: -h, --help zeige diese Hilfe an und tue nichts weiteres </code></pre>
<p><code>argparse</code> uses the <a href="https://docs.python.org/3/library/gettext.html#gnu-gettext-api" rel="noreferrer"><code>gettext</code> API inspired by GNU gettext</a>. You can use this API to integrate your translation of <code>argparse</code> in a relatively clean manner.</p> <p>To do so, call the following code before <code>argparse</code> outputs any text (but possibly after <code>import argparse</code>):</p> <pre><code>import gettext # Use values that suit your project instead of 'argparse' and 'path/to/locale' gettext.bindtextdomain('argparse', 'path/to/locale') gettext.textdomain('argparse') </code></pre> <p>In order for this solution to work, your translation of <code>argparse</code> must be located at <code>path/to/locale/ll/LC_MESSAGES/argparse.mo</code> where <code>ll</code> is the code of the current language (for example <code>de</code>; can be configured for example by setting the environment variable <code>LANGUAGE</code>).</p> <h2>How do you generate the <code>.mo</code> file?</h2> <ol> <li><code>pygettext --default-domain=argparse /usr/local/lib/python3.5/argparse.py</code> <ul> <li>Use the actual location of <code>argparse.py</code></li> <li>Creates the file <code>argparse.pot</code></li> </ul></li> <li><code>cp argparse.pot argparse-ll.po</code> <ul> <li>Use an actual language code instead of <code>ll</code></li> </ul></li> <li>Fill in the missing translation strings in <code>argparse-ll.po</code></li> <li><code>msgfmt argparse-ll.po -o locale/ll/LC_MESSAGES/argparse.mo</code></li> </ol> <p>See <a href="https://docs.python.org/3/library/gettext.html#internationalizing-your-programs-and-modules" rel="noreferrer"><code>gettext</code> documentation</a> for details about creating <code>.mo</code> file.</p> <p>I have published these instructions in more detail in <a href="https://github.com/filipbartek/argparse-cs/blob/master/README.md" rel="noreferrer">README.md</a> of my <a href="https://github.com/filipbartek/argparse-cs" rel="noreferrer">Czech translation of <code>argparse</code></a>.</p>
python|internationalization|argparse
10
1,903,697
7,719,651
How can I change the resolution of a raster using GDAL?
<p>I am looking for the best way to change the resolution of a GDAL raster dataset.</p> <p>For example, I have a raster that has a pixel size of (30, -30), and I would like to change the pixel size to (5, -5), interpolating all values for a given pixel into the output raster.</p> <p>So for each pixel of the input raster, I would like to have 36 pixels in the output raster that all share the same value.</p> <p>If I run <code>gdalwarp -tr 5 -5 inputRaster.tif outputRaster.tif</code>, I get exactly the result that I'm looking for, and so I would assume that I should be able to replicate this functionality with some GDAL function.</p> <p>I would prefer to avoid using a call to python's Subprocess class, if possible.</p>
<p>Use gdal.Warp function:</p> <pre><code>gdal.Warp('outputRaster.tif', 'inputRaster.tif', xRes=5, yRes=5) </code></pre>
python|gdal
6
1,903,698
41,973,862
sqlite3: count number of instances in column A for every unique instance in column B
<p>Say I have a sqlite table set up as such:</p> <pre><code> ColumnA | ColumnB ---------|---------- A | One B | One C | Two D | Three E | Two F | Three G | Three </code></pre> <p>Is there a query that would find the number of instances in Column A that have the same instance in Column B? Or would using a script to pull from rows (python sqlite3) be better?</p> <p>for instance, </p> <pre><code>query("One") = 2 query("Two") = 2 query("Three") = 3 </code></pre> <p>Thank you</p>
<p>This can easily be achieved by sqlite3 itself. </p> <pre><code>$ sqlite3 mydb.db SQLite version 3.11.0 2016-02-15 17:29:24 Enter ".help" for usage hints. sqlite&gt; .databases seq name file --- --------------- ---------------------------------------------------------- 0 main /home/ziya/mydb.db sqlite&gt; create table two_column( col_a char(5), col_b varchar(20) ); sqlite&gt; insert into two_column values('A', 'One'); sqlite&gt; insert into two_column values('B', 'One'); sqlite&gt; insert into two_column values('C', 'Two'); sqlite&gt; insert into two_column values('D', 'Three'); sqlite&gt; insert into two_column values('E', 'Two'); sqlite&gt; insert into two_column values('F', 'Three'); sqlite&gt; insert into two_column values('G', 'Three'); sqlite&gt; select * from two_column; A|One B|One C|Two D|Three E|Two F|Three G|Three sqlite&gt; select count(*) from two_column where col_b = 'One'; 2 sqlite&gt; select count(*) from two_column where col_b = 'Two'; 2 sqlite&gt; select count(*) from two_column where col_b = 'Three'; 3 </code></pre> <p>If you are ok with python,</p> <pre><code>&gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; c = sqlite3.connect("mydb.db") &gt;&gt;&gt; cur = c.execute("SELECT COUNT(col_b) FROM two_column WHERE col_b = '{}' ".format('A')) &gt;&gt;&gt; [r for r in cur] [(0,)] </code></pre> <p>You can easily make a function using above statements. </p>
python|sqlite
1
1,903,699
41,740,677
Add element with single quote to dictionary in Python
<p>I created dictionary in python like below:</p> <pre><code>flip= {'0': 'a"', '1':'b"', '2':'c"'} </code></pre> <p>But I don't want to use double quotes. I need elements with single quotes. How can I do something like below? I was trying with <code>\\</code>, <code>\</code>, but it seems not to work.</p> <p>Correct dict should look like below:</p> <pre><code>flip= {'0': 'a'', '1':'b'', '2':'c''} </code></pre>
<p>You can simply use double quotes around the element.</p> <pre><code>lip= {'0': "a'", '1':"b'", '2':"c'"} </code></pre>
python|string|dictionary|escaping|quotes
4