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,908,200
68,634,831
No gradients provided for any variable: ['generated_image:0']
<p>I working on neural style transfer project. when in final step when I train the model it is showing error</p> <p>I am adding two images one content image and second style image to produce the new image which is content image with style of style image</p> <blockquote> <p>No gradients provided for any variable: ['generated_image:0'].</p> </blockquote> <pre><code>optimizer = tf.keras.optimizers.Adam(learning_rate=0.001) @tf.function() def train_step(generated_image): with tf.GradientTape() as tape: a_G = vgg_model_outputs(generated_image) J_style = style_cost(a_S, a_G) J_content = content_cost(a_C, a_G) J = total_cost(J_content, J_style, alpha = 10, beta = 40) grad = tape.gradient(J, generated_image) optimizer.apply_gradients([(grad, generated_image)]) generated_image.assign(tf.clip_by_value(generated_image,clip_value_min=0.0, clip_value_max=1.0)) return J </code></pre> <pre><code>epochs = 5000 for i in range(epochs): train_step(generated_image) if i % 250 == 0: print(f&quot;Epoch {i} &quot;) if i % 250 == 0: image = tensor_to_image(generated_image) imshow(image) image.save(f&quot;output/image_{i}.jpg&quot;) plt.show() </code></pre> <p>full stack trace</p> <pre><code>ValueError Traceback (most recent call last) &lt;ipython-input-23-3a761c39189b&gt; in &lt;module&gt;() 1 epochs = 5000 2 for i in range(epochs): ----&gt; 3 train_step(generated_image) 4 if i % 250 == 0: 5 print(f&quot;Epoch {i} &quot;) 8 frames /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) 887 888 with OptionalXlaContext(self._jit_compile): --&gt; 889 result = self._call(*args, **kwds) 890 891 new_tracing_count = self.experimental_get_tracing_count() /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) 931 # This is the first call of __call__, so we have to initialize. 932 initializers = [] --&gt; 933 self._initialize(args, kwds, add_initializers_to=initializers) 934 finally: 935 # At this point we know that the initialization is complete (or less /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) 762 self._concrete_stateful_fn = ( 763 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access --&gt; 764 *args, **kwds)) 765 766 def invalid_creator_scope(*unused_args, **unused_kwds): /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) 3048 args, kwargs = None, None 3049 with self._lock: -&gt; 3050 graph_function, _ = self._maybe_define_function(args, kwargs) 3051 return graph_function 3052 /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) 3442 3443 self._function_cache.missed.add(call_context_key) -&gt; 3444 graph_function = self._create_graph_function(args, kwargs) 3445 self._function_cache.primary[cache_key] = graph_function 3446 /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) 3287 arg_names=arg_names, 3288 override_flat_arg_shapes=override_flat_arg_shapes, -&gt; 3289 capture_by_value=self._capture_by_value), 3290 self._function_attributes, 3291 function_spec=self.function_spec, /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) 997 _, original_func = tf_decorator.unwrap(python_func) 998 --&gt; 999 func_outputs = python_func(*func_args, **func_kwargs) 1000 1001 # invariant: `func_outputs` contains only Tensors, CompositeTensors, /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) 670 # the function a weak reference to itself to avoid a reference cycle. 671 with OptionalXlaContext(compile_with_xla): --&gt; 672 out = weak_wrapped_fn().__wrapped__(*args, **kwds) 673 return out 674 /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) 984 except Exception as e: # pylint:disable=broad-except 985 if hasattr(e, &quot;ag_error_metadata&quot;): --&gt; 986 raise e.ag_error_metadata.to_exception(e) 987 else: 988 raise ValueError: in user code: &lt;ipython-input-22-71263e1538e0&gt;:11 train_step * optimizer.apply_gradients([(grad, generated_image)]) /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:630 apply_gradients ** grads_and_vars = optimizer_utils.filter_empty_gradients(grads_and_vars) /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/optimizer_v2/utils.py:76 filter_empty_gradients ([v.name for _, v in grads_and_vars],)) ValueError: No gradients provided for any variable: ['generated_image:0']. </code></pre> <p>general image:</p> <pre><code>generated_image = tf.Variable(tf.image.convert_image_dtype(content_image, tf.float32)) noise = tf.random.uniform(tf.shape(generated_image), 0, 0.5) generated_image = tf.add(generated_image, noise) generated_image = tf.clip_by_value(generated_image, clip_value_min=0.0, clip_value_max=1.0) </code></pre> <p>i don't know what is wrong? please help!</p>
<p>I assume that you are trying to run the code from this <a href="https://www.coursera.org/learn/convolutional-neural-networks/home/welcome" rel="nofollow noreferrer">Coursera course</a> on your own computer, as I got exactly the same problem after trying to do it. The problem is that when you pass the generated_image to the train_step, it is of the wrong type. If you check the <code>type(generated_image)</code> it is likely to be</p> <p><code>&lt;class 'tensorflow.python.framework.ops.EagerTensor'&gt;</code>,</p> <p>while it should be:</p> <p><code>&lt;class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'&gt;</code>.</p> <p>You can easily fix this by adding the line <code>generated_image = tf.Variable(generated_image)</code> This line of code was originally there in a testing cell and you may have deleted it by mistake when cleaning up the code (this is exactly what I did). The best place is to add this line just after the last line of generated_image that you have posted.</p>
python|tensorflow|deep-learning|conv-neural-network
0
1,908,201
41,582,595
Twisted lineReceived not getting called
<p>I encountered a strange behavior when i was building a command line interface in python. Here is the striped down version of the code that can reproduce the issue.</p> <pre><code>from twisted.internet import reactor, stdio from twisted.protocols import basic class CommandLine(basic.LineReceiver): def __init__(self): self.linebuf = '' self.setLineMode() # why lineReceived doesn't work? # def lineReceived(self, data): def dataReceived(self, data): print 'data received ' + ' '.join([str(ord(c)) for c in data ]) print data if __name__=='__main__': stdio.StandardIO(CommandLine()) reactor.run() </code></pre> <p>The code above works as intended, out put in the form of "data received 108 115 115 10" is printed everytime a line is entered. Here is a sample output using dataReceived:</p> <pre><code>$ python cmdline.py hello data received 104 101 108 108 111 10 hello ^[[A data received 27 91 65 10 </code></pre> <p>However nothing gets printed out except the echo of the command line itself when I use lineReceived instead of dataReceived in the code above. Example output using lineReceived:</p> <pre><code>$ python cmdline.py hello ^[[A </code></pre> <p>According the the documentation on <a href="http://twistedmatrix.com/documents/8.0.0/api/twisted.protocols.basic.LineReceiver.html#lineReceived" rel="nofollow noreferrer">lineReceived</a>, the lineReceived function gets invoked when a line is received with the LineReceiver in line mode.</p> <p>For now I am using dataReceived to make it work. But I would like to find out why lineReceived is not working as intended. Any hint, suggestions, advice would be very much appreciated!</p> <p>Regards.</p>
<p>The reason is line <a href="http://twistedmatrix.com/documents/current/api/twisted.protocols.basic.LineReceiver.html#delimiter" rel="nofollow noreferrer">delimiter</a> constant which is set to r'\r\n' by default (MS Windows delimiter). Try to set it to '\n' (Linux and Mac OS) instead:</p> <pre><code>class CommandLine(basic.LineReceiver): delimiter = '\n' </code></pre>
python|command-line|twisted
2
1,908,202
6,791,920
How to limit import that may throw
<p>I have a class that will normally run under Windows and uses the win32com module. I also have a mock version of this class, both for testing and for demo purposes, which imports from the original, and should be able to run anywhere. So, it's like this, in two files:</p> <pre><code>import win32com.client class basic(): def local_instance(self): # called once during setup of execution res = win32com.client.Dispatch('Foo.Bar') def res_attrib(self): # called repeatedly by threads; must re-instantiate COM obj return win32com.client.Dispatch('Foo.Bar').Attribute def otherstuf(self): ... ======================= from basic import basic class mock(basic): def local_instance(self): res = mock_foobar() # mock implementation with .Attribute def res_attrib(self): return res.Attribute # mock implementation, this is OK # otherwise uses otherstuf() unchanged </code></pre> <p>The problem with this is when the mock version is loaded in an environment without win32com, the <code>import win32com.client</code> statement throws.</p> <p>My question is, what's the correct approach to limiting the application of that import?</p> <ul> <li><p>embed the import inside each of the methods, where it will be executed repeatedly:</p> <pre><code>def local_instance(self): import win32com.client res = win32com.client.Dispatch('Foo.Bar') def res_attrib(self): import win32com.client return win32com.client.Dispatch('Foo.Bar').Attribute </code></pre></li> <li><p>nest the import and the def's inside a try block, where it will fail strangely if user tries to run basic in a Windows environment but doesn't happen to have win32com installed:</p> <pre><code>try: import win32com.client def local_instance(self): res = win32com.client.Dispatch('Foo.Bar') def res_attrib(self): return win32com.client.Dispatch('Foo.Bar').Attribute except: # alternate or no defs </code></pre></li> <li><p>or other?</p></li> </ul>
<blockquote> <p>nest the import and the def's inside a try block,</p> </blockquote> <p>This is the standard approach that most people use.</p> <p>Do this <strong>outside</strong> any class definitions. At the very top level with your ordinary imports. Once only.</p> <p>Use the two functions within any class definition which occurs <em>after</em> this in the module.</p> <pre><code>try: import win32com.client def local_instance(): res = win32com.client.Dispatch('Foo.Bar') def res_attrib(): return win32com.client.Dispatch('Foo.Bar').Attribute except ImportError, why: # alternate or no defs </code></pre> <blockquote> <p>where it will fail strangely if user tries to run basic in a Windows environment but doesn't happen to have win32com installed:</p> </blockquote> <p>This is not true at all.</p> <p>First, you can examine the <code>why</code> variable.</p> <p>Second, you can examine <code>os.name</code> or <code>platform.uname()</code> to see if this is Win32 and alter the <code>except</code> block based on operating system.</p>
python
5
1,908,203
57,003,228
Get the first three largest values of a 2dnumpy array in python
<p>Hi I have a numpy array for eg.</p> <pre><code>arr = np.random.rand(4,5) array([[0.70733982, 0.1770464 , 0.55588376, 0.8810145 , 0.43711158], [0.22056565, 0.0193138 , 0.89995761, 0.75157581, 0.21073093], [0.22333035, 0.92795789, 0.3903581 , 0.41225472, 0.74992639], [0.92328687, 0.20438876, 0.63975818, 0.6179422 , 0.40596821]]) </code></pre> <p>I need to find the first three largest elements in the array.I tried </p> <pre><code>arr[[-arr.argsort(axis=-1)[:, :3]]] </code></pre> <p>I also referred this <a href="https://stackoverflow.com/questions/6910641/how-do-i-get-indices-of-n-maximum-values-in-a-numpy-array/23734295#23734295">question</a> on StackOverflow which only gives indices not values</p> <p>I was able to get the indices of the first three max values,but how to get its corresponding values.?</p> <p>Also I tried sorting the array by converting into list like given <a href="https://stackoverflow.com/questions/2173797/how-to-sort-2d-array-by-row-in-python">here</a></p> <p>But didnt give me the required result.Any Ideas?</p>
<p>You can directly use <code>np.sort()</code>:</p> <pre><code># np.sort sorts in ascending order # --&gt; we apply np.sort -arr arr_sorted = -np.sort(-arr,axis=1) top_three = arr_sorted[:,:3] </code></pre>
python|arrays|sorting|numpy-ndarray
1
1,908,204
25,784,965
get last insert ID
<p>So the question is how to get the id when view function try to <code>save()</code> the object.?</p> <p>I am using dropzonejs for uploading file to the server. Whenever User <code>drag &amp; drop</code> the file without waiting it will sent the files to server, this is working fine but </p> <p>Now i want <code>id</code> of the file for further processing like</p> <p><strong>What i want is :-</strong></p> <p>If User select <code>two or three</code> files in choose the check box option and click next and the render page i want to list all the selected files for saving <code>title</code> or <code>editing</code> etc .. even saving the foreign key also. </p> <p><strong>I tried:</strong></p> <pre><code>new_file = Tracks(file = request.FILES['file']) new_file.save() pprint.pprint(new_file.id) </code></pre> <p><em>Output of the console log is</em> </p> <pre><code>[11/Sep/2014 08:56:34] "GET /app/track-info HTTP/1.1" 200 10112 9L [11/Sep/2014 08:56:42] "POST /app/upload-tracks HTTP/1.1" 302 0 [11/Sep/2014 08:56:42] "GET /app/upload-tracks HTTP/1.1" 200 9580 10L [11/Sep/2014 08:57:20] "POST /app/upload-tracks HTTP/1.1" 302 0 </code></pre> <p>So conclusion from above <code>when each file upload happen 1 *id* is printing</code>.</p> <pre><code>#upload.html &lt;div class="tb-column col-5"&gt;&lt;p class="name" data-dz-name&gt;&lt;/p&gt;&lt;/div&gt; &lt;div class="tb-column col-2"&gt;&lt;p class="size" data-dz-size&gt;&lt;/p&gt;&lt;/div&gt; &lt;div class="select"&gt;&lt;input type="checkbox" class="checkBox" value="???" id="check"&gt;&lt;/div&gt; </code></pre> <p>So from what i want to achieve, i just need the value of the check box ....</p> <p>how to identify the particular HTML element, based on the output comes from console log (like 9L, 10L etc ..)</p> <p>how can i write <code>value="???"</code> which take automatically ID of the file .?</p> <p>I asked different <a href="https://stackoverflow.com/questions/25757756/how-can-i-create-a-two-step-form-or-wizard-where-the-model-has-a-foreign-key-b">question</a> yesterday &amp; some what related to this one but i had the difficulty in storing the file into db, so i dropped that idea. </p>
<p>I guess you wrote the view like save file into db ?</p> <p>then here is the answer will help you to get last inserted <code>id</code> in html page</p> <p>First write two view(request).</p> <ol> <li>For rendering page template and context.</li> <li>Second view is for <code>where file handling</code> and get the <code>id</code> </li> </ol> <p>like:</p> <pre><code>def view_second(request) if request.method == 'POST': if form valid: #get file here new.save() msg = new.id return HttpResponse(msg) </code></pre> <p>And that's it, Now in your html after the dropzone script ..</p> <pre><code>Dropzone.options.myDropzone = { init: function() { this.on("success", function(file, response) { #alert(response) }); </code></pre> <p>so in the response you will get the <code>id</code></p>
jquery|python|django|html|dropzone.js
0
1,908,205
44,434,889
How to handle print output from yahoo-finance quote reader?
<p>I'm designing a tool that will help me manage risk in my equities portfolio. I've got some code that gathers current price data from yahoo finance for 4 equities, 2x longs and 2x shorts. This is using the yahoo-finance tool.</p> <p>I can gather the data but I can't work out how to divide the prices by each other to return the value of the spread (stockA/stockB as a relative value trade)</p> <pre><code>#always helpful to show the version: (env) LaurencsonsiMac:~ admin$ python Python 2.7.10 (default, Oct 23 2015, 18:05:06) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin from yahoo_finance import Share &gt;&gt;&gt; L1 = Share('YHOO') &gt;&gt;&gt; L2 = Share('GOOG') &gt;&gt;&gt; S1 = Share('AAPL') &gt;&gt;&gt; S2 = Share('MSFT') &gt;&gt;&gt; print L1.get_price() 50.55 &gt;&gt;&gt; print S1.get_price() 154.45 </code></pre> <p>A small victory! I can fetch the price :) but I dont know how to manipulate this output as an object and define Long1 as “whatever is returned by print L1.get_price()” The final output would be a table like this, with the spread values as a single (super important!) number to two or three (whatever) decimal places.</p> <pre><code>Position, Spread YHOO/AAPL, 0.327 #value of Yahoo stock price/Apple stock price GOOG/MSF, 4.55 ticker/ticker, 10.14 ticker/ticker, 0.567 </code></pre> <p>I attempted to define Long1 and Short1 as the number that L1.get_price() prints:</p> <pre><code>&gt;&gt;&gt; Long1 = &quot;L1.get_price()&quot; &gt;&gt;&gt; Short1 = &quot;S2.get_price()&quot; </code></pre> <p>then hopefully I should get a number by dividing those two:</p> <pre><code>&gt;&gt;&gt; Long1/Short1 Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for /: 'str' and 'str' </code></pre> <p>so i tried to convert these numbers to a float [because it might work why not] but I’m clearly misunderstanding something:</p> <pre><code>&gt;&gt;&gt; float(Long1)/float(Short1) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ValueError: could not convert string to float: L1.get_price() </code></pre> <p>Alternatively I did manage to get an output using this piece of code using the pandas module: (thank you Brad Solomon for this:)</p> <pre><code>import pandas_datareader.data as web def get_quotes(symbols, type='dict'): quotes = web.get_quote_yahoo(symbols)['last'] if type == 'dict': quotes = quotes.to_dict() # otherwise, Series return quotes quotes = get_quotes(symbols=['RAD', 'MSFT']); quotes Out[16]: {'MSFT': 70.409999999999997, 'RAD': 3.46} </code></pre> <p>But how would you realise MSFT / RAD, get python to &quot;read the string&quot;?</p> <p>I'm really quite stuck, can anyone hint me how I can get my quoted prices into real objects I can use?</p>
<p>Variable assignment for <em>Long1</em> and <em>Short1</em> is wrong: instead of calling methods, you assign string literals with the names of the function. Try to change them to:</p> <pre><code>&gt;&gt;&gt; Long1 = L1.get_price() &gt;&gt;&gt; Short1 = S2.get_price() </code></pre>
python|pandas|yahoo-finance|trading|pandas-datareader
0
1,908,206
44,638,882
Estimate the standard deviation of fitted parameters in scipy.odr?
<p>(<em>Somewhat related to this question <a href="https://stackoverflow.com/questions/23951876/linear-fit-including-all-errors-with-numpy-scipy">Linear fit including all errors with NumPy/SciPy</a>, and borrowing code from this one <a href="https://stackoverflow.com/questions/22670057/linear-fitting-in-python-with-uncertainty-in-both-x-and-y-coordinates">Linear fitting in python with uncertainty in both x and y coordinates</a></em>)</p> <p>I fit a linear model (<code>y=a*x+b</code>) using fixed errors in <code>x,y</code> using <a href="https://docs.scipy.org/doc/scipy/reference/odr.html" rel="nofollow noreferrer">scipy.odr</a> (code is below), and I get:</p> <pre><code>Parameters (a, b): [ 5.21806759 -4.08019995] Standard errors: [ 0.83897588 2.33472161] Squared diagonal covariance: [ 1.06304228 2.9582588 ] </code></pre> <p>What is the correct standard deviation values for the fitted <code>a, b</code> parameters? I'm assuming these must be obtained from the <code>Squared diagonal covariance</code> values, but then how are these values related to the <code>Standard errors</code>?</p> <p><strong>ADD</strong></p> <p>As mentioned in the answer to <a href="https://stackoverflow.com/questions/41028846/how-to-compute-standard-error-from-odr-results">How to compute standard error from ODR results?</a> by <code>ali_m</code>, this is apparently related to <a href="https://github.com/scipy/scipy/issues/6842" rel="nofollow noreferrer">a bug in scipy.odr</a>. If one uses</p> <pre><code>np.sqrt(np.diag(out.cov_beta * out.res_var)) </code></pre> <p>(i.e: multiply the covariance by the residual variance) instead of just</p> <pre><code>np.sqrt(np.diag(out.cov_beta)) </code></pre> <p>the result now coincides with <code>out.sd_beta</code>.</p> <p>So now my question is: which is the proper standard deviation for the fitted parameters <code>(a, b)</code>? Is it <code>out.sd_beta</code> (equivalently: <code>np.sqrt(np.diag(out.cov_beta * out.res_var))</code>) or <code>np.sqrt(np.diag(out.cov_beta))</code>?</p> <p><br><br><br></p> <hr> <pre><code>import numpy as np from scipy.odr import Model, RealData, ODR import random random.seed(9001) np.random.seed(117) def getData(c): """Initiate random data.""" x = np.array([0, 1, 2, 3, 4, 5]) y = np.array([i**2 + random.random() for i in x]) xerr = c * np.array([random.random() for i in x]) yerr = c * np.array([random.random() for i in x]) return x, y, xerr, yerr def linear_func(p, x): """Linear model.""" a, b = p return a * x + b def fitModel(x, y, xerr, yerr): # Create a model for fitting. linear_model = Model(linear_func) # Create a RealData object using our initiated data from above. data = RealData(x, y, sx=xerr, sy=yerr) # Set up ODR with the model and data. odr = ODR(data, linear_model, beta0=[0., 1.]) # Run the regression. out = odr.run() # Estimated parameter values beta = out.beta print("Parameters (a, b): {}".format(beta)) # Standard errors of the estimated parameters std = out.sd_beta print("Standard errors: {}".format(std)) # Covariance matrix of the estimated parameters cov = out.cov_beta stddev = np.sqrt(np.diag(cov)) print("Squared diagonal covariance: {}".format(stddev)) # Generate data and fit the model. x, y, xerr, yerr = getData(1.) fitModel(x, y, xerr, yerr) </code></pre>
<p>Yes, <code>out.sd_beta</code> contains the standard deviations for the estimated parameters, which are equivalent to the square roots of the diagonal terms in the parameter covariance matrix.</p> <p>As you've already mentioned above, there's a bug in <code>scipy.odr</code> that means you have to multiply <code>out.cov_beta</code> by the residual variance <code>out.res_var</code> in order to derive the actual covariance matrix for the parameters.</p>
python|scipy|regression
2
1,908,207
71,974,983
"list indices must be integers or slices, not [custom class]" but I'm specifying an int class instance?
<p>I have a custom class defined like so:</p> <pre><code>class points: def __init__(self, x=0, h=0, l=0): self.x = x self.h = h self.l = l #bool location, 0 for start point, 1 for endpoint </code></pre> <p>Further in my code, I successfully build a list of these <code>points</code>, and the error comes when I attempt the following conditional:</p> <pre><code>for i in points_list: if (sorted_points[i].l == 0): </code></pre> <p>Python thinks that <code>sorted_points[i].l</code> isn't an integer or slice (it thinks it's a <code>points</code> object), but the only thing it can be is an integer (I even try printing out the list of <code>sorted_points</code> <code>l</code> values, and they are all 1 or 0), so I am very confused.</p>
<p><code>for el in my_list</code> syntax iterates over the elements of <code>my_list</code>. Look:</p> <pre><code>class A: pass l = [A(), A(), A()] for el in l: print(type(el)) # &lt;class '__main__.A'&gt; </code></pre> <p>So in your case you should use your <code>i</code> as instance of point.</p> <pre><code>for i in points_list: if i.l == 0: # if it's boolean, you should even write if not i.l ... </code></pre> <p>If you want to iterate over indexes, use <code>range</code></p> <pre><code>for i in range(len(points_list)): if not sorted_points[i].l: ... </code></pre>
python|class
1
1,908,208
71,909,569
Is there a way to limit the score to 7 points when scored
<pre><code>if fireBall.rect.x&gt;=690: score_1+=1 fireBall.ballspeed[0] = -fireBall.ballspeed[0] fireBall.rect.center = pygame.display.get_surface().get_rect().center if fireBall.rect.x&lt;=0: score_2+=1 fireBall.ballspeed[0] = -fireBall.ballspeed[0] fireBall.rect.center = pygame.display.get_surface().get_rect().center if fireBall.rect.y&gt;490: fireBall.ballspeed[1] = -fireBall.ballspeed[1] if fireBall.rect.y&lt;0: fireBall.ballspeed[1] = -fireBall.ballspeed[1] </code></pre> <p>I am making a ping pong game, I wanted the score to go to 7, but in my code the players can score continuously would keep on increasing.</p>
<p>To limit a value you can either use the built-in <a href="https://docs.python.org/3/library/functions.html#min" rel="nofollow noreferrer"><code>min</code></a> function</p> <pre class="lang-py prettyprint-override"><code>score_1 = min(score_1+1, 7) </code></pre> <p>or a <a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions" rel="nofollow noreferrer">Conditional expression</a>:</p> <pre class="lang-py prettyprint-override"><code>score_1 = score_1+1 if score_1 &lt; 7 else 7 </code></pre>
python|pygame
1
1,908,209
72,051,908
How to create table like structure in Python for alternative to avoid nesting of lists problem?
<p>I want to store data in a table like structure. The way i will populate it is generation of row after complex processing into different section of the codebase.</p> <pre><code>def insert_into_list(col1,col2,col3...): mytable=[] mytable.append([col1,col2,upper(col3)...]) return mytable </code></pre> <p>my ideal table will be of below structure:</p> <pre><code>mytable=[ ['john','doe','michigan',5000], ['jane','doe','michigan',10000], ['mona','johnson','florida',20000], ['sami','kahn','georgia',20000], ...and so on ] </code></pre> <p>Issue with using append is that mytable list is getting converted to a nested list at more than 2 levels and I am unable to do post processing on it easily.</p> <p>On the other hand using insert() I am getting error with insert that only 2 values are allowed and as you can see from my example my table has more than 3 columns atleast</p> <p>If I try to use pandas dataframe using append function, it threw error the append function in it is going to be deprecated and use concact. And concat is not easy to work with :|</p> <p>Questions:</p> <ol> <li>How can i modify the my use of list functions i.e. append or insert to correctly do it?</li> <li>Should i explore some other data structure instead of list to do this kind of work? If what options do you suggest to look . The criteria is that data structure should be easy to move around in various functions and different .py files</li> </ol> <p>You may ask why I am programming like this. I have been a Oracle Database Administrator dba and i am used to thinking table to be something like this :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>first</th> <th>last</th> <th>state</th> <th>salary</th> </tr> </thead> <tbody> <tr> <td>john</td> <td>doe</td> <td>michigan</td> <td>5000</td> </tr> <tr> <td>jane</td> <td>doe</td> <td>michigan</td> <td>10000</td> </tr> <tr> <td>mona</td> <td>johnson</td> <td>florida</td> <td>20000</td> </tr> <tr> <td>sami</td> <td>kahn</td> <td>georgia</td> <td>20000</td> </tr> </tbody> </table> </div>
<p>Most people use either a pandas dataframe or a numpy 2D array. Both are good options, although pandas tends to give more functionality (and it is built on top of numpy in any case).</p> <p>If concat is giving you trouble, you should be able to do the same thing you are doing with your list and just add items row by row by using <code>df.loc()</code> or <code>df.iloc()</code>.</p> <p>I found a good example for you here: <a href="https://www.geeksforgeeks.org/how-to-add-one-row-in-an-existing-pandas-dataframe/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/how-to-add-one-row-in-an-existing-pandas-dataframe/</a></p>
python
1
1,908,210
35,809,626
Python Lists : Why new list object gets created after concatenation operation?
<p>I was going through the topic about list in Learning Python 5E book. I notice that if we do concatenation on list, it creates new object. Extend method do not create new object i.e. In place change. What actually happens in case of Concatenation?</p> <p>For example</p> <pre><code>l = [1,2,3,4] m = l l = l + [5,6] print l,m #output ([1,2,3,4,5,6], [1,2,3,4]) </code></pre> <p>And if I use Augmented assignment as follows,</p> <pre><code>l = [1,2,3,4] m = l l += [5,6] print l,m #output ([1,2,3,4,5,6], [1,2,3,4,5,6]) </code></pre> <p>What is happening in background in case of both operations?</p>
<p>There are two methods being used there: <code>__add__</code> and <code>__iadd__</code>. <code>l + [5, 6]</code> is a shortcut for <code>l.__add__([5, 6])</code>. <code>l</code>'s <code>__add__</code> method returns the result of addition to something else. Therefore, <code>l = l + [5, 6]</code> is reassigning <code>l</code> to the addition of <code>l</code> and <code>[5, 6]</code>. It doesn't affect <code>m</code> because you aren't changing the object, you are redefining the name. <code>l += [5, 6]</code> is a shortcut for <code>l.__iadd__([5, 6])</code>. In this case, <code>__iadd__</code> changes the list. Since <code>m</code> refers to the same object, <code>m</code> is also affected.</p> <p><strong>Edit</strong>: If <code>__iadd__</code> is not implemented, for example with immutable types like <code>tuple</code> and <code>str</code>, then Python uses <code>__add__</code> instead. For example, <code>x += y</code> would be converted to <code>x = x + y</code>. Also, in <code>x + y</code> if <code>x</code> does not implement <code>__add__</code>, then <code>y.__radd__(x)</code>, if available, will be used instead. Therefore <code>x += y</code> <em>could</em> actually be <code>x = y.__radd__(x)</code> in the background.</p>
python|python-2.7|python-3.x
6
1,908,211
36,133,139
Use Python to modify an E-Mail (email.Message) and add an attachment
<p>I am reading a mail from stdin using</p> <pre><code>message = mailbox.email.message_from_file(sys.stdin) </code></pre> <p>and want to add an text file attachment. I tried the following:</p> <pre><code>new_msg = email.mime.multipart.MIMEMultipart('related') old_msg = email.mime.message.MIMEMessage(message) new_msg.attach(old_msg) att_msg = email.mime.text.MIMEText("Textfile attachment") att_msg.add_header('Content-Disposition', 'attachment', filename= 'my_attachment.txt') new_msg.attach(att_msg) maildir.add(new_msg) </code></pre> <p>where <code>maildir = mailbox.Maildir('~/mail')</code>.</p> <p>However, I get a message in <code>~/mail</code> with two attachments <code>ForwardedMessage.eml</code> and <code>my_attachment.txt</code>.</p> <p>My goal is to have the original message (with the same headers), but with the text file attached.</p> <p><strong>EDIT</strong> Let me give you an example. Original message:</p> <pre><code>To: foo@bar.com From: User &lt;user@mydomain.net&gt; Message-ID: &lt;56F2AAD2.7030408@mydomain.net&gt; Date: Wed, 23 Mar 2016 15:40:18 +0100 MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit Testmessage </code></pre> <p>With my code:</p> <pre><code>Content-Type: multipart/related; boundary="===============7892775444970429949==" MIME-Version: 1.0 --===============7892775444970429949== Content-Type: message/rfc822 MIME-Version: 1.0 To: foo@bar.com From: User &lt;user@mydomain.net&gt; Message-ID: &lt;56F2AAD2.7030408@mydomain.net&gt; Date: Wed, 23 Mar 2016 15:40:18 +0100 MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit Testmessage --===============7892775444970429949== Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="atach.txt" Textfile attachment --===============7892775444970429949==-- </code></pre> <p>And this is what Thunderbird gives me (and what I want):</p> <pre><code>To: foo@bar.com From: User &lt;user@mydomain.net&gt; Message-ID: &lt;56F2AAD2.7030408@mydomain.net&gt; Date: Wed, 23 Mar 2016 15:40:18 +0100 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------010607020403070301060303" This is a multi-part message in MIME format. --------------010607020403070301060303 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit Testmessage --------------010607020403070301060303 Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="atach.txt" Textfile attachment --------------010607020403070301060303-- </code></pre>
<p>I have just tried out your code and it works perfect I will provide the working solution. I think it is better to import the needed module classes as sole classes for use in the code. As shown here</p> <pre><code>import sys import mailbox import email from email.mime.multipart import MIMEMultipart from email.mime.message import MIMEMessage from email.mime.text import MIMEText message = mailbox.email.message_from_file(sys.stdin) maildir = mailbox.Maildir('./mail',create=True) new_msg = MIMEMultipart('related') old_msg = MIMEMessage(message) new_msg.attach(old_msg) att_msg = MIMEText("Textfile attachment") att_msg.add_header('Content-Disposition', 'attachment',filename='atach.txt') new_msg.attach(att_msg) maildir.add(new_msg) </code></pre> <p>I have also passed an extra keyword arg to create the mailbox if it does not exist. <strong>create=True</strong>. </p> <p>running the above and checking the mail Dir gives me the following I hope that is what you desire.</p> <pre><code>Content-Type: multipart/related; boundary="===============2731426334901210480==" MIME-Version: 1.0 --===============2731426334901210480== Content-Type: message/rfc822 MIME-Version: 1.0 Hello trial 2 --===============2731426334901210480== Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="atach.txt" Textfile attachment --===============2731426334901210480==-- </code></pre>
python|email|attachment|mime|multipart
1
1,908,212
15,144,846
Errno 10055 cannot connect in Python network related code on Windows
<p>I am new to creating networks, and relatively new to python. I recently purchased a second computer to run some python programs. That second computer enters data into a mysql database housed on my main computer.</p> <p>I am getting a lot of 10055 errors. Sometimes from selenium/urllib, sometimes from trying to connect to the mysql database. The errors either provide:</p> <p>Selenium - Errno 10055. An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full</p> <p>MySQL - Can't connect to MySQL server on IP (10055)</p> <p>I have searched for hours for a solution to this problem, but cant find one that works. Any ideas?</p> <p>I am running windows 7, on a pretty powerful computer. I really doubt this is a memory problem.</p> <p>one of the pieces of code that is causing problems is the following (I am getting the can't connect to mysql server) - it only gives problems sometimes:</p> <pre><code> def connect_to_database(schema_name): import MySQLdb import socket counter = 0 #try 100 times until a connection is made while counter &lt;= 100: try: #gets ip of host comp ip = socket.gethostbyname('PC NAME') conn = MySQLdb.connect(ip, "username", "pw", schema_name) c = conn.cursor() conn.set_character_set('utf8') c.execute('SET NAMES utf8;') c.execute('SET CHARACTER SET utf8;') c.execute('SET character_set_connection=utf8;') break except Exception, err: print traceback.format_exc() try: #if failure, use different ip, so far i have only seen 2 ip's for the network. if socket.gethostbyname(socket.gethostname()) == '10.0.0.13': ip = '10.0.0.14' else: ip = '10.0.0.13' conn = MySQLdb.connect(ip, "username", "pw", schema_name) c = conn.cursor() conn.set_character_set('utf8') c.execute('SET NAMES utf8;') c.execute('SET CHARACTER SET utf8;') c.execute('SET character_set_connection=utf8;') break except Exception, err: print traceback.format_exc() counter = counter + 1 return c, conn </code></pre>
<p>I think I have a solution. More testing will confirm. I increased the number of empheral ports on my windows7 machine to 65,000. See below for instructions.</p> <p><a href="https://stackoverflow.com/questions/7006939/how-to-change-view-ephemeral-port-range-in-windows-machines">how to change/view ephemeral port range in windows machines</a></p>
python|windows|networking
0
1,908,213
15,128,411
Python version in terminal after download Python for OSX
<p>I downloaded and successfully installed Python 3.3 for OSX. After executing "python" in terminal it opened the python terminal window, stating: "Python 2.7.2 (default, June 20 2012...)</p> <p>Is there another update I need to do?</p> <p>Thanks!</p>
<p>python3 should start the correct version for you.</p>
python-3.x
1
1,908,214
46,489,888
Using 2 levels of XML to find node and add string
<p>I have a plist i have parsed with lxml. Thanks to help from users here I have a full set of items i want to add, in the correct format, and can add them in. The trouble I have now is using 2 different levels of the xml file to select where to put it. If I have the following how can i be sure to insert my text over "WUT" in the set that uses both "Notes" and "13", and not in "Books" and "13"? Or the other way around?</p> <pre><code>&lt;root&gt; &lt;key&gt;Title&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Set&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Notes&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Tester&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;13&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Param&lt;/key&gt; &lt;array&gt; &lt;string&gt;WUT&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;key&gt;18&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Param&lt;/key&gt; &lt;array&gt; &lt;string&gt;WUT&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;dict&gt; &lt;key&gt;Books&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Tester&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;13&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Param&lt;/key&gt; &lt;array&gt; &lt;string&gt;WUT&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/root&gt; </code></pre> <p>So ideally my new plist would look like:</p> <pre><code>&lt;root&gt; &lt;key&gt;Title&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Set&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Notes&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Tester&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;13&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Param&lt;/key&gt; &lt;array&gt; &lt;string&gt;1&lt;/string&gt; &lt;string&gt;2&lt;/string&gt; &lt;string&gt;3&lt;/string&gt; &lt;string&gt;4&lt;/string&gt; &lt;string&gt;5&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;key&gt;18&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Param&lt;/key&gt; &lt;array&gt; &lt;string&gt;WUT&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;dict&gt; &lt;key&gt;Books&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Tester&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;13&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Param&lt;/key&gt; &lt;array&gt; &lt;string&gt;WUT&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/root&gt; </code></pre> <p>I have tried using xpath and running. </p> <pre><code>for plist_title in tree.xpath('//dict[key="Notes"][1]') for plist_tester in plist_title.xpath('//dict[key="13"][1]') plist_tester.insert(1,myData) </code></pre> <p>but the data only gets inserted after the last "13" and not the one I would like to define it to. </p>
<p>There is a good library for parsing XMLs in python called BeautifulSoup. Check the following links out.</p> <ul> <li><a href="https://stackoverflow.com/questions/4071696/python-beautifulsoup-xml-parsing">Python BeautifulSoup XML Parsing</a></li> <li><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow noreferrer">https://www.crummy.com/software/BeautifulSoup/bs4/doc/</a></li> </ul> <p>I am sure this is not the answer you wanted, but sometimes it's better to teach a man to fish.</p>
python|xml|xpath|lxml|plist
1
1,908,215
70,536,259
How do you know if a Pytorch Save contains a model and/or just the weights?
<p>I'm fairly new to pytorch and this might be a version issue, but I see torch.load and torch.load_state_dict used, but in both cases the file extension is commonly &quot;.pth&quot;</p> <p>Models that I have created, I can Save and Load them via torch.Save and torch.Load and call model.eval()</p> <p>I have another model file that I'm fairly sure is just the state dictionary, as model.eval() fails after a load.</p> <p>How would I inspect the file and know that one has a full model in it?</p> <p>Thanks much.</p>
<p>As far as I know there isn't a foolproof way to figure this out. <code>torch.save</code> uses Python's pickle under the hood (ref: <a href="https://pytorch.org/docs/stable/notes/serialization.html#saving-loading-tensors" rel="nofollow noreferrer">Pytorch docs</a>), so users can save arbitrary Python objects. For example, the following code wraps the state dicts in a dictionary:</p> <pre><code># example from https://github.com/lucidrains/lightweight-gan/blob/fce20938562a0cc289c915f7317722a8241abd37/lightweight_gan/lightweight_gan.py#L1437 save_data = { 'GAN': self.GAN.state_dict(), 'version': __version__, 'G_scaler': self.G_scaler.state_dict(), 'D_scaler': self.D_scaler.state_dict() } torch.save(save_data, self.model_name(num)) </code></pre> <p>If it helps, state dicts themselves are <code>OrderedDict</code> objects. If <code>isinstance(model, collections.OrderedDict)</code> returns True, you can be fairly confident that <code>model</code> is a state dict. (Remember to <code>import collections</code>)</p> <p>Models themselves are subclasses of <code>torch.nn.Module</code>, so you can check if something is a model by verifying that <code>isinstance(model, torch.nn.Module)</code> returns True.</p>
pytorch
0
1,908,216
69,797,021
need to find the number of files in folders and sub folders except .dat files
<p>I need to find the number of files in folders and sub folders except .dat files, here is my code:</p> <pre><code>import os directoryPath = r'C:\Users\\vishns\Documents\Python_Code\Test_Folder' number_of_files = sum( len(files) for r, d, files in os.walk(directoryPath) ) print(number_of_files) </code></pre>
<p>Here is a solution:</p> <pre><code>import os nfiles = 0 ndat = 0 directory = &quot;C://Users//vishns//Documents//Python_Code//Test_Folder&quot; for root, dirs, files in os.walk(directory): for file in files: if file.endswith(&quot;.dat&quot;): ndat += 1 else: nfiles += 1 print('Number of dat files:{}'.format(ndat)) print('Number of relevant files:{}'.format(nfiles)) print('Number of total files:{}'.format(ndat+nfiles)) </code></pre>
python
0
1,908,217
73,016,787
Pandas: Swapping cells in excel
<p>I have data in excel (3 columns)</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>KLM: 123</td> <td>QRS: 345</td> <td>NOP: 356</td> </tr> <tr> <td>NOP: 454</td> <td>KLM: 123</td> <td>QRS: 564</td> </tr> <tr> <td>NOP: 65</td> <td>KLM: 423</td> <td>QRS: 642</td> </tr> <tr> <td>QRS: 54</td> <td>KLM: 523</td> <td>NOP: 325</td> </tr> <tr> <td>QRS: 234</td> <td>KLM: 123</td> <td>NOP: 56</td> </tr> <tr> <td>KLM: 234</td> <td>NOP: 5425</td> <td>QRS: 3425</td> </tr> </tbody> </table> </div> <p>I am trying to swap the value and get the results shown below. i.e. values starting with &quot;KLM&quot; in one column, &quot;QRS&quot; in second column, followed by &quot;NOP&quot; in third column.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>KLM: 123</td> <td>QRS: 345</td> <td>NOP: 356</td> </tr> <tr> <td>KLM: 123</td> <td>QRS: 564</td> <td>NOP: 454</td> </tr> <tr> <td>KLM: 423</td> <td>QRS: 642</td> <td>NOP: 65</td> </tr> <tr> <td>KLM: 523</td> <td>QRS: 54</td> <td>NOP: 325</td> </tr> <tr> <td>KLM: 123</td> <td>QRS: 234</td> <td>NOP: 56</td> </tr> <tr> <td>KLM: 234</td> <td>QRS: 3425</td> <td>NOP: 5425</td> </tr> </tbody> </table> </div> <p>any help using pandas or excel would be appreciable. Thanks in advance</p>
<p>Do with <code>np.sort</code> then pass to dataframe</p> <pre><code>import numpy as np out = pd.DataFrame(np.sort(df.values)).iloc[:,[0,2,1]] Out[346]: 0 2 1 0 KLM: 123 QRS: 345 NOP: 356 1 KLM: 123 QRS: 564 NOP: 454 2 KLM: 423 QRS: 642 NOP: 65 3 KLM: 523 QRS: 54 NOP: 325 4 KLM: 123 QRS: 234 NOP: 56 5 KLM: 234 QRS: 3425 NOP: 5425 </code></pre>
excel|pandas
3
1,908,218
73,074,234
env command not working with find command
<p>Im trying to write a script: <code>env PYTHONPATH=$PYTHONPATH: $Dir/scripts find * -name ‘*.py' -exec pylint (} \\; | grep . &amp;&amp; exit 1</code></p> <p>The code is finding all scripts in the root directory instead of using the environmental variables I set. Any help on writing this code to only look for files in the directory I set as a value in PYTHONPATH.</p>
<p><code>env PYTHONPATH=$PYTHONPATH: $Dir/scripts</code> isn't doing what you think it's doing. Including <code>$PYTHONPATH</code> includes the former value of <code>PYTHONPATH</code>, meaning whatever you have it already set to or a blank default. The space in your variable also makes it invalid, and instead interprets the <code>$Dir/scripts</code> as a new command. It looks like what you want would be <code>env PYTHONPATH=$Dir/scripts</code> — but there's actually an easier way.</p> <p>If you have <code>__init__.py</code> files in your directory, you can just do <code>pylint ./some-directory</code>. If you don't, you can use <code>xargs</code>: <code>find . -type f -name &quot;*.py&quot; | xargs pylint</code>. If you wanted to pass the directory instead of have it coded to <code>.</code> (your current calling directory) you could do that too:</p> <pre class="lang-bash prettyprint-override"><code># set directory to first argument dir=&quot;$1&quot; # check if &quot;dir&quot; was actually provided, if not, set to `.` if [ -z &quot;$dir&quot; ]; then dir=.; fi find &quot;$dir&quot; -type f -name &quot;*.py&quot; | xargs pylint </code></pre> <p>You could save that in a script or function and then call it either with a directory (like <code>run-pylint-on-everything.sh ~/foo/bar</code>, or not, in which case it would run starting from your current shell location.</p>
python|linux|shell
0
1,908,219
55,671,336
How do I create an object upon clicking a button in kivy?
<p>I have an object, "Streak" that I want to be able to create when a button is pressed. What I have are multiple TextInputs and a button. I want the button to be able to get all the inputs and store them in the "Streak" object. How would I go about doing this? Here is the .kv code:</p> <pre><code>&lt;ScreenOne&gt;: name: "one" AnchorLayout: anchor_x: 'left' anchor_y: 'top' Button: on_release: app.root.current = "main" text: "Back" size: 50, 25 size_hint: None, None font_size: 18 GridLayout: cols:1 rows:6 Label: text: "Action" font_size: 18 size: 600, 50 size_hint: None, None TextInput: id: action_entry multiline: False size: 600, 28 size_hint: None, None Label: text: "Streak #" size: 600, 50 size_hint: None, None TextInput: id: streak_entry multiline: False size_hint: None, None size: 600, 28 Label: size: 600, 50 size_hint: None, None text: "Due every" GridLayout: cols:3 rows:2 Label: text: "Day(s)" size_hint: None, None font_size: 18 Label: text: "Hour(s)" size_hint: None, None font_size: 18 Label: text: "Minute(s)" size_hint: None, None font_size: 18 TextInput: id: day_entry multiline: False size_hint: None, None size: 200, 28 TextInput: id: hour_entry multiline: False size_hint: None, None size: 200, 28 TextInput: id: minute_entry multiline: False size_hint: None, None size: 200, 28 AnchorLayout: anchor_x: "right" anchor_y: "bottom" Button: text: "Add" size: 50, 25 size_hint: None, None font_size: 18 on_press: Streak.create(instance) </code></pre> <p>Here is the .py code:</p> <pre><code>class Streak(): def __init__(self, action, action_num, day, hour, minute): self.action = action self.action_num = action_num self.day = day self.hour = hour self.minute = minute class MainScreen(Screen): pass class ScreenOne(Screen): pass class ScreenManagement(ScreenManager): pass presentation = Builder.load_file("StreakStar.kv") class MainApp(App): def build(self): # build() returns an instance return presentation def create(self, instance): streak = Streak(action_entry.text, streak_entry.text, day_entry.text, hour_entry.text, minute_entry.text) if __name__ == '__main__': MainApp().run() </code></pre> <p>When I press the button I get a NameError: name 'Streak' is not definded</p>
<p>All of the ids are already stored in the <code>ids</code> library - assuming you want to use this variable as a string you could just concatenate the ids you require.</p> <p>The reason why you're getting an error is because <code>streak</code> isn't previously defined in your function. </p> <pre><code>def create(self): streak = "" streak = self.ids.action_entry.text +", "+ self.ids.streak_entry.text +", "+ self.ids.day_entry.text.... </code></pre> <p>Will give you a string of these <code>ids</code></p>
python|kivy
0
1,908,220
55,956,248
How to intercept a mouse signal in a QComboBox
<p>I have a custom combo box placed on a QDialog widget, and I can not catch any of the mouse signals. I sub classed QComboBox to intercept two signals not provided by QComboBox: LostFocusEvent and mouseDobleClickEvent. LostFocusEvent works well but the combo is not firing the mouse events. I need three signals on the combo box and only one suitable is provided.</p> <p>I tried to set combo.grabMouse(), disregarding the documentation warnings, and the combo.doubleClicked start working, but all other widgets connected through signals start behaving erratically. Also tried combo.view().doubleClick.connect with similar results. Also I tried other mouse events with similar results (Press- Release- etc) Finally, I tried to to use event instead of QMouseEvent in the comboBox sub class, but it's intercepted by the focusOutEvent slot. Mouse event work on QPushButtons including double click on QTableView widgets Using Windows 8 Python 3.7 PyQt5.</p> <pre><code>`class Agreement(QDialog): def __init__(self,db, address, parent=None): super().__init__(parent= None) self.parent = parent ....................................... def setUi(self): ..................................... self.comboSupplier = ComboFocus.FocusCombo(self) self.comboSupplier.setMaximumSize(220,30) self.comboSupplier.setEditable(True) #self.comboSupplier.grabMouse() self.comboSupplier.activated.connect(self.supplierChange) self.comboSupplier.focusLost.connect(self.supplierFocusLost) self.comboSupplier.doubleClicked.connect(self.editContact) ........................................... def supplierChange(self): try: row = self.comboSupplier.currentIndex() idx = self.comboSupplier.model().index(row,0) self.supplierId = self.comboSupplier.model().data(idx) self.agreementTitle[0] = self.comboSupplier.currentText() self.setAgreementTitle() self.okToSave[2] = int(self.supplierId) self.okSaving() except TypeError as err: print('supplierChange' + type(err).__name__ + ' ' + err.args[0]) @pyqtSlot() def editContact(self): try: c = Contacts(self.db,self.comboSupplier.currentText(), APM.OPEN_EDIT_ONE, self.supplierId,parent=self) c.show() c.exec() except Exception as err: print(type(err).__name__, err-args) @pyqtSlot(ComboFocus.FocusCombo) def supplierFocusLost(self, combo): try: self.setFocusPolicy(Qt.NoFocus) name = combo.currentText() if combo.findText(name) &gt; -1: return ........................................ class FocusCombo(QComboBox): focusLost = pyqtSignal(QComboBox) focusGot = pyqtSignal(QComboBox) doubleClicked = pyqtSignal(QComboBox) def __init__(self, parent = None): super().__init__(parent) self.parent = parent def mouseDoubleClickEvent(self,event=QMouseEvent.MouseButtonDblClick): print("double click detected") self.doubleClicked.emit(self) def focusOutEvent(self, event): if event.gotFocus(): self.focusGot.emit(self) elif event.lostFocus(): self.focusLost.emit(self) if __name__ == '__main__': app = QApplication(sys.argv) cb = FocusCombo() cb.show() app.exec_() sys.exit(app.exec_()) </code></pre> <p>I'd like to double click on the comboBox to open a widget to edit the contact attributes on the fly.</p>
<p>When you set QLineEdit to editable, a QLineEdit is added, so to track your events you must use an eventFilter:</p> <pre class="lang-py prettyprint-override"><code>from PyQt5 import QtCore, QtGui, QtWidgets class FocusCombo(QtWidgets.QComboBox): focusLost = QtCore.pyqtSignal(QtWidgets.QComboBox) focusGot = QtCore.pyqtSignal(QtWidgets.QComboBox) doubleClicked = QtCore.pyqtSignal(QtWidgets.QComboBox) def setEditable(self, editable): super(FocusCombo, self).setEditable(editable) if self.lineEdit() is not None: self.lineEdit().installEventFilter(self) def eventFilter(self, obj, event): if obj is self.lineEdit(): if event.type() == QtCore.QEvent.MouseButtonDblClick: self.doubleClicked.emit(self) """elif event.type() == QtCore.QEvent.MouseButtonPress: print("press") elif event.type() == QtCore.QEvent.MouseButtonRelease: print("release")""" return super(FocusCombo, self).eventFilter(obj, event) def mouseDoubleClickEvent(self,event): print("double click detected") self.doubleClicked.emit(self) super(FocusCombo, self).mouseDoubleClickEvent(event) def focusOutEvent(self, event): if event.gotFocus(): self.focusGot.emit(self) elif event.lostFocus(): self.focusLost.emit(self) super(FocusCombo, self).focusOutEvent(event) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) cb = FocusCombo() cb.addItems(list("abcdef")) cb.setEditable(True) cb.doubleClicked.connect(print) cb.show() sys.exit(app.exec_()) </code></pre>
python|python-3.x|pyqt|pyqt5|qcombobox
0
1,908,221
55,771,158
Is possible to have the console active only on certain times after compiling the py to exe using pyinstaller or anything else?
<p>I’m building a program in python that will copy large files using robocopy. Since the gui freezes while the copy is done i only have two options: 1. Learn how to do multithreading and design the gui to show the progress and not freeze. 2. Keep the console on after compiling with pyinstaller as an alternative to show robocopy progress while the gui freezes.</p> <p>I am open to doing multithreading but i’m a beginner and is pretty hard to understand how to make another subprocess for robocopy and from there extract the progress into a label from gui. The option i thought about is to have the cmd console active only while the copy is done. Is it possible? The scenario will be like this:</p> <ol> <li>Open the program (the console will be hidden)</li> <li>Press the copy button (console pops up and shows the copy progress while the gui freezes)</li> <li>After the copy is done hide the console again</li> </ol> <p>As i said above. I’m not totally excluding adding multithreading but for that i will need some help.</p> <p>Thanks!</p>
<p>Please try this code, should be working, please let me know if something wrong:</p> <pre><code>import tkinter as tk import os import subprocess import threading main = tk.Tk() main.title('Title') frame_main = tk.Frame(main) frame_main.grid(columnspan=1) src = 'D:/path/to/the/folder' dest = 'D:/path/to/the/folder2' selection_platf = len(os.name) def copy_build_button(): if selection_platf &lt; 11: subprocess.call(["robocopy", src, dest, r"/XF", 'BT V_SyncPackage.zip', "/S"]) else: #for linux subprocess.call(["robocopy", src, dest, "/S"]) def copy_thread(): thread_1 = threading.Thread(target=copy_build_button) thread_1.start() button_main1 = tk.Button(frame_main, text="copy_build_button", width=50, height=5, fg="green", command=copy_thread) button_main1.grid(column=0, sticky='N'+'S'+'E'+'W') main.mainloop() </code></pre>
python|cmd|pyinstaller
0
1,908,222
73,512,438
Selenium will not open site
<p>I am trying to have selenium open a website in Microsoft Edge, and it will not open. The code I am using is</p> <pre><code>from selenium import webdriver # create webdriver object driver = webdriver.ChromiumEdge() # get goodle.com driver.get(&quot;https://google.com&quot;) </code></pre> <p>It returns this error:</p> <pre><code>File &quot;c:\Users\Henry\OneDrive\Desktop\Genetic programming\starthere.py&quot;, line 21, in &lt;module&gt; driver = webdriver.ChromiumEdge() File &quot;C:\Users\Henry\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\edge\webdriver.py&quot;, line 61, in __init__ super().__init__(DesiredCapabilities.EDGE['browserName'], &quot;ms&quot;, File &quot;C:\Users\Henry\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\chromium\webdriver.py&quot;, line 89, in __init__ self.service.start() File &quot;C:\Users\Henry\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\common\service.py&quot;, line 81, in start raise WebDriverException( selenium.common.exceptions.WebDriverException: Message: 'msedgedriver' executable needs to be in PATH. Please download from https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ </code></pre> <p>I did add the Webdriver exe file to the path, but it still gives this error.</p>
<p>Instead of adding it to the <code>PATH</code> try this way pointing directly to the executable:</p> <pre class="lang-py prettyprint-override"><code>from selenium import webdriver from selenium.webdriver.edge.service import Service s = Service(executable_path=r'C:\path\to\msedgedriver.exe') driver = webdriver.Edge(service=s) </code></pre>
python|selenium|selenium-webdriver|microsoft-edge
1
1,908,223
49,889,113
converting spacy token vectors into text
<p>I am using spacy to create vectors of a sentence. If the sentence is 'I am working', it gives me a vector of shape (3, 300). Is there any way to get back the text in the sentence using those vectors?</p> <p>Thank in advance, Harathi</p>
<p>Actually you can get directly the string from the doc object with .orth_ method, which returns a string representation of the token rather than a SpaCy token object</p> <pre><code>import en_core_web_sm nlp = en_core_web_sm.load() tokenizer = nlp.Defaults.create_tokenizer(nlp) text = 'I am working' tokens = [token.orth_ for token in tokenizer(text)] print(tokens) ['I', 'am', 'working'] </code></pre>
python|vector|text|nlp|spacy
2
1,908,224
66,575,172
How to plot a histogram of a single dataframe column and exclude 0s
<p>I have a huge dataframe that looks like this:</p> <pre><code> Date value 1 2022-01-01 00:00:00 0.000 2 2022-01-01 01:00:00 0.000 3 2022-01-01 02:00:00 0.000 4 2022-01-01 08:00:00 0.058 5 2022-01-01 09:00:00 4.419 6 2022-01-01 10:00:00 14.142 </code></pre> <p>I want to only plot in a histogram the column 'value' but without the 0 values. How do I do that?</p> <p>I have tried :</p> <pre><code>plt.hist(df['value' &gt;0], bins=50) </code></pre> <pre><code>plt.hist(df['value' =! 0], bins=50) </code></pre> <p>but no luck. Any ideas?</p> <p>Many thanks</p>
<p>There's a syntax error with <code>df['value' &gt; 0]</code> -- needs to be either <code>df[df['value'] &gt; 0]</code> or <code>df[df.value &gt; 0]</code>.</p> <p>The idea is that you create a boolean index with <code>df.value</code>:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df.value &gt; 0 0 False 1 True 2 False 3 True 4 True 5 True Name: value, dtype: bool </code></pre> <p>And then use that index on <code>df</code> to retrieve the <code>True</code> indexes:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df[df.value &gt; 0] date value 1 2022/01/01 0.100 3 2022/01/01 0.058 4 2022/01/01 4.419 5 2022/01/01 14.142 </code></pre> <p>On the plotting side, you can also plot directly with pandas:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df[df.value &gt; 0].plot.hist(bins=50) </code></pre>
python|pandas|dataframe|matplotlib|histogram
1
1,908,225
66,387,083
Installing TensorFlow Profiler for Dummies
<p>I am trying to follow this <a href="https://www.tensorflow.org/guide/profiler" rel="nofollow noreferrer">guide</a> to install the TensorFlow Profiler to better understand why my recently installed Keras does run on the GPU, but hardly uses any ressources (and is really slow). However, I am unable to come to any results, since the guide does not provide me with sufficient information, since I am not a programmer by trade and obiously lack necessary knowledge.</p> <p>What have I tried so far? I use Anaconda and have a running version of python 3.7 installed. I also installed tensorflow and the necessary drivers and such so that tensorflow is able to access my GPUs. Following the linked guide, I downloaded the &quot;install_and_run.py&quot; and tried executing it using the conda prompt. I get asked to specify --envdir and --logdir. Where do I point these? Is the environment directory just the directory to my current conda environment? Since I tried pointing both envdir and logdir into that direction and ended up with the error that the command</p> <blockquote> <p>True&quot; is unknown and &quot;True' returned non-zero exit status 1.</p> </blockquote> <p>I could not come up with any solution for this. It should probably be mentioned that I have very little experience in using the conda prompt to run .py-files and usually only use it to install packages.</p> <p>I am also unsure what is meant by the subsequent steps that talk about the CUPTI path. The given path is no complete path as far as i know. Where am I supposed to look for it? Or am I meant to exectute some of this</p> <pre><code>/sbin/ldconfig -N -v $(sed 's/:/ /g' &lt;&lt;&lt; $LD_LIBRARY_PATH) | \ grep libcupti </code></pre> <p>as a command? I have tried running <code>/sbin/ldconfig -N -v $</code> but my system could not find the path (potentially because I started looking from the wrong directory?).</p> <p>Any help is much appreciated. Sorry for the potentially confusing post from a confused person.</p> <p>Thank you!</p>
<p>Tensorflow profiler is no longer bundled with Tensorboard. There is a <a href="https://www.tensorflow.org/tensorboard/tensorboard_profiling_keras" rel="nofollow noreferrer">tutorial</a> on how to install and run it, when fitting Keras model.</p> <p>The summary is:</p> <ol> <li>Inside your env run <code>pip install tensorboard_plugin_profile</code></li> <li>Declare a tensorboard callback as you normally would</li> </ol> <pre class="lang-py prettyprint-override"><code>tboard_callback = tf.keras.callbacks.TensorBoard(log_dir = logs, histogram_freq = 1, profile_batch = '500,520') </code></pre> <ol start="3"> <li>Fit your model (with declared tensorboard callback)</li> <li>On a separe terminal (with your env activated) run <code>tensorboard --logdir=path/to/logs</code></li> </ol> <p>The Profiler tab shown in the tutorial may not be visisble, but there should be a profile option available in the drop down menu on the top right corner.</p>
python|tensorflow|keras|anaconda|tensorboard
2
1,908,226
63,838,736
How to correct type errors with mypy library
<p>I check my code using <code>mypy</code>. I got these errors:</p> <ol> <li><p>I have an object <code>names: List[str]</code>, for <code>len(names)</code> I get</p> <p><code>Argument 1 to &quot;len&quot; has incompatible type &quot;Optional[List[str]]&quot;; expected &quot;Sized&quot;</code></p> <p>When I try to index like <code>names[i]</code> I get:</p> <p><code>Value of type &quot;Optional[List[str]]&quot; is not indexable</code></p> </li> <li><p>I have an object <code>matrix: List[List[int]]</code>, similarly <code>matrix[i][j]</code></p> <p><code>Value of type &quot;Optional[List[List[int]]]&quot; is not indexable</code></p> </li> <li><p>I have an object</p> <pre><code> def func() -&gt; Dict[str, List[str]] g = {&quot;1&quot;: [&quot;2&quot;], &quot;2&quot;: [&quot;3&quot;]} return g </code></pre> <p>annotated as <code>Dict[str, List[str]]</code>, I get an error:</p> <p><code>Incompatible return value type (got &quot;Dict[str, object]&quot;, expected &quot;Dict[str, List[str]]&quot;)</code></p> <p>I don't understand, why I got this type. If I change it to <code>Dict[str, object]</code>, I get another errors in my code like in 4.</p> </li> <li><p>When I try to use my object:</p> <pre><code> d: DefaultDict[str, List[str]] = defaultdict(list) for obj in g: d[obj].extend(g.get(obj)) </code></pre> <p>I get this error:</p> <p><code>Argument 1 to &quot;extend&quot; of &quot;list&quot; has incompatible type &quot;Optional[List[str]]&quot;; expected &quot;Iterable[str]&quot;</code></p> </li> </ol> <p>I am new in <code>python</code> and don't understand principles of working with <code>mypy</code>- how should I annotate types so as not to get similar errors?</p>
<p>In number 4. when you use <code>.get()</code> method the return type becomes optional i.e. if you were expecting to get <code>List[str]</code> it would be <code>Optional[list[str]]</code> this is equivalent to <code>[None, List[str]]</code>. To overcome this you could do following:-</p> <pre><code>if g.get(obj) is None: raise RunTimeError(&quot;Not found&quot;) </code></pre>
python
1
1,908,227
71,756,133
How to create a python program that run calling name instead of name.py from root terminal?
<p>If I have a <code>main.py</code> file in a folder, how can I create a command in my PC that, calling only main from any point in the terminal, makes my <code>main.py</code> file running? Thanks</p>
<p>You should add main.py to your PATH. What happens when you are running, for instance, <code>python</code> is that your terminal looks up the command <code>python</code> in PATH and runs the program that it is pointing to. You could see it as a kind of shortcut to the program Python.</p> <p>By adding your program to your PATH, you can tell the computer that if you type <code>helloworld</code> in your terminal, the terminal should run <code>/my/path/to/helloworld.py</code>.</p> <p>I don't know what OS you are on, so here are links for most common OS on how to add a PATH variable.</p> <p><a href="https://www.computerhope.com/issues/ch000549.htm" rel="nofollow noreferrer">Windows</a></p> <p><a href="https://linuxize.com/post/how-to-add-directory-to-path-in-linux/" rel="nofollow noreferrer">Linux</a></p> <p><a href="https://www.architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/" rel="nofollow noreferrer">Mac OSX</a></p>
python
2
1,908,228
71,504,847
Selecting all rows with the first 5 different values of a list
<p>I have a predefined list with 100 elements, whose values represent cluster labels. First, I would like to find the first 5 different cluster labels from the list. Then, I want to select all rows that have one of the five values as entry, and finally write their index and label into a new array.</p> <p>How do I have to adjust my code to achive that? I think I have to use a loop, but since I am new to python I dont know how to set it correctly.</p> <pre><code>list = np.array(list) new_array = [] for x in list: new_array.append(list[index, value]) print(new_array) </code></pre>
<p>You can use <code>np.unique</code> to get the unique values of a list:</p> <pre><code>first_vals = np.unique(list)[:5] new_array = [] for index, value in enumerate(list): if value in first_vals: new_array.append([index, value]) print(new_array) </code></pre> <p>Output:</p> <pre><code>[[0, 0], [1, 0], [2, 1], [3, 0], [4, 2], [5, 1], [6, 3], [10, 4], [11, 4], [12, 1], [14, 3], [15, 1], [16, 3], [17, 2], [18, 3]] </code></pre> <p>(Note: it's bad practice use names of Python builtins as variable names, e.g. <code>list</code></p>
python|numpy|cluster-analysis
1
1,908,229
5,401,118
Django messages being displayed twice
<p>I'm using Django's message framework, and I have a very odd problem where my messages are being displayed twice in the template, even though {{messages|length}} is 1</p> <p>My view</p> <pre><code>if request.method == 'POST': form = EditProfileForm(user=request.user, meta=meta, data=request.POST, files=request.FILES) if form.is_valid(): user = form.save() if 'uploaded_image' in request.FILES: #TODO limit image size, check mime type filename = request.FILES['uploaded_image'] destination = open('%s/%s' % (settings.FILE_UPLOAD_PATH, form.filename), 'wb+') for chunk in filename.chunks(): destination.write(chunk) destination.close() print 'adding success message' #this is printed once messages.success(request, 'Settings saved.') #this message is displayed twice #messages.add_message(request, messages.SUCCESS, 'Yup. Saved.') return HttpResponseRedirect(reverse('someview')) else: print form.errors messages.error(request, 'Error updating settings. See errors below.') </code></pre> <p>in my template:</p> <pre><code>{% block message%} {{message.count}} {% if messages %} {{messages|length}} {% for message in messages%} &lt;p class="{{message.tags}}"&gt;{{message}}&lt;/p&gt; {% endfor %} {% endif %} {% endblock %} </code></pre> <p>Any ideas?</p>
<p>Turns out this was a template inheritance issue. Double check and make sure you don't have the same block in two different templates.</p>
python|django
3
1,908,230
62,486,733
Python packaging with setuptools does not include my source code when installing
<p>I'm trying to make a python program into a package: This is my setup.py</p> <pre><code>from setuptools import setup, find_packages setup( name='scroll', version='2020.6.14', # package_dir={'': 'scroll'}, packages=find_packages(), install_requires=[ 'Click', ], entry_points=''' [console_scripts] scroll=scroll:scroll ''', # .... all other stuff ) </code></pre> <p>This is the module structure,</p> <pre><code>SCROLL - scroll/ | +--scroll.py - setup.py - MANIFEST.in - venv/ </code></pre> <p>When I run <code>python setup.py sdist</code>, a <code>tar.gz</code> file is created and when extracted, it contains the source code at <code>projects\SCROLL\dist\scroll-2020.6.14\dist_scroll-2020.6\scroll-2020.6.14\scroll</code></p> <p>But when I install the archive using <code>pip install ./dist/scroll-2020.6.14.tar.gz</code>, Running <code>scroll</code> produces an <code>ModuleNotFoundError: No module named 'scroll'</code> This is because during installation, the source code is not copied to <code>SCROLL\venv\lib\python3.8\site-packages\</code>.</p> <p>Copying the scroll folder manually to <code>site-packages</code> solves this error</p> <p>I have tried using <code>MANIFEST.in</code> file with contents below but the code is still not copied to <code>site-packages</code></p> <pre><code>include scroll recursive-include scroll *.py </code></pre>
<p>I solved this by packaging the module using <a href="https://pypi.org/project/flit/" rel="nofollow noreferrer">flit</a>. I just found out it can create scripts too after asking the question.</p> <p>For the how-to:</p> <p>Refer to <a href="https://setuptools.readthedocs.io/en/latest/setuptools.html#automatic-script-creation" rel="nofollow noreferrer">https://setuptools.readthedocs.io/en/latest/setuptools.html#automatic-script-creation</a></p>
python|pip|setuptools|python-packaging|python-click
0
1,908,231
62,826,533
Django website deployed on heroku does not work
<p>I created a django website and was trying to deploy it to heroku. I followed this tutorial and did everything he did but i'm getting these errors in the logs</p> <pre><code>2020-07-10T02:06:01.015381+00:00 heroku[router]: at=error code=H14 desc=&quot;No web processes running&quot; method=GET path=&quot;/&quot; host=website.herokuapp.com request_id=9efff235-77f8-41e8-bc9e-9f80bd2b6aa1 fwd=&quot;172.98.86.231&quot; dyno= connect= service= status=503 bytes= protocol=https 2020-07-10T02:06:01.743381+00:00 heroku[router]: at=error code=H14 desc=&quot;No web processes running&quot; method=GET path=&quot;/favicon.ico&quot; host=website.herokuapp.com request_id=bf2f44a0-8f5c-4e63-a1c9-e16a33761803 fwd=&quot;172.98.86.231&quot; dyno= connect= service= status=503 bytes= protocol=https </code></pre> <p>my procfile has these contents</p> <pre><code>web: gunicorn website.wsgi --log-file - </code></pre> <p>my requirements.txt includes these</p> <pre><code>asgiref==3.2.3 Django==2.1.7 pytz==2019.3 sqlparse==0.3.0 SQLAlchemy==1.3.9 psycopg2==2.8.4 Jinja2==2.10.3 gunicorn==20.0.4 </code></pre> <p>I used to get the same HTTP errors when running the site locally but the site used to render and work properly. I'm getting the same error in heroku but site is not working</p> <p>Can someone explain what these error means and how to fix them or you could also reply with a link to a video or documentation you used to deploy your website and worked</p>
<p>I figured it out. In my case I renamed the &quot;procfile&quot; to &quot;Procfile&quot; updated the contents of the procfile to</p> <pre><code>web: gunicorn website.wsgi:application --log-file - python manage.py collectstatic --noinput manage.py migrate </code></pre> <p>and this worked</p>
python|python-3.x|django|heroku|gunicorn
1
1,908,232
67,398,320
Show the user who was banned discord.py
<p>I have this code to ban spammers:</p> <pre><code>@bot.event async def on_message(message): counter = 0 with open(&quot;spam_detect.txt&quot;, &quot;r+&quot;) as file: for lines in file: if lines.strip(&quot;\n&quot;) == str(message.author.id): counter += 1 file.writelines(f&quot;{str(message.author.id)}\n&quot;) if counter &gt; 5: await message.guild.ban(message.author, reason=&quot;Spammer&quot;) await asyncio.sleep(5) await message.guild.unban(message.author) await message.channel.send(&quot;Banned for spam&quot;) print(&quot;banned&quot;) </code></pre> <p>The user gets softbanned, the messages get deleted, but i can only get it to say <code>Banned for spam</code>..and with the bot wiping everything that user did i cannot know who was banned and when. How can i get it to say <code>&lt;USER&gt; was banned for spam</code> ?</p>
<p>I generally don't recommend doing heavy stuff like this in an <code>on_message</code> event. I recommend using a cache, and add the user as usual.</p> <p>But to answer your question:</p> <pre><code>if counter &gt; 5: await message.guild.ban(message.author, reason=&quot;Spammer&quot;) await asyncio.sleep(5) await message.guild.unban(message.author) await message.channel.send(f&quot;Banned {message.author.name} for spam&quot;) print(&quot;banned&quot;) </code></pre> <p>I added <code>f&quot;Banned {message.author.name} for spam&quot;</code>. This shows the name from the user that was banned. If you want to get the whole name with discriminator, do <code>message.author</code> instead.</p>
python|discord|discord.py
0
1,908,233
67,506,062
Error when I run a python script in task scheduler
<p>I get an error when I run my python script in windows task scheduler. My script is taking some date from an excel file. And the error is &quot; No such file or directory&quot;. How I can fix it</p>
<p>The answer is in the error &quot; No such file or directory &quot;</p> <p>Triple check your locations in the python script by copy / pasting them and seeing if you can manually get there.</p>
python-3.x|task|windows-task-scheduler
0
1,908,234
64,550,375
Isolate strings from CSV and print them
<h2>Question:</h2> <p>This is a small part in a bigger project. I'd like to believe I'm good at understanding delimiters and CSVs but I don't know what to do or what to ask.</p> <p>Dumb question, how can I isolate the strings from this list and print them?</p> <pre><code>(0, 'img_10.jpg') (1, 'img_8.mp4') (2, 'img_31.mp4') (3, 'img_30.mp4') (4, 'img_9.mp4') (5, 'img_12.jpg') (6, 'img_20.mp4') (7, '.DS_Store') (8, 'img_21.mp4') (9, 'img_35.mp4') </code></pre> <h2>Desired output:</h2> <pre><code>'img_10.jpg' 'img_8.mp4' 'img_31.mp4' 'img_30.mp4' 'img_9.mp4' 'img_12.jpg' 'img_20.mp4' '.DS_Store' 'img_21.mp4' 'img_35.mp4' </code></pre> <h2>My script below:</h2> <pre><code>import glob, os import sys import csv folder_path = &quot;path&quot; list = os.listdir(folder_path) with open(&quot;files.txt&quot;, &quot;w&quot;, newline='\n', encoding='utf-8') as csvfile: i = 0 for file in enumerate(list): csvfile.write(str(file) + &quot;\n&quot;) print(file) </code></pre>
<p>Don't enummerate use list iterator When you enumerate the list it will give index and the element as tuple that's why you got <code>(i,element)</code> tuple. If you don't need indexes then you can only iterate the list elements.</p> <p><strong>Using <code>list</code> as a varaible name is not a good practice because it is a python keyword</strong></p> <pre><code>folder_path = &quot;path&quot; list_files = os.listdir(folder_path) with open(&quot;files.txt&quot;, &quot;w&quot;, newline='\n', encoding='utf-8') as csvfile: i = 0 for file in list_files: csvfile.write(str(file) + &quot;\n&quot;) print(file) </code></pre>
python|csv
1
1,908,235
70,311,260
How to send non-empty Origin header in POST request if running an app on localhost?
<p>I just upgraded to Django 4 and it includes <a href="https://code.djangoproject.com/ticket/16010" rel="nofollow noreferrer">the ticket 16010</a> with <a href="https://github.com/django/django/commit/2411b8b5eb65fe3d7bcc1ee1f59e2433520c7df6#diff-eaa105f5b436e20dd838c27c7a753ef4cf888edcc8f868c084600f6cb7343166R227" rel="nofollow noreferrer">csrf origin verification changes</a>.</p> <p>To my knowledge, if you are running an app on localhost, browsers won't send origin (they will <a href="https://stackoverflow.com/questions/42239643/when-do-browsers-send-the-origin-header-when-do-browsers-set-the-origin-to-null/42242802#42242802">send null</a>). So, whenever we run a Django app on localhost, we should expect a header <code>Origin: null</code> in POST requests.</p> <p>But with the recent change CSRF on localhost can't be validated because of another change - <code>CSRF_TRUSTED_ORIGINS</code> now need to have a scheme. <a href="https://docs.djangoproject.com/en/4.0/releases/4.0/#csrf-trusted-origins-changes-4-0" rel="nofollow noreferrer">release notes</a></p> <p>Is it possible to add a non-empty <code>Origin</code> header when POSTing from localhost?</p> <p>To be clear, this won't work</p> <pre><code>from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = default_headers + ('Access-Control-Allow-*',) CORS_ALLOWED_ORIGINS = [ &quot;http://localhost:8000&quot;, &quot;http://127.0.0.1:8000&quot;, ] CSRF_TRUSTED_ORIGINS = [ &quot;http://localhost:8000&quot;, &quot;http://127.0.0.1:8000&quot;, ] </code></pre> <pre><code>&lt;form method=&quot;post&quot;&gt; {% csrf_token %} &lt;/form&gt; </code></pre> <blockquote> <pre><code>Origin checking failed - null does not match any trusted origins. </code></pre> </blockquote> <p>Request headers</p> <pre><code>Host: localhost:8000 Origin: null </code></pre>
<p><code>Origin</code> will be <code>null</code> in many different cases. My problem was that I had</p> <pre><code>&lt;meta name=&quot;referrer&quot; content=&quot;no-referrer&quot;&gt; </code></pre> <p>in the base template.</p>
python|django
0
1,908,236
11,318,801
Python "push server" tcp client
<p>I am developing python service for xbmc and I am hopelessly stuck. XBMC has TCP API that communicates by JSON-RPC. XBMC has server TCP socket that is mainly design to recieve commands and respond, but if something happens in system it sends "Notification" to TCP. The problem is that I need to create TCP client that behaves like server therefore it is able to recieve this "Notification". Wherever I run <code>socket.recv(4096)</code> it waits for data and stucks my code, because I need to loop my code. Structure of code is basically like this:</p> <pre><code>import xbmc, xbmcgui, xbmcaddon class XPlayer(xbmc.Player) : def __init__ (self): xbmc.Player.__init__(self) def onPlayBackStarted(self): if xbmc.Player().isPlayingVideo(): doPlayBackStartedStuff() player=XPlayer() doStartupStuff() while (not xbmc.abortRequested): if xbmc.Player().isPlayingVideo(): doPlayingVideoStuff() else: doPlayingEverythingElseStuff() xbmc.sleep(500) # This loop is the most essential part of code if (xbmc.abortRequested): closeEverything() xbmc.log('Aborting...') </code></pre> <p>I tried everything threading, multiprocessing, blocking, non-blocking and nothing helped. Thanks,</p>
<p>You likely want select(), poll() or epoll(): <a href="http://docs.python.org/library/select.html" rel="nofollow">http://docs.python.org/library/select.html</a></p> <p>This Python pipe-progress-meter application uses select, as an example: <a href="http://stromberg.dnsalias.org/~strombrg/reblock.html" rel="nofollow">http://stromberg.dnsalias.org/~strombrg/reblock.html</a></p> <p>If you know what sort of delimiters are separating the various portions of the protocol, you may also find this useful, without a need for select or similar: <a href="http://stromberg.dnsalias.org/~strombrg/bufsock.html" rel="nofollow">http://stromberg.dnsalias.org/~strombrg/bufsock.html</a> It deals pretty gracefully with "read to the next null byte", "read a maximum of 100 bytes", etc.</p>
python|tcp|json-rpc
1
1,908,237
56,547,700
using "with" statement on class methods
<p>I'm required to use "with" on a method of an object and not on the object itself.</p> <p>Here is what I've already tried:</p> <pre><code>class LSTM: ... def run(self): def __enter__(self): do something return self def __exit__(self, type, value, tb): return self </code></pre> <p>An example of I want to use the function in main:</p> <pre><code>lstm = LSTM(...) with lstm.run(): ... </code></pre> <p>The error I get:</p> <pre><code>AttributeError: __enter__ </code></pre>
<p>The object <em>returned by your method</em> must be a context manager. Write your method as a generator and apply the <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" rel="nofollow noreferrer"><code>contextlib.contextmanager</code> decorator</a> to automatically create the proper helper object:</p> <pre><code>from contextlib import contextmanager class LSTM: @contextmanager def run(self): # prepare yield self # clean up </code></pre> <p>The object created by the decorator uses anything before the <code>yield</code> as <code>__enter__</code>, and anything after it as <code>__exit__</code>. Whatever is provided by <code>yield</code> is available for use in the <code>as</code> clause of the with statement. If an error terminates the context, it is raised at <code>yield</code>.</p>
python
3
1,908,238
56,464,316
How to Implement Scheduled Sampling in Keras?
<p>How can I implement the concept of Scheduled Sampling while training an LSTM Encoder-Decoder with teacher forcing in Keras?</p> <p>The source paper is here: <a href="https://arxiv.org/abs/1506.03099" rel="nofollow noreferrer">https://arxiv.org/abs/1506.03099</a></p> <p>From this post, I see that pure Tensor-flow supports this training helper:</p> <p><a href="https://stackoverflow.com/questions/43795423/scheduled-sampling-in-tensorflow">scheduled sampling in Tensorflow</a></p> <p><a href="https://www.tensorflow.org/api_docs/python/tf/contrib/seq2seq/ScheduledOutputTrainingHelper" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/contrib/seq2seq/ScheduledOutputTrainingHelper</a></p> <p>Is there a way to do this in Keras, maybe using a custom backend function?</p>
<p>Tensorflow contrib API is deprecated in Tensorflow2.x version. Few libraries of tf.contrib are moved to Tensorflow addons.</p> <p>Use <code>tfa.seq2seq.ScheduledOutputTrainingSampler</code></p> <pre><code>tfa.seq2seq.ScheduledOutputTrainingSampler( sampling_probability: tfa.types.TensorLike, time_major: bool = False, seed: Optional[int] = None, next_inputs_fn: Optional[Callable] = None ) </code></pre> <p>For more information on the library find <a href="https://www.tensorflow.org/addons/api_docs/python/tfa/seq2seq/ScheduledOutputTrainingSampler" rel="nofollow noreferrer">here</a></p>
tensorflow|keras|lstm
0
1,908,239
56,694,948
Compute the "best of 4" average per row
<p>How to find the average of the best <code>n</code> out of <code>N</code> cells for each row in a pandas dataframe?</p> <p>See the dataframe below, where I want to find the average of the best 4 scores out of 6 (n=4, N=6):</p> <pre><code>df = pd.DataFrame({'stu1' : [17,19,12,17,13,13], 'stu2' : [20,18,15,17,15,0], 'stu3' : [16,19,0,16,0,0], 'stu4' : [0,0,0,0,0,0], 'stu5' : [0,8,14,0,7,9]}, index = 'q1 q2 q3 q4 q5 q6'.split()).T </code></pre> <p>The average of the best 4 of <code>st1</code> would be based on the following values: 17, 19, 17, 13 and be 16.50. For <code>st3</code> is would be based on 16, 19, 0, 16, resulting in 12.75.</p> <p>How to calculate this for all rows?</p>
<p>You can sort your columns per row, then take the best 4 simply by slicing. From there, computing the mean is straightforward:</p> <pre><code>np.sort(df)[:,-4:].mean(axis=1) # array([16.5 , 17.5 , 12.75, 0. , 9.5 ]) pd.Series(np.sort(df)[:,-4:].mean(axis=1), index=df.index) stu1 16.50 stu2 17.50 stu3 12.75 stu4 0.00 stu5 9.50 dtype: float64 </code></pre>
python|pandas|dataframe
3
1,908,240
17,786,565
How do you change border line color of wx.StaticBox?
<p><img src="https://i.stack.imgur.com/nCOCZ.jpg" alt="enter image description here"></p> <p>As you can see from the above pic, the border line of wx.StaticBox is always grey on windows, is it possible to change it? I've searched quite a bit, but there doesn't seem to be any properties/attributes for the border line color, so how do you do it?</p> <p>Thanks a lot</p>
<p>This question had discussed in <a href="https://groups.google.com/forum/#!topic/wxpython-users/aZUo4R2rubY" rel="nofollow">wxPython google group</a>. "wx doesn't provide that level of control over the borders of widgets." Robin Dunn. You can try to create new class inherit it from <code>wx.StaticBox</code> and implement <code>OnPaint</code> method</p>
python|wxpython
2
1,908,241
61,165,627
Web scraping multiple similar pages
<p>I'm new to python web scraping, and I was attempting to take the addresses of different winmar locations in Canada, as well as put the results into a csv file. So far, the only way I have found to differentiate between the different locations' sites is by a code at the end of the address (numbers). The problem is that the results do not change as the program runs, and instead produces the results of the first location (305) when printing and into the csv file. Thanks for your time and consideration!</p> <p>Here's my code:</p> <pre class="lang-py prettyprint-override"><code>import csv import requests from bs4 import BeautifulSoup x = 0 numbers = ['305', '405', '306', '307', '308', '309', '4273'] f = csv.writer(open('Winmar_locations.csv', 'w')) f.writerow(['City:', 'Address:']) for links in numbers: for x in range(0, 6): url = 'https://www.winmar.ca/find-a-location/' + str(numbers[x]) r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") location_name = soup.find("div", attrs={"class": "title_block"}) location_name_items = location_name.find_all('h2') location_list = soup.find(class_='quick_info') location_list_items = location_list.find_all('p') for name in location_name_items: names = name.text names = names.replace('Location | ', '') for location in location_list_items: locations = location.text.strip() locations = locations.replace('24 Hour Emergency | (902) 679-1116','') print(names, locations) x = x+1 f.writerow([names, locations]) </code></pre>
<p>You had a few things wrong in your code and one thing about the website you are scraping</p> <ul> <li><p>First accessing the url like this <code>https://www.winmar.ca/find-a-location/308</code> will not change the location properly, it needs to be like this <code>https://www.winmar.ca/find-a-location/#308</code> with hashbang before the number.</p></li> <li><p>The website has duplicate html with the same classes, that means you nearly have all locations loaded all the time and they just choose which to show from their js code -bad practice ofcourse-, that makes your matcher always gets the same location, which explains why you always had the same location repeated.</p></li> <li><p>Lastly, you had a lot of unnecessary loops, you only need to loop over the numbers array and that's it.</p></li> </ul> <p>here is a modified version of your code</p> <pre class="lang-py prettyprint-override"><code>import csv import requests from bs4 import BeautifulSoup x = 0 numbers = ['305', '405', '306', '307', '308', '309', '4273'] names = [] locations = [] for x in range(0, 6): url = 'https://www.winmar.ca/find-a-location/#' + str(numbers[x]) print(f"pinging url {url}") r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") scope = soup.find(attrs={"data-id": str(numbers[x])}) location_name = scope.find("div", attrs={"class": "title_block"}) location_name_items = location_name.find_all('h2') location_list = scope.find(class_='quick_info') location_list_items = location_list.find_all('p') name = location_name.find_all("h2")[0].text print(name) names.append(name) for location in location_list_items: loc = location.text.strip() if '24 Hour Emergency' in loc: continue print(loc) locations.append(loc) x = x+1 </code></pre> <p>Notice the scoping I did</p> <pre><code> scope = soup.find(attrs={"data-id": str(numbers[x])}) </code></pre> <p>that makes your code immune to how much locations they have loaded in the html, you only targeting the scope with the location you want.</p> <p>this results in :</p> <pre><code>pinging url https://www.winmar.ca/find-a-location/#305 Location | Annapolis 70 Donald E Hiltz Connector Road Kentville, NS B4N 3V7 pinging url https://www.winmar.ca/find-a-location/#405 Location | Bridgewater 15585 Highway # 3 Hebbville, NS B4V 6X7 pinging url https://www.winmar.ca/find-a-location/#306 Location | Halifax 9 Isnor Dr Dartmouth, NS B3B 1M1 pinging url https://www.winmar.ca/find-a-location/#307 Location | New Glasgow 5074 Hwy. #4, RR #1 Westville, NS B0K 2A0 pinging url https://www.winmar.ca/find-a-location/#308 Location | Port Hawkesbury 8 Industrial Park Rd Lennox Passage, NS B0E 1V0 pinging url https://www.winmar.ca/find-a-location/#309 Location | Sydney 358 Keltic Drive Sydney River, NS B1R 1V7 </code></pre>
python|web-scraping|beautifulsoup
3
1,908,242
66,210,713
Why do i get the victory message right after choosing the first position
<p>I am trying to make a tic tac toe game in the terminal with python but i cant figure out why i get the victory message after choosing the first position can anybody else see why? i have made a for loop to check if i have won in rows or columns and made 2 if statements to check if i have won by diagonal</p> <pre><code>import random board = [[' ',' ',' '], [' ',' ',' '], [' ',' ',' ']] def checkwin(board): for row in board: if len(set(row)) == 1: return True elif board[0][0] == board[1][1] == board[2][2]: return True elif board[2][0] == board[1][1] == board[0][2]: return True else: return False def check_space_taken(board, number): if not choose_position(board, number) == ' ': return True else: return False def choose_position(board, number): if number &lt;= 3: board[0][number-1] = 'X' elif number &lt;= 6: board[1][number-4] = 'X' elif number &lt;= 9: board[2][number-7] = 'X' return board, number def computer_position(board, computer_number): computer_number = random.randint(0,9) if computer_number &lt;= 3: board[0][computer_number-1] = 'O' elif computer_number &lt;= 6: board[1][computer_number-4] = 'O' elif computer_number &lt;= 9: board[2][computer_number-7] = 'O' return board, computer_number Game_over = False while not Game_over: print(board) player_input = int(input('move to: ')) changed_board = choose_position(board, player_input) for line in changed_board: print(line) if checkwin(board): print('\n-----------------------Congrats you won-----------------------\n') Game_over = True </code></pre>
<p>In principle, your logic isn't incorrect, but you need to account for empty spaces. You also forgot to check columns:</p> <pre><code>def checkwin(board): for i in range(3): if board[i][0] != &quot; &quot; and board[i][0] == board[i][1] == board[i][2]: return True # found a winning row if board[0][i] != &quot; &quot; and board[0][i] == board[1][i] == board[2][i]: return True # found a winning column # winning diagonals? if board[1][1] != &quot; &quot; and board[0][0] == board[1][1] == board[2][2]: return True if board[1][1] != &quot; &quot; and board[2][0] == board[1][1] == board[0][2]: return True return False </code></pre>
python|python-3.x|tic-tac-toe
0
1,908,243
72,831,277
Value error where a 1D array was expected but got an array with shape (18632, 3)
<p>I am currently learning segmentation and was using this project <a href="https://github.com/jalajthanaki/Customer_segmentation" rel="nofollow noreferrer">https://github.com/jalajthanaki/Customer_segmentation</a> I found to learn but I reached the 99th cell and got a: <a href="https://i.stack.imgur.com/DM3uV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DM3uV.png" alt="enter image description here" /></a></p> <p>Here is the cell that is causing the problem:</p> <pre><code># sum of purchases / user &amp; order temp = df_cleaned.groupby(by=['CustomerID', 'InvoiceNo'], as_index=False) ['TotalPrice'].sum() basket_price = temp.rename(columns = {'TotalPrice':'Basket Price'}) # percentage of the price of the order / product category for i in range(5): col = 'categ_{}'.format(i) temp = df_cleaned.groupby(by=['CustomerID', 'InvoiceNo'], as_index=False)[col].sum() basket_price.loc[:, col] = temp # date of the order df_cleaned['InvoiceDate_int'] = df_cleaned['InvoiceDate'].astype('int64') temp = df_cleaned.groupby(by=['CustomerID', 'InvoiceNo'], as_index=False) ['InvoiceDate_int'].mean() df_cleaned.drop('InvoiceDate_int', axis = 1, inplace = True) basket_price.loc[:, 'InvoiceDate'] = pd.to_datetime(temp['InvoiceDate_int']) # selection of significant entries: basket_price = basket_price[basket_price['Basket Price'] &gt; 0] basket_price.sort_values('CustomerID', ascending = True)[:5] </code></pre> <p>The reason this confuses me is I am not sure what array is causing this problem and google has not helped me. I am absolutely new to this so any and all help is appreciated.</p>
<p>I think the problem is here:</p> <pre><code>for i in range(5): col = 'categ_{}'.format(i) temp = df_cleaned.groupby(by=['CustomerID', 'InvoiceNo'], as_index=False)[col].sum() basket_price.loc[:, col] = temp </code></pre> <p>Here <strong>temp</strong> supposed to be a <strong>three</strong> column dataframe &amp; here</p> <pre><code>basket_price.loc[:, col] = temp </code></pre> <p>You are assigning a <strong>three column dataframe</strong> to a column, which doesnt make sense.</p>
python|pandas|data-science
1
1,908,244
63,100,425
Is there way to change runtime type in Google Colab using python
<p><a href="https://i.stack.imgur.com/m1iwV.png" rel="nofollow noreferrer">Google Colab Runtime Selection</a></p> <p>Is there way to change runtime type in Google Colab using python code instead of using GUI as shown in the image.</p>
<p>You can read the notebook.ipynb into json string. Edit it, the overwrite it or create a new notebook file.</p> <p>It may be easier to download it, edit it with a text editor, then upload and open it again.</p> <p>For example, a notebook.ipynb with GPU runtime will look like this</p> <pre><code>{ &quot;nbformat&quot;: 4, &quot;nbformat_minor&quot;: 0, &quot;metadata&quot;: { &quot;colab&quot;: {...}, &quot;kernelspec&quot;: { &quot;name&quot;: &quot;python3&quot;, &quot;display_name&quot;: &quot;Python 3&quot; }, &quot;accelerator&quot;: &quot;GPU&quot; }, &quot;cells&quot;: [...] } </code></pre> <p>To change to Python 2.7, you change &quot;name&quot;:&quot;python2&quot;.</p> <p>To change to GPU runtime, you add &quot;accelerator&quot;: &quot;GPU&quot;.</p> <p>You can do this by hand (edit it in a text editor) or by Python (read json to dict, replace, overwrite, re-open).</p>
python|computer-science|google-colaboratory
1
1,908,245
62,392,885
How to use urllib3 to POST x-www-form-urlencoded data
<p>I am trying to use urllib3 in Python to POST x-www-form-urlencoded data to ServiceNow API. The usual curl command would look like this</p> <pre><code>curl -d "grant_type=password&amp;client_id=&lt;client_ID&gt;&amp;client_secret=&lt;client_Secret&gt;&amp;username=&lt;username&gt;&amp;password=&lt;password&gt;" https://host.service-now.com/oauth_token.do </code></pre> <p>So far, I have tried the following:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import urllib3 import urllib.parse http = urllib3.PoolManager() data = {"grant_type": "password", "client_id": "&lt;client_ID&gt;", "client_secret": "&lt;client_Secret&gt;", "username": "&lt;username&gt;", "password": "&lt;password&gt;"} data = urllib.parse.urlencode(data) headers = {'Content-Type': 'application/x-www-form-urlencoded'} accesTokenCreate = http.request('POST', "https://host.service-now.com/outh_token.do", headers = headers, fields= data) print(accesTokenCreate.data)</code></pre> </div> </div> </p> <p>However, it does not generate the result similar to curl command and gives errors like below:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>Traceback (most recent call last): File "/VisualStudio/Python/ServiceNow.py", line 18, in &lt;module&gt; accesTokenCreate = http.request('POST', "https://visierdev.service-now.com/outh_token.do", headers = headers, fields= data) File "/usr/local/homebrew/lib/python3.7/site-packages/urllib3/request.py", line 80, in request method, url, fields=fields, headers=headers, **urlopen_kw File "/usr/local/homebrew/lib/python3.7/site-packages/urllib3/request.py", line 157, in request_encode_body fields, boundary=multipart_boundary File "/usr/local/homebrew/lib/python3.7/site-packages/urllib3/filepost.py", line 78, in encode_multipart_formdata for field in iter_field_objects(fields): File "/usr/local/homebrew/lib/python3.7/site-packages/urllib3/filepost.py", line 42, in iter_field_objects yield RequestField.from_tuples(*field) TypeError: from_tuples() missing 1 required positional argument: 'value'</code></pre> </div> </div> </p> <p>Could someone please help me understand how to properly use urllib3 to post such data to the ServiceNow API?</p>
<p>According to the <a href="https://urllib3.readthedocs.io/en/latest/reference/urllib3.request.html" rel="nofollow noreferrer">urlllib3 documentation</a>, you are not using the <code>request()</code> method properly. Specifically, the <code>fields</code> parameter in your code is not a &quot;parameter of key/value strings AND key/filetuple&quot;. It's not suppose to be a URL-encoded string.</p> <p>To fix your code, simply change the <code>request</code> call's <code>fields</code> parameter to <code>body</code> as in:</p> <pre><code>accesTokenCreate = http.request( 'POST', &quot;https://host.service-now.com/outh_token.do&quot;, headers=headers, body=data) </code></pre> <p>Better yet, you can use the <code>request_encode_body()</code> function and pass in the fields directly without <code>urlencode</code>-ing it and let that function call <code>urllib.parse.urlencode()</code> for you (per the same documentation).</p>
python|api|servicenow|urllib3
1
1,908,246
62,150,433
Set timezone relative to user in django
<p>I made a web app using django, I'm not sure about the timezones and stuff. I have the user's preferred timezone, how can I set this timezone relative to that particular user? or will it automatically adjust to the user's timezone?</p>
<p>You can set the time zone that you want django to use in the settings.py</p> <p>eg settings.py</p> <pre><code>TIME_ZONE = 'Europe/Berlin' </code></pre>
python|django
-1
1,908,247
62,159,372
Problem importing modul OpenCV in Anaconda
<p>I am a beginner in terms of using python. Currently, I got python 3.7 and I am using anaconda as IDE. For my project, I need to detect the location and brightness of points/dots in an external imported picture. I figure I could use the modul OpenCV. Unfortunately, I am stuck right now with the problem to import the module cv2. I already successfully installed the package using </p> <pre><code>python -m pip install OpenCV-python </code></pre> <p>on command prompt. OpenCV Version which was installed is 4.2.0.34. While compiling the test script of OpenCV on Spyder</p> <pre><code>import cv2 print(cv2.__version__) </code></pre> <p>I got this message </p> <pre><code>"ImportError : DLL load failed : The Modul was not found." </code></pre> <p>Can somebody let me know please how to fix this problem? Is somehow the version of OpenCV I got not compatible with the Python version? I already watched and followed many tutorial videos on Youtube, but I couldn't find the solution. I tried to copy the cv2.pyd to the site-packages folder in </p> <pre><code>C:/user/Anaconda3/Lib/site-packages directory </code></pre> <p>still it didn't fix the problem...</p> <p>I would appreciate any answers and help I could get here. Thank you!</p>
<p>try installing it using these commands in the following order:</p> <pre><code>conda update anaconda-navigator conda update navigator-updater pip install opencv-python </code></pre> <p>It should work fine.</p>
python|module|opencv-python
1
1,908,248
35,355,689
Speeding Up Python 3.4 Code
<p>I have a problem where I need to find the next largest palindrome after a given number, however I am running into problems with the runtime being over 1 second. Is there any way I can speed this code up?</p> <pre><code>inp = input() if inp == '9' * len(inp): print('1' + ('0' * (len(inp) - 1)) + '1') #ran into a problem where 999 would give 9109 else: num = list(inp) oldnum = int(inp) if len(num) % 2 == 0: #for even length numbers for i in range(len(num) // 2): num[len(num) // 2 + i] = num[len(num) // 2 - 1 - i] if int("".join(num)) &gt; oldnum: print("".join(num)) else: #sometimes the palindrome was smaller eg: 1199 --&gt; 1111 num[len(num) // 2 - 1] = str(int(num[len(num) // 2 - 1]) + 1) num[len(num) // 2] = str(int(num[len(num) // 2]) + 1) print("".join(num)) else: #basically the same but for odd length numbers for i in range(len(num) // 2): num[len(num) // 2 + 1 + i] = num[len(num) // 2 - 1 - i] if int("".join(num)) &gt; oldnum: print("".join(num)) else: num[len(num) // 2] = str(int(num[len(num) // 2]) + 1) print("".join(num)) </code></pre>
<p>Here's how I would break it down,</p> <pre><code># simple version, easy to understand and fast enough # up to maybe a thousand digits def next_palindrome(n): """ Find the first integer p such that p &gt; n and p is palindromic """ # There are two forms of palindrome: # even number of digits, abccba # odd number of digits, abcba # Find abc s = str(n) abc = s[:(len(s) + 1) // 2] # There are six possibilites for p: # # abcpq &lt; abcba -&gt; p = abcba # abcpq &gt;= abcba -&gt; p = ab(c + 1)ba (with carries as needed) # abcpqr == 999999 -&gt; p = 1000001 *(num digits + 1) # # abcpqr &lt; abccba -&gt; p = abccba # abcpqr &gt;= abccba -&gt; p = ab(c+1)(c+1)ba (with carries as needed) # abcpq == 99999 -&gt; p = 100001 *(num digits + 1) # # *Note that the even-number-of-9s case is properly handled by # odd-digits-with-carry, but odd-number-of-9s needs special handling # # Make basis substrings cba = abc[::-1] ba = cba[1:] abc1 = str(int(abc) + 1) cba1 = abc1[::-1] ba1 = cba1[1:] # Assemble candidate values candidates = [ int(abc + ba), # abcba int(abc1 + ba1), # ab(c+1)ba int(abc + cba), # abccba int(abc1 + cba1), # ab(c+1)(c+1)ba int(abc1[:-1] + ba1) # handles odd-number-of-9s ] # Find the lowest candidate &gt; n return min(c for c in candidates if c &gt; n) def main(): while True: n = int(input("\nValue for n (or -1 to quit): ")) if n == -1: break else: print("Next palindrome is {}".format(next_palindrome(n))) if __name__ == "__main__": main() </code></pre> <p>which runs like</p> <pre><code>Value for n (or -1 to quit): 12301 Next palindrome is 12321 Value for n (or -1 to quit): 12340 Next palindrome is 12421 Value for n (or -1 to quit): 99999 Next palindrome is 100001 Value for n (or -1 to quit): 123001 Next palindrome is 123321 Value for n (or -1 to quit): 123400 Next palindrome is 124421 Value for n (or -1 to quit): 999999 Next palindrome is 1000001 Value for n (or -1 to quit): -1 </code></pre> <hr> <p><strong>Edit:</strong> I thought you were talking about maybe 100 digits. A million digits makes it worth spending more time minimizing the number of string operations and typecasts, like so:</p> <pre><code># Super-efficient version # for playing with million-digit palindromes def str_lt(x, y): """ Take two integer strings, `x` and `y`, return int(`x`) &lt; int(`y`) """ return len(x) &lt; len(y) or x &lt; y def str_add_1(n): """ Given an integer string `n`, return str(int(n) + 1) """ # find the first non-9 digit, starting from the right for i in range(len(n) - 1, -1, -1): if n[i] != '9': return n[:i] + str(int(n[i]) + 1) + '0' * (len(n) - i - 1) # string was all 9s - overflow return '1' + '0' * len(n) def next_palindrome(n): """ For non-negative integer `n` (as int or str) find the first integer p such that p &gt; n and p is palindromic Return str(p) Note: `n` must be well-formed, ie no leading 0s or non-digit characters """ # Make sure n is a string if not isinstance(n, str): n = str(n) # There are three forms of palindrome: # single digit, x (ab == '') # even number of digits, abba ( x == '') # odd number of digits, abxba ( x is single digit) # if len(n) == 1: # take care of single digit case return '11' if n == '9' else str_add_1(n) else: # There are six possibilites for p: # # (1) abqr &lt; abba -&gt; p = abba # (2) abqr &gt;= abba -&gt; p = a(b+1)(b+1)a (with carries as needed) # (3) abqr == 9999 -&gt; p = 10001 (carry results in overflow) # # (4) abxqr &lt; abxba -&gt; p = abxba # (5) abxqr &gt;= abxba -&gt; p = ab(x + 1)ba (with carries as needed) # (6) abxqr == 99999 -&gt; p = 100001 (carry results in overflow) # # Find ab, x, qr half = len(n) // 2 ab = n[ : half] x = n[ half:-half] # a 0- or 1-digit string qr = n[-half: ] ba = ab[::-1] if str_lt(qr, ba): # solve cases (1) and (4) return "".join([ab, x, ba]) if x == '9': # do manual carry from x ab1 = str_add_1(ab) ba1 = ab1[::-1] if len(ab1) &gt; len(ab): # carry results in overflow - case (6) return ab1 + ba1 else: # carry but no overflow - case (5) return "".join([ab1, '0', ba1]) if x: # no carry - case (5) return "".join([ab, str_add_1(x), ba]) # x == '' ab1 = str_add_1(ab) ba1 = ab1[::-1] if len(ab1) &gt; len(ab): # carry results in overflow - case (3) return ab1[:-1] + ba1 else: # no overflow - case (2) return ab1 + ba1 </code></pre> <p>On my machine, this finds a million-digit palindrome in less than 0.002 seconds (vs about 18.5 seconds for your code).</p>
python|performance|python-3.x
1
1,908,249
58,774,422
xlsxWriter issue regarding exporting dates as dates
<p>I have a list that includes dates in the following format: 11/22/2019. When I export this list to Excel, The Excel sheet recognizes these dates as General and therefor I cannot sort on these dates. Is there a way to make these dates recognizable by Excel as dates without using VBA?</p> <pre><code>import xlsxwriter workbook = xlsxwriter.Workbook('C:/test.xlsx') worksheet = workbook.add_worksheet("Table 1") dates_array = ["02/12/1999", "04/12/2009", "11/02/2019"] # Export dates_array to Excel file row = 0 column = 0 for item in dates_array: worksheet.write(row, column, item) row += 1 workbook.close() </code></pre>
<p>Strictly speaking those aren’t dates, they are just strings that look like dates. You need to convert them into dates, which in Python is generally a datetime object and in Excel is a real number + a format. </p> <p>XlsxWriter can convert Python datetime objects into Excel dates but it doesn’t automagically convert date-like strings to Excel dates. This is explained in more detail in the <a href="https://xlsxwriter.readthedocs.io/working_with_dates_and_time.html" rel="nofollow noreferrer">Working with Dates and Times</a> section of the XlsxWriter docs.</p> <p>Here is an example of how you could convert them:</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime import xlsxwriter workbook = xlsxwriter.Workbook('test.xlsx') worksheet = workbook.add_worksheet("Table 1") dates_array = ["02/12/1999", "04/12/2009", "11/02/2019"] date_format = workbook.add_format({'num_format': 'mm/dd/yyyy'}) # Set the column width for clarity. worksheet.set_column(0, 0, 20) row = 0 column = 0 for item in dates_array: date_time = datetime.strptime(item, '%m/%d/%Y') worksheet.write(row, column, date_time, date_format) row += 1 workbook.close() </code></pre> <p>Cell formatting, like the above, overrides column formatting so if you want to set a column format then you can omit the cell format, like this:</p> <pre class="lang-py prettyprint-override"><code>worksheet.set_column(0, 0, 20, date_format) row = 0 column = 0 for item in dates_array: date_time = datetime.strptime(item, '%m/%d/%Y') worksheet.write(row, column, date_time) row += 1 workbook.close() </code></pre> <p>Finally, if you want to also add vertical alignment to the column format you can add that to the date format, like this:</p> <pre class="lang-py prettyprint-override"><code>date_format = workbook.add_format({'num_format': 'mm/dd/yyyy', 'align': 'vcenter'}) </code></pre>
python|xlsxwriter
2
1,908,250
58,961,460
Rename Excel Tabs
<p>I am trying to rename tabs in an excel spreadsheet however it for one of the tabs it produces this name every time: '# of Behavioral Health Reps (5)1' Not sure why. There is only 1 of these matching tabs in each file. It also does not do it to any other tab. </p> <pre><code>text_search = pd.DataFrame( {'text_to_search': [ 'Retro' ,'Prior' ,'Concurr' ,'Rate' ,'claims pd' ,'health reps' ,'External'] , 'Replace': [ 'UR - Retrospective (1)' ,'UR - Prior Auth Req (2)' ,'UR - Concurrent Auth Req (2)' ,'Rate of First Level Appeals (3)' ,'Pct of Claims Paid (4)' ,'# of Behavioral Health Reps (5)' ,'External Appeals (9)']}) for mco in files: wb = xl.load_workbook(mco, data_only=True) for sheet in wb.sheetnames: for index, row in text_search[0:].iterrows(): #print(row['text_to_search'],row['Replace']) if re.search(row['text_to_search'], sheet, re.IGNORECASE): worksheet = wb[sheet] worksheet.title = row['Replace'] wb.save(mco) wb.close()``` </code></pre>
<p>If it looks like a mapping, then use a mapping:</p> <pre><code>l1 = [ 'Retro' ,'Prior' ,'Concurr' ,'Rate' ,'claims pd' ,'health reps' ,'External'] l2 =[ 'UR - Retrospective (1)' ,'UR - Prior Auth Req (2)' ,'UR - Concurrent Auth Req (2)' ,'Rate of First Level Appeals (3)' ,'Pct of Claims Paid (4)' ,'# of Behavioral Health Reps (5)' ,'External Appeals (9)'] mapping = {k:v for k,v in zip(l1, l2)} for ws in wb: if s.title in mapping: s.title = mapping[s.title] </code></pre> <p>If case is likely to an issue then convert to lowercase:</p> <pre><code>l1 = [v.lower() for v in l1] if s.title.lower() in mapping: </code></pre>
python|python-3.x|openpyxl
3
1,908,251
73,194,125
SELECT APDU command on Raspberry Pi pico with PN532 repond nothing
<p>I have Raspberry Pi pico with PN532 NFC/RFID breakout board.<br> connecting SPI interface and using circuitPython with Thonny IDE.<br> When I read UID from iso7816 smart card and it worked.<br> But sending SELECT APDU command to card respond nothing.<br> I am using this PN532 library <a href="https://github.com/adafruit/Adafruit_CircuitPython_PN532" rel="nofollow noreferrer">https://github.com/adafruit/Adafruit_CircuitPython_PN532</a><br></p> <p>Here is the Thonny Shell reponse -</p> <pre><code>Found PN532 with firmware version: 1.6&lt;br&gt; Waiting for RFID/NFC card to write to!&lt;br&gt; .....&lt;br&gt; Found card with UID: ['0x4', '0x28', '0x2c', '0x42', '0x5e', '0x69', '0x80']&lt;br&gt; Authenticating block 4 ...&lt;br&gt; [0, 164, 4, 0, 7, 160, 0, 0, 16, 0, 1, 18]&lt;br&gt; bytearray(b'%') </code></pre> <p>This is my codes</p> <pre><code>import board import busio from digitalio import DigitalInOut, Direction, Pull # Additional import needed for I2C/SPI # from digitalio import DigitalInOut # # NOTE: pick the import that matches the interface being used # # from adafruit_pn532.i2c import PN532_I2C from adafruit_pn532.spi import PN532_SPI from adafruit_pn532.adafruit_pn532 import COMMAND_TGGETDATA from adafruit_pn532.adafruit_pn532 import COMMAND_TGSETDATA # SPI connection: spi = busio.SPI(board.GP2, board.GP3, board.GP4) cs_pin = DigitalInOut(board.GP5) pn532 = PN532_SPI(spi, cs_pin, debug=False) def printString(data1): out = '' for x in range(len(data1)): out += '%02x' % data1[x] return out ic, ver, rev, support = pn532.firmware_version print(&quot;Found PN532 with firmware version: {0}.{1}&quot;.format(ver, rev)) # Configure PN532 to communicate with MiFare cards pn532.SAM_configuration() print(&quot;Waiting for RFID/NFC card to write to!&quot;) key = b&quot;\xFF\xFF\xFF\xFF\xFF\xFF&quot; while True: # Check if a card is available to read uid = pn532.read_passive_target(timeout=0.5) print(&quot;.&quot;, end=&quot;&quot;) # Try again if no card is available. if uid is not None: break print(&quot;&quot;) print(&quot;Found card with UID:&quot;, [hex(i) for i in uid]) print(&quot;Authenticating block 4 ...&quot;) def sendAPDU(apdu): sendData = pn532.call_function(COMMAND_TGSETDATA,params=apdu) def getAPDU(): result = pn532.call_function(COMMAND_TGGETDATA,255) print(result) apdu = printString(result)[2:] return apdu cardApdu = [0x00, 0xA4, 0x04, 0x00, 0x07, 0xA0, 0x00, 0x00, 0x10, 0x00, 0x01, 0x12] # select apdu command AID &quot;0xA0000010000112&quot; print(cardApdu) pos = sendAPDU(cardApdu) answerPos = getAPDU() print(answerPos) </code></pre>
<p>hey your command is correct is was just missing the LE at the end</p> <blockquote> <p>cardApdu = [0x00, 0xA4, 0x04, 0x00, 0x07, 0xA0, 0x00, 0x00, 0x10, 0x00, 0x01, 0x12]</p> </blockquote> <p>the command should be something like this.</p> <p><code>[0x00, 0xA4, 0x04, 0x00, 0x07, 0xA0, 0x00, 0x00, 0x10, 0x00, 0x01, 0x12, 0x00] </code></p>
python|raspberry-pi|nfc|apdu|adafruit-circuitpython
0
1,908,252
16,014,484
Generate possible combinations and get first 50 only
<p>I'm looking for a way to get the first 50 only of the possible combinations (20 in fixed length) with conditions but I can't seem to find what I'm looking for. I have an example below.</p> <pre><code>import itertools a = array([1,2,5]) b = array([8,9,10]) c = 0 if c == 1: x = a y = b else: x = b y = a mylist = list(itertools.product(x,y,x,y,x,y,x,y,x,y,x,y,x,y,x,y,x,y,x,y)) </code></pre> <p>My output would be:</p> <pre><code>(8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 1) (8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 2) (8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 5) (8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 2 8 1) (8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 2 8 2) (8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 2 8 5) . . </code></pre> <p>and so on..</p> <p>I already encountered memory error. I think this has too many combinations, so I just want to get the first 50 only. Is there a way to do it?</p> <p>Thanks in advance!</p>
<p>Stay with <code>itertools</code>, use <a href="http://docs.python.org/2/library/itertools.html#itertools.islice" rel="noreferrer"><code>islice</code></a>: </p> <pre><code>list(itertools.islice(itertools.product(x,y,x,y,x,y,x,y,x,y,x,y,x,y,x,y,x,y,x,y), 50)) </code></pre> <p>this takes the first 50 elements from the <code>product</code> and converts them into a list.</p>
python|combinations
6
1,908,253
15,789,343
Find all Occurences of Every Substring in String
<p>I am trying to find all occurrences of sub-strings in a main string (of all lengths). My function takes one string and then returns a dictionary of every sub-string (which occurs more than once, of course) and how many times it occurs (format of the dictionary: <code>{substring: # of occurrences, ...}</code>). I am using <code>collections.Counter(s)</code> to help me with it.</p> <p>Here is my function:</p> <pre><code>from collections import Counter def patternFind(s): patterns = {} for index in range(1, len(s)+1)[::-1]: d = nChunks(s, step=index) parts = dict(Counter(d)) patterns.update({elem: parts[elem] for elem in parts.keys() if parts[elem] &gt; 1}) return patterns def nChunks(iterable, start=0, step=1): return [iterable[i:i+step] for i in range(start, len(iterable), step)] </code></pre> <p>I have a string, <code>data</code> with about 2500 random letters (in a random order). However, there are 2 strings inserted into it (random points). Say this string is 'TEST'. <code>data.count('TEST')</code> returns 2. However, <code>patternFind(data)['TEST']</code> gives me a <code>KeyError</code>. Therefore, my program does not detect the two strings in it. </p> <p>What have I done wrong? Thanks!</p> <p>Edit: My method of creating testing-instances:</p> <pre><code>def createNewTest(): n = randint(500, 2500) x, y = randint(500, n), randint(500, n) s = '' for i in range(n): s += choice(uppercase) if i == x or i == y: s += "TEST" return s </code></pre>
<h2>Using Regular Expressions</h2> <p>Apart from the <code>count()</code> method you described, regex is an obvious alternative</p> <pre><code>import re needle = r'TEST' haystack = 'khjkzahklahjTESTkahklaghTESTjklajhkhzkhjkzahklahjTESTkahklagh' pattern = re.compile(needle) print len(re.findall(pattern, haystack)) </code></pre> <h2>Short Cut</h2> <p>If you need to build a dictionary of substrings, possibly you can do this with only subset of those strings. Assuming you know the <code>needle</code> you are looking for in the <code>data</code> then you only need the dictionary of substrings of <code>data</code> that are the same length of <code>needle</code>. This is very fast.</p> <pre><code>from collections import Counter needle = "TEST" def gen_sub(s, len_chunk): for start in range(0, len(s)-len_chunk+1): yield s[start:start+len_chunk] data = 'khjkzahklahjTESTkahklaghTESTjklajhkhzkhjkzahklahjTESTkahklaghTESz' parts = Counter([sub for sub in gen_sub(data, len(needle))]) print parts[needle] </code></pre> <h2>Brute Force: building dictionary of all substrings</h2> <p>If you need to have a count of all possible substrings, this works but it is very slow:</p> <pre><code>from collections import Counter def gen_sub(s): for start in range(0, len(s)): for end in range(start+1, len(s)+1): yield s[start:end] data = 'khjkzahklahjTESTkahklaghTESTjklajhkhz' parts = Counter([sub for sub in gen_sub(data)]) print parts['TEST'] </code></pre> <p>Substring generator adapted from this: <a href="https://stackoverflow.com/a/8305463/1290420">https://stackoverflow.com/a/8305463/1290420</a></p>
python|regex|string
4
1,908,254
25,355,072
Optimizing a prime number generator in Python
<p>I am looking for any suggestions on optimizing my prime number generator. Could you please include the correction and a little comment on why it will be faster in your response. </p> <pre><code>def primeList ( highestNumber ): """ This function takes a integer and returns a list of all primes less than or equal to that integer""" numbers = range( 2, highestNumber + 1 ) # creates an inclusive list of all numbers between 2 and highestNumber isPrime = [ True ] * len( numbers ) # each element corresponds to an element in numbers and keeps track of whether or not it is prime primes = [] # Where I'll build a list of prime numbers for i in range( len( numbers ) ): if ( isPrime[i] == True ): increment = numbers[i] position = i + increment primes.append( numbers[ i ] ) while ( position &lt; len( numbers )): # will only execute if the above if statement is true because position will still be greater than len( number ) isPrime[position] = False # Sets an element of isPrime to False if it is a multiple of a lower number position += increment return primes </code></pre>
<p>There's already a great discussion on various prime number generators here: <a href="https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python?rq=1">Fastest way to list all primes below N</a></p> <p>At that link is a Python script that you can use to compare your algorithm against several others.</p>
python|primes
2
1,908,255
70,912,103
How to convert a discrete array to continuous array using numpy?
<p>I am having an array a = np.array([3,5,7,8,10]). I want to convert this into b = ([0,0,1,0,1,0,1,1,0,1]). Array b is basically pointing to the position in the array a (converting it to 0 and 1). How can i do that ?. Intention is to use np.convolve to identify where there is a window of continuous numbers. I have tried to use b = np.digitize(c,a), where c = np.arange(1,10,1). But it gives error both a, b are not in same size.</p>
<p>You can try something like</p> <pre><code>a.sort() b = [1 if i in a else 0 for i in range(1,a[-1]+1)] </code></pre> <p>The output is <code>[0, 0, 1, 0, 1, 0, 1, 1, 0, 1]</code></p> <p>You can skip a.sort() if the array is already sorted.</p>
numpy
0
1,908,256
60,314,001
Connect as sys user using cx_Oracle in python to local database
<p>Trying to connect to Oracle database using Python cx_Oracle. In sqlplus I do use "sqlplus / as sysdba" as I connect to local database. I'm trying to use the same method without password in Python, but getting ORA-01017 or ORA-12541</p> <pre><code>tns_entry=cx_Oracle.makedsn('localhost',1521,'db1') &gt;&gt;&gt; conn = cx_Oracle.connect(mode = cx_Oracle.SYSDBA,dsn=tns_entry) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; cx_Oracle.DatabaseError: ORA-12541: TNS:no listener &gt;&gt;&gt; conn = cx_Oracle.connect("/",mode = cx_Oracle.SYSDBA,dsn=tns_entry) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; cx_Oracle.DatabaseError: ORA-12541: TNS:no listener &gt;&gt;&gt; conn = cx_Oracle.connect(mode = cx_Oracle.SYSDBA,dsn="TNS SERVICE") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; cx_Oracle.DatabaseError: ORA-01017: invalid username/password; logon denied </code></pre> <p>Where am I going wrong? Please provide your input. Thanks</p>
<p>For some reason my cx_Oracle.connect is not working with connect string. So added explicit os variable</p> <pre><code>os.environ["ORACLE_SID"] ='db1' connection = cx_Oracle.connect("/", mode = cx_Oracle.SYSDBA) cursor = connection.cursor() </code></pre>
python|cx-oracle
1
1,908,257
2,441,533
How to implement Comet server side with Python?
<p>I once tried to implement Comet in PHP. Soon, I found that PHP is not suitable for Comet, since each HTTP request will occupy one process/thread. As a result, it doesn't scale well. </p> <p>I just installed mod_python in my XAMPP. I thought it would be easy to implement Comet with Python asynchronous programming. But still cannot get a clue how to implement it.</p> <p>Is there any idea how to implement Comet in mod_python?</p>
<p>First of all, I'm not async expert at all, I just investigated the topic once. IMHO if you're using XAMPP then you're loosing the posibility of doing long polling because Apache uses thread/processes (depending on configuration) for each request.</p> <p>What you need, is non-blocking web server, like <a href="http://www.tornadoweb.org/" rel="noreferrer">Tornado</a>, that allows splitting requests into two parts, of which the second one is fired on some event, but meanwhile server can accept subsequent inbound requests.</p> <p>Example from <a href="http://www.tornadoweb.org/documentation" rel="noreferrer">Tornado documentation</a> /<a href="http://creativecommons.org/licenses/by/3.0/" rel="noreferrer">license</a>/:</p> <pre><code>class MainHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): http = tornado.httpclient.AsyncHTTPClient() http.fetch("http://friendfeed-api.com/v2/feed/bret", callback=self.async_callback(self.on_response)) def on_response(self, response): if response.error: raise tornado.web.HTTPError(500) json = tornado.escape.json_decode(response.body) self.write("Fetched " + str(len(json["entries"])) + " entries " "from the FriendFeed API") self.finish() </code></pre> <p>-- as far as I know this is not possible under Apache - in which fetch is regular part of request handler, which of course block until it's complete - so what you end with is frozen thread or process.</p> <p>Another famous library for doing non-blocking services in Python is <a href="http://twistedmatrix.com/trac/" rel="noreferrer">Twisted</a>, but I don't know much about it, only that it also is able to help you in handling a lot of connections with only one thread/process.</p>
python|comet
8
1,908,258
3,155,128
Python packages installation in Windows
<p>I recently began learning Python, and I am a bit confused about how packages are distributed and installed.</p> <p>I understand that the official way of installing packages is <strong>distutils</strong>: you download the source tarball, unpack it, and run: <code>python setup.py install</code>, then the module will automagically install itself</p> <p>I also know about <strong>setuptools</strong> which comes with <code>easy_install</code> helper script. It uses <strong>eggs</strong> for distribution, and from what I understand, is built on top of distutils and does the same thing as above, plus it takes care of any dependencies required, all fetched from PyPi</p> <p>Then there is also <strong>pip</strong>, which I'm still not sure how it differ from the others.</p> <p>Finally, as I am on a windows machine, a lot of packages also offers binary builds through a <strong>windows installer</strong>, especially the ones that requires compiling C/Fortran code, which otherwise would be a nightmare to manually compile on windows (assumes you have MSVC or MinGW/Cygwin dev environment with all necessary libraries setup.. nonetheless try to build numpy or scipy yourself and you will understand!)</p> <p>So can someone help me make sense of all this, and explain the differences, pros/cons of each method. I'd like to know how each keeps track of packages (Windows Registry, config files, ..). In particular, how would you manage all your third-party libraries (be able to list installed packages, disable/uninstall, etc..)</p>
<p>I use pip, and not on Windows, so I can't provide comparison with the Windows-installer option, just some information about pip:</p> <ul> <li>Pip is built on top of setuptools, and requires it to be installed.</li> <li>Pip is a replacement (improvement) for setuptools' easy_install. It does everything easy_install does, plus a lot more (make sure all desired distributions can be downloaded before actually installing any of them to avoid broken installs, list installed distributions and versions, uninstall, search PyPI, install from a requirements file listing multiple distributions and versions...).</li> <li>Pip currently does not support installing any form of precompiled or binary distributions, so any distributions with extensions requiring compilation can only be installed if you have the appropriate compiler available. Supporting installation from Windows binary installers is on the roadmap, but it's not clear when it will happen.</li> <li>Until recently, pip's Windows support was flaky and untested. Thanks to a lot of work from Dave Abrahams, pip trunk now passes all its tests on Windows (and there's a continuous integration server helping us ensure it stays that way), but a release has not yet been made including that work. So more reliable Windows support should be coming with the next release.</li> <li>All the standard Python package installation mechanisms store all metadata about installed distributions in a file or files next to the actual installed package(s). Distutils uses a distribution_name-X.X-pyX.X.egg-info file, pip uses a similarly-named directory with multiple metadata files in it. Easy_install puts all the installed Python code for a distribution inside its own zipfile or directory, and places an EGG-INFO directory inside that directory with metadata in it. If you import a Python package from the interactive prompt, check the value of package.__file__; you should find the metadata for that package's distribution nearby. </li> <li>Info about installed distributions is only stored in any kind of global registry by OS-specific packaging tools such as Windows installers, Apt, or RPM. The standard Python packaging tools don't modify or pay attention to these listings.</li> <li>Pip (or, in my opinion, any Python packaging tool) is best used with <a href="http://pypi.python.org/pypi/virtualenv" rel="noreferrer">virtualenv</a>, which allows you to create isolated per-project Python mini-environments into which you can install packages without affecting your overall system. Every new virtualenv automatically comes with pip installed in it.</li> </ul> <p>A couple other projects you may want to be aware of as well (yes, there's more!):</p> <ul> <li><a href="http://bitbucket.org/tarek/distribute" rel="noreferrer">distribute</a> is a fork of setuptools which has some additional bugfixes and features.</li> <li><a href="http://bitbucket.org/tarek/distutils2" rel="noreferrer">distutils2</a> is intended to be the "next generation" of Python packaging. It is (hopefully) adopting the best features of distutils/setuptools/distribute/pip. It is being developed independently and is not ready for use yet, but eventually should replace distutils in the Python standard library and become the de facto Python packaging solution.</li> </ul> <p>Hope all that helped clarify something! Good luck.</p>
python|pip|package|setuptools|distutils
11
1,908,259
67,953,915
extract information from p tag and insert into dict python with beautifulsoap
<p>I am trying to web scrape a government public page that contains speeches and biography of ministers. At the end I would like a dictionary like this:</p> <pre><code>data = { { &quot;time&quot;: &quot;18/05/2016&quot;, &quot;author_speech&quot;: name &quot;bio&quot;: [list, of, paragraphs_bio] &quot;speech&quot;: [list, of, paragraphs_speech] &quot;bio_link&quot;: &quot;url&quot; &quot;speech_link&quot;: &quot;url&quot; } { &quot;time&quot;: &quot;01/01/2011&quot;, &quot;author_speech&quot;: &quot;name&quot; &quot;bio&quot;: [list, of, paragraphs] &quot;speech&quot;: [list, of, paragraphs] &quot;bio_link&quot;: &quot;url&quot; &quot;speech_link&quot;: &quot;url&quot; } } </code></pre> <p>Page example</p> <pre><code>&lt;div class=&quot;item-page&quot;&gt; &lt;p&gt;&lt;strong&gt;TITLE&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;18/05/2016&lt;/strong&gt;&amp;nbsp; &amp;nbsp; &lt;a href=&quot;/link//paragraphs/bio&quot;&gt;Author's name&lt;/a&gt;&amp;nbsp;|&amp;nbsp;&lt;a href=&quot;/link/paragraphs/speech&quot;&gt;Speech&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;01/01/2011&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/strong&gt;&lt;a href=&quot;/link/paragraphs/bio02&quot;&gt;Author's name02&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;28/08/2013&amp;nbsp; &amp;nbsp; &lt;/strong&gt;&lt;a href=&quot;/link/paragraphs/bio03&quot;&gt;Author's name03&lt;/a&gt;&amp;nbsp;|&amp;nbsp;&lt;a href=&quot;/link/paragraphs/speech&quot;&gt;Speech&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;01/01/2011&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/strong&gt;&lt;a href=&quot;/link/paragraphs/bio04&quot;&gt;Author's name04&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;01/01/2011&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/strong&gt;&lt;a href=&quot;/link/paragraphs/bio05&quot;&gt;Author's name05&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;28/08/2013&amp;nbsp; &amp;nbsp; &lt;/strong&gt;&lt;a href=&quot;/link/paragraphs/bio03&quot;&gt;Author's name06&lt;/a&gt;&amp;nbsp;|&amp;nbsp;&lt;a href=&quot;/link/paragraphs/speech&quot;&gt;Speech&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>With beautifulsoap, I'm currently creating separate lists of times, speech authors, speech links, links to biographies and then put them in a dictionary or dataframe. But I'm having difficulty with two things:</p> <ul> <li>(1) as you can see in the html example indicated above in some paragraphs it has the five information to be extracted and in other paragraphs only three pieces of information. with that, when it comes to combining the lists, it does not work. Would it be possible to iterate by paragraph and extract the internal information from each paragraph?</li> <li>(2) in the href links there are paragraphs with information to be extracted (I can do this), but I am having difficulty integrating this in the same dictionary indicated above</li> </ul> <pre class="lang-py prettyprint-override"><code> url = 'www.example.com/' html = urlopen(url) bs = BeautifulSoup(html.read(), 'html.parser') for time in bs.find_all('strong'): times.append(times.get_text()) times_tmp2 = times[2:] time_tmp2 = &quot;&quot;.join([str(_) for _ in times_tmp2]) time_tmp2 = unicodedata.normalize(&quot;NFKD&quot;, time_tmp2) time_tmp2 = re.split(&quot;(\d{2}[-/]\d{2}[-/]\d{4})&quot;, time_tmp2) time_tmp2 = [x for x in time_tmp2 if x != ''] time_tmp2 = [elem for elem in time_tmp2 if elem.strip()] times_final = list(set(time_tmp2)) links_to_speech = [] for link in bs.find_all('a', string='Speech'): # print(urllib.parse.urljoin(url, link.get('href'))) links_to_speech.append(urllib.parse.urljoin(url, link.get('href'))) authors = [] for author in bs.find_all('a'): authors.append(author.get_text()) authors_final = [] for author in authors: init = 'First Author' final = 'Not Author' index_init = authors.index(init) index_final = authors.index(final) a = autores[index_inito:index_final] a = [x for x in a if x != 'Speech'] authors_final = a links_bio = [] p = bs.find_all('p') for link_bio in p: a = link_bio.find('a') links_bio.append(a) </code></pre>
<p>Based on the provided target data structure above, you appear to be using a dictionary. It isn't clear what you would like your keys to be so I would probably suggest using a list/array.</p> <p>I would suggest a slightly different way to dissect the problem.One potential implementation would be to iterate over each row (paragraph <code>&lt;p&gt;</code> of the table (div <code>&lt;div&gt;</code>) and consume the data as it is present. This allows us to populate the <code>data</code> array one index at a time.</p> <p>From here, if the link(s) are present you could then query the external data source (or read from a different location on the page) to collect the respective data. In the example below, I choose to do this in a different iteration of data to help make the code a bit more readable.</p> <p>I have not used the <a href="https://github.com/il-vladislav/BeautifulSoup4" rel="nofollow noreferrer">BeautifulSoap4</a> library before. I apologise if my solution isn't the most elegant regarding the libraries usage.</p> <pre class="lang-py prettyprint-override"><code>from typing import List from urllib.request import urlopen import bs4.element from bs4 import BeautifulSoup data: List = [] # &lt;- we want the data here. # Parse the webpage html bs = BeautifulSoup('''\ &lt;div class=&quot;item-page&quot;&gt; &lt;p&gt;&lt;strong&gt;TITLE&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;18/05/2016&lt;/strong&gt;&amp;nbsp; &amp;nbsp; &lt;a href=&quot;/link//paragraphs/bio&quot;&gt;Author's name&lt;/a&gt;&amp;nbsp;|&amp;nbsp;&lt;a href=&quot;/link/paragraphs/speech&quot;&gt;Speech&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;01/01/2011&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/strong&gt;&lt;a href=&quot;/link/paragraphs/bio02&quot;&gt;Author's name02&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;28/08/2013&amp;nbsp; &amp;nbsp; &lt;/strong&gt;&lt;a href=&quot;/link/paragraphs/bio03&quot;&gt;Author's name03&lt;/a&gt;&amp;nbsp;|&amp;nbsp;&lt;a href=&quot;/link/paragraphs/speech&quot;&gt;Speech&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;01/01/2011&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/strong&gt;&lt;a href=&quot;/link/paragraphs/bio04&quot;&gt;Author's name04&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;01/01/2011&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/strong&gt;&lt;a href=&quot;/link/paragraphs/bio05&quot;&gt;Author's name05&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;28/08/2013&amp;nbsp; &amp;nbsp; &lt;/strong&gt;&lt;a href=&quot;/link/paragraphs/bio03&quot;&gt;Author's name06&lt;/a&gt;&amp;nbsp;|&amp;nbsp;&lt;a href=&quot;/link/paragraphs/speech&quot;&gt;Speech&lt;/a&gt;&lt;/p&gt; &lt;/div&gt;''', features='html.parser') # Grab the paragraphs within the `item-page` div, checkout CSS selectors :). entries = bs.select('div.item-page p') # Populate the entries with time and links (if they are present) for entry in entries: entry: bs4.element.Tag # https://github.com/il-vladislav/BeautifulSoup4/blob/master/bs4/element.py time = entry.select_one('strong').get_text() if time == 'TITLE': continue # skip this entry # Grab a list of the links (may be of size 0-2 depending on the contents). links = [link.get('href') for link in entry.select('a')] # Populate the array with a document. data.append({ 'time': time, 'speech_link': links[0] if len(links) &gt; 0 else '', 'speech': [], 'bio_link': links[1] if len(links) &gt; 1 else '', 'bio': [], }) # Collect speeches and bios if present. for person in data: if person['speech_link']: # empty strings evaluate as False and would be skipped. html = urlopen('https://baconipsum.com/api/?type=all-meat&amp;paras=2&amp;start-with-lorem=1&amp;format=html') person['speech'] = [para.get_text() for para in BeautifulSoup(html, 'html.parser').select('p')] if person['bio_link']: html = urlopen('https://baconipsum.com/api/?type=all-meat&amp;paras=2&amp;start-with-lorem=1&amp;format=html') person['bio'] = [para.get_text() for para in BeautifulSoup(html, 'html.parser').select('p')] print(data) </code></pre>
python|html|dictionary|beautifulsoup
1
1,908,260
30,414,441
Python time interval delay variable
<p>I written a script to scrape google search results[Text, Link, Description] using Python. The code is working great, but i need a small tweak in the code to avoid google to analyse the HTTP requests Patterns . Here is the code </p> <pre><code> #import requests #import json #from os.path import exists from selenium import webdriver #from selenium.webdriver.support.ui import WebDriverWait #from selenium.common.exceptions import TimeoutException #from selenium.webdriver.common.keys import Keys #from selenium.webdriver.common.by import By import time #from lxml import html from scrapy import Selector as s #import os import csv import itertools lister = ['https://www.google.co.uk/search?q=MOT+in+Godmanchester&amp;num=10', 'https://www.google.co.uk/search?q=MOT+in+Godmanchester&amp;num=10&amp;start=10', 'https://www.google.co.uk/search?q=MOT+in+Hanley+Grange&amp;num=10', 'https://www.google.co.uk/search?q=MOT+in+Hanley+Grange&amp;num=10&amp;start=10', 'https://www.google.co.uk/search?q=MOT+in+Huntingdon&amp;num=10', 'https://www.google.co.uk/search?q=MOT+in+Huntingdon&amp;num=10&amp;start=10', 'https://www.google.co.uk/search?q=MOT+in+March&amp;num=10'] #a = range(1,3348,1) #start = 0 driver = webdriver.Firefox() with open("C:\Drive F data\Google\output.csv", "ab")as export: fieldnames = ['link','text1','text2','text3'] writer = csv.DictWriter(export, fieldnames=fieldnames) writer.writeheader() for serial,eacher in enumerate(lister,start=1): link = (eacher) time.sleep(6) driver.get(link) time.sleep(3) print serial,'.'+link source = driver.page_source source1 = s(text=source,type="html") text1 = source1.xpath('//h3[(contains(@class, "r")) and not(contains(@style, "line-height:normal"))]//text()').extract() text2 = source1.xpath('//h3[(contains(@class, "r")) and not(contains(@style, "line-height:normal"))]//@href').extract() text3 = source1.xpath('//span[@class="st"]').extract() for each,each1,each2 in itertools.izip(text1,text2,text3): each = each.encode('utf8') each1 = each1.encode('utf8') each2 = each2.encode('utf8') #print each, each1, each2 writer.writerow({'link':link,'text1':each,'text2':each1,'text3':each2}) #writer.writerow({'link':link,'text1':text1,'text2':text2}) """ r = requests.get("https://www.google.co.uk/search?q=MOT+in+Ampthill&amp;num=10") source1 = html.fromstring(r.text) text1 = source1.xpath("//h3[@class='r']") print text1 """ </code></pre> <p>On line 34 i inserted a delay of 3 seconds , but i want this delay to be a variable ranging from 10 to 30 with intervals as 2 .range(10,30,2)</p> <p>so that when the script executed the first delay will be 10 then 12 then 14 then 16 &amp; so on till 30, &amp; after reaching 30 it should come back starting from 10 then 12 then 14 &amp; so on.</p> <p>Please see the script &amp; provide useful suggestions / modifications</p>
<p>Why not just put a random number into your <code>sleep()</code>? Google will probably catch on to your sequence method.</p> <pre><code>from random import randint # ..your code.. random_int = randint(10, 30) print('Sleeping for {} seconds'.format(random_int)) time.sleep(random_int) </code></pre> <p>Now each request will sleep for a random amount of time, much harder to detect.</p>
python|loops|for-loop|xpath
1
1,908,261
66,983,909
You have missing dependencies! # Mandatory: spyder_kernels >=2.0.1,<2.1.0 : 2.0.1 (NOK)
<p>I got that warning massage after upgrade to Spyder 5.0.0</p> <blockquote> <p>&quot;You have missing dependencies!</p> <p># Mandatory:</p> <p>spyder_kernels&gt;=2.0.1,&lt;2.1.0 : 2.0.1 (NOK)&quot;</p> </blockquote> <p><a href="https://i.stack.imgur.com/L2QXk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L2QXk.png" alt="enter image description here" /></a></p>
<p>the warning message may be misleading and unnecessary. I checked, and I have spyder_kernels 2.0.1 installed. The requirement is that the installed version needs to be greater than or equal to 2.01 and less than or equal to 2.1.0 — which mine is.</p> <p>The issue is known and it will be fixed soon. Spyder isn't actually missing the dependency. It only thinks so. You can safely ignore the warning</p>
python|spyder
7
1,908,262
67,000,841
How to append value to list in single cell in Pandas dataframe based on condition
<p>I want to append a value to a list in my dataframe based on a condition.</p> <p>Sample df:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>List</th> </tr> </thead> <tbody> <tr> <td>Peter</td> <td>[a, b c]</td> </tr> <tr> <td>George</td> <td>[d, e f]</td> </tr> </tbody> </table> </div> <p>I want to add the values [g, h] to the list column if the name is George.</p> <p>Desired output:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>List</th> </tr> </thead> <tbody> <tr> <td>Peter</td> <td>[a, b c]</td> </tr> <tr> <td>George</td> <td>[d, e f, g, h]</td> </tr> </tbody> </table> </div> <p>Any suggestions?</p>
<p>Use cutom lambda function for add values to lists by mask:</p> <pre><code>L = ['g','h'] m = df['Name'].eq('George') df['List'] = df['List'].mask(m, df['List'].apply(lambda x: x + L)) print (df) Name List 0 Peter [a, b, c] 1 George [d, e, f, g, h] </code></pre> <p>Or:</p> <pre><code>df.loc[m, 'List'] = df.loc[m, 'List'].apply(lambda x: x + L) </code></pre> <p>Or:</p> <pre><code>df['List'] = np.where(m, df['List'].apply(lambda x: x + L), df['List']) </code></pre>
python|pandas|list|dataframe
1
1,908,263
66,815,120
Can´t find a hash in the downloaded Version of Haveibeenpwned, even though it is in there (python)
<p>I´m trying to build a local version of the Haveibeenpwned password database. So I downloaded the File from the <a href="https://haveibeenpwned.com/Passwords" rel="nofollow noreferrer">website</a> (NTLM Hashes, ordered by hash), unzipped it and wrote a simple python programm as proof of concept:</p> <pre><code>input_file = open(&quot;Path/to/my/file&quot;,&quot;r&quot;)#HIBP Textfile (20GB) test = &quot;32ED87BDB5FDC5E9CBA88547376818D4&quot; #123456 test2 = &quot;8846F7EAEE8FB117AD06BDD830B7586C&quot; #password for lines in input_file: line = input_file.readline() line = line.split(&quot;:&quot;) hash_value = line[0] if(hash_value == test): print(&quot;Pwned!&quot;) print(line) elif(hash_value == test2): print(&quot;Pwned&quot;) print(line) else: pass </code></pre> <p>This works for the &quot;password&quot; hash but not for &quot;123456&quot;. Output of the script:</p> <pre><code> Pwned ['8846F7EAEE8FB117AD06BDD830B7586C', '3861493\n'] &gt;&gt;&gt; </code></pre> <p>I opened the file with EmEditor and searched for the 123456 hash and it is in there. But I´m not sure why the script does not find it. I suppose it has something to do with the file size of around 20GB, but I´m not sure how to mitigate this.</p> <p>I know this is by no means efficient, it´s only purpose is to check if everything works.</p> <p><strong>Edit:</strong> corrected a little mistake: I did not download the &quot;ordered by prevalence&quot; version of HIBP but the &quot;ordered by hash&quot; version</p>
<p>Your code is skipping every second line, because <code>for lines in input_file:</code> goes to the next line as well as <code>line = input_file.readline()</code></p> <p>try it this way:</p> <pre><code>for line in input_file: line = line.split(&quot;:&quot;) ... </code></pre>
python-3.x
3
1,908,264
42,873,544
how to convert json to model in python3
<p>i am trying convert <code>json</code> string to <code>model</code></p> <p>then it is easy to get value with <code>.</code> </p> <p>i have checked <a href="https://stackoverflow.com/questions/11590190/is-there-a-python-json-library-can-convert-json-to-model-objects-similar-to-goo">another question</a> </p> <p>but different, my json sting looks like,</p> <pre><code>{ "id":"123", "name":"name", "key":{ "id":"345", "des":"des" }, } </code></pre> <p>i prefer to use 2 class like,</p> <pre><code>class A: id = '' name = '' key = new B() class B: id = '' des = '' </code></pre>
<p>There are few libraries that might help:</p> <ul> <li><a href="http://marshmallow.readthedocs.io/" rel="nofollow noreferrer">marshmallow</a> is nice</li> <li><a href="https://github.com/Pylons/colander" rel="nofollow noreferrer">colander</a> from Pylons</li> <li><a href="http://schematics.readthedocs.io/" rel="nofollow noreferrer">schematics</a></li> </ul> <p>For easier cases you can also use something from standard library like</p> <ul> <li><a href="https://docs.python.org/3/library/typing.html#typing.NamedTuple" rel="nofollow noreferrer">named tuples</a> and one from <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="nofollow noreferrer">collections</a> which is available also in py2</li> <li><a href="https://docs.python.org/3/library/types.html?highlight=simplenamespace#types.SimpleNamespace" rel="nofollow noreferrer">SimpleNamespace</a></li> </ul>
python|json
2
1,908,265
65,894,198
Discord.py - Send message under different name or user
<p>I've been working on a bot and there was a small request, which I have no idea how to do.</p> <p>When user types their message, the bot checks whether the message contains a predetermined keyword (to put everything into perspective, I'm using examples from an already working BOT), replace this part (for example an emoji) and post the message again, under the name of the user, which posted the message. <em>(I do not want to do exactly this, I just want to know how to &quot;post as another user&quot; like</em> <em><strong>Animated Emojis</strong></em> <em>bot)</em>.</p> <p>It works like this:</p> <p><img src="https://i.stack.imgur.com/cKnWM.png" alt="Example of image" /></p> <p>Also somehow, the user created is not a valid user, since they don't have any roles or can be messaged. This is what happens if you click on their profile (in chat):</p> <p><img src="https://i.stack.imgur.com/myhC2.png" alt="Invalid profile" /></p> <p>As I've said before, this is somehow possible (the <em>animated emojis</em> bot is one of the examples) and I wonder, how can I do something like this.</p> <p>Thanks in advance and I hope you have lovely day!</p>
<p>I have found a simple way, and seems like what you are talking about, simply creating a webhook with the user's name or another user you use the command to &quot;act&quot; as, will create a Discord webhook with those details, then deletes the webhook, but keeps the message. Try this.</p> <pre><code>@client.command() async def act(ctx, member: discord.Member, *, message=None): if message == None: await ctx.send( f'Please provide a message with that!') return webhook = await ctx.channel.create_webhook(name=member.name) await webhook.send( str(message), username=member.name, avatar_url=member.avatar_url) webhooks = await ctx.channel.webhooks() for webhook in webhooks: await webhook.delete() </code></pre> <p>EDIT: A webhook is a communication type that can be used to access &amp; automate your messages to send data updates to your Discord text channels.</p> <p>In this case, when sending the message from the command, the user appears as a bot, but everything else is from the user. NQN bot uses this exact method</p>
python|discord|discord.py
6
1,908,266
50,796,244
How do I check if a value is in a nested python dictionary?
<p>How do I check if a value is in a nested python dictionary?</p> <p>I want to check if the choice the user enters is in the dictionary and if not add the new movie to the dictionary, and if it is to state the movie is already stored.</p> <p>I would also like the user to enter movie choice and the dictionary to print the details of the that particular movie rather than all 10.</p> <p>Click on link to view picture of code.</p> <p><strong>This is the written code:</strong></p> <pre><code>topMovies = {1:{'Movie':'Avatar', 'Year': '2009', 'Gross Profit': '£2.788 billion', 'Budget': '£237 million'}, 2:{'Movie':'Titanic', 'Year': '1997', 'Gross Profit': '£2.187 billion', 'Budget': '£200 million'}, 3:{'Movie':'Star Wars: The Force Awakens', 'Year': '2015', 'Gross Profit': '£2.068 billion', 'Budget': '£306 million'}, 4:{'Movie':'Avengers: Infinity War', 'Year': '2018', 'Gross Profit': '£1.814 billion', 'Budget': '£400 million'}, 5:{'Movie':'Jurassic World', 'Year': '2015', 'Gross Profit': '£1.672 billion', 'Budget': '£150 million'}, 6:{'Movie':'The Avengers', 'Year': '2012', 'Gross Profit': '£1.519 billion', 'Budget': '£220 million'}, 7:{'Movie':'Fast and Furious 7', 'Year': '2015', 'Gross Profit': '£1.516 billion', 'Budget': '£190 million'}, 8:{'Movie':'Avengers: Age of Ultron', 'Year': '2015', 'Gross Profit': '£1.405 billion', 'Budget': '£444 million'}, 9:{'Movie':'Black Panther', 'Year': '2018', 'Gross Profit': '£1.344 billion', 'Budget': '£210 million'}, 10:{'Movie':'Harry Potter and the Deathly Hollows: Part 2', 'Year': '2011', 'Gross Profit': '£1.342 billion', 'Budget': '£250 million (shared with part 1)'}} for movieID, movieInfo in topMovies.items(): print("\nNumber: ", movieID) for key in movieInfo: print(key , ": " , movieInfo[key]) print("\n") #checking if movie already stored and if not add new movie else movie is already stored choice = input('Please enter choice: ') for x in topMovies: if choice != topMovies[x]: print("Enter new movie!") topMovies[x] = {} topMovies[x]['Movie'] = choice topMovies[x]['Year'] = input('Enter the year of release for the movie: ') topMovies[x]['Gross Profit'] = input('Enter the gross profit of the movie: ') topMovies[x]['budget'] = input('Enter the budget for the movie: ') print("\n") print(topMovies[x]) elif choice == topMovies[x]['Movie']: print("Movie already stored!") break </code></pre>
<p>You have to test the value of <code>choice</code> against all movies <code>'Movie'</code> values <em>before</em> letting the user create a new entry:</p> <pre><code>choice = input('Please enter choice: ') for movie in topMovies.values(): if movie["Movie"] == choice: print("Movie already stored!") break else: # IMPORTANT: this is a 'else' for the `for` loop, # it will only be executed if the loop terminates # without a `break` # create the movie here - warning: you'll need to find # the highest `topMovies` key to compute the new movie key. </code></pre> <p>Note that this solution is inefficient (sequential scanning is O(N)) and not as readable as it could be. You could improve it by using a better datastructure - when you see a dict whose keys are consecutive ascending integers chances are you want a <code>list</code> instead - and a reverse index (a dict mapping movies names to their index in the list).</p> <pre><code>top_movies = [ {'Movie':'Avatar', 'Year': '2009', 'Gross Profit': '£2.788 billion', 'Budget': '£237 million'}, {'Movie':'Titanic', 'Year': '1997', 'Gross Profit': '£2.187 billion', 'Budget': '£200 million'}, {'Movie':'Star Wars: The Force Awakens', 'Year': '2015', 'Gross Profit': '£2.068 billion', 'Budget': '£306 million'}, {'Movie':'Avengers: Infinity War', 'Year': '2018', 'Gross Profit': '£1.814 billion', 'Budget': '£400 million'}, {'Movie':'Jurassic World', 'Year': '2015', 'Gross Profit': '£1.672 billion', 'Budget': '£150 million'}, {'Movie':'The Avengers', 'Year': '2012', 'Gross Profit': '£1.519 billion', 'Budget': '£220 million'}, {'Movie':'Fast and Furious 7', 'Year': '2015', 'Gross Profit': '£1.516 billion', 'Budget': '£190 million'}, {'Movie':'Avengers: Age of Ultron', 'Year': '2015', 'Gross Profit': '£1.405 billion', 'Budget': '£444 million'}, {'Movie':'Black Panther', 'Year': '2018', 'Gross Profit': '£1.344 billion', 'Budget': '£210 million'}, {'Movie':'Harry Potter and the Deathly Hollows: Part 2', 'Year': '2011', 'Gross Profit': '£1.342 billion', 'Budget': '£250 million (shared with part 1)'} ] movies_index = {movie["Movie"].lower(): index for index, movie in enumerate(top_movies)} # .... choice = input('Please enter choice: ').strip() # dict lookup is O(1) and highly optimised if choice.lower() in movies_index: print("Movie already stored!") else: new_movie = {"Movie": choice} # fill in the fields # ... top_movies.append(new_movie) movies_index[choice.lower()] = len(top_movies) - 1 </code></pre>
python|dictionary
1
1,908,267
3,552,928
how do i set a timeout value for python's mechanize?
<p>How do i set a timeout value for python's mechanize?</p>
<p>Alex is correct: <code>mechanize.urlopen</code> takes a <code>timeout</code> argument. Therefore, just insert a number of <a href="http://docs.python.org/library/socket.html#socket.socket.settimeout" rel="noreferrer">seconds in floating point</a>: <code>mechanize.urlopen('http://url/', timeout=30.0)</code>.</p> <p>The background, from the source of <code>mechanize.urlopen</code>:</p> <pre><code>def urlopen(url, data=None, timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT): ... return _opener.open(url, data, timeout) </code></pre> <p>What is <code>mechanize._sockettimeout._GLOBAL_DEFAULT_TIMEOUT</code> you ask? It's just the <code>socket</code> module's setting.</p> <pre><code>import socket try: _GLOBAL_DEFAULT_TIMEOUT = socket._GLOBAL_DEFAULT_TIMEOUT except AttributeError: _GLOBAL_DEFAULT_TIMEOUT = object() </code></pre>
python|timeout|mechanize
13
1,908,268
50,408,201
DataFrame.apply(func, raw=True) doesn't seem to take effect?
<p>I am trying to hash together only a few columns of my dataframe <code>df</code> so I do</p> <pre><code>temp = df['field1', 'field2'] df["hash"] = temp.apply(lambda x: hash(x), raw=True, axis=1) </code></pre> <p>I set raw to true because the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html#pandas.DataFrame.apply" rel="nofollow noreferrer">doc</a> (I am using 0.22) says it will pass a numpy array instead of a mutable Series but even with <code>raw=True</code> I am getting a Series, why?</p> <pre><code> File "/nix/store/9ampki9dbq0imhhm7i27qkh56788cjpz-python3.6-pandas-0.22.0/lib/python3.6/site-packages/pandas/core/frame.py", line 4877, in apply ignore_failures=ignore_failures) File "/nix/store/9ampki9dbq0imhhm7i27qkh56788cjpz-python3.6-pandas-0.22.0/lib/python3.6/site-packages/pandas/core/frame.py", line 4973, in _apply_standard results[i] = func(v) File "/home/teto/mptcpanalyzer/mptcpanalyzer/data.py", line 190, in _hash_row return hash(x) File "/nix/store/9ampki9dbq0imhhm7i27qkh56788cjpz-python3.6-pandas-0.22.0/lib/python3.6/site-packages/pandas/core/generic.py", line 1045, in __hash__ ' hashed'.format(self.__class__.__name__)) TypeError: ("'Series' objects are mutable, thus they cannot be hashed", 'occurred at index 1') </code></pre>
<p>It's strange, as I can't reproduce your exact error (that is, by me, <code>raw=True</code> indeed results in an <code>np.ndarray</code> being passed). In any case, neither a <code>Series</code> nor a <code>np.ndarray</code> are hashable. The following works, though:</p> <pre><code>temp.apply(lambda x: hash(tuple(x)), axis=1) </code></pre> <p>A <code>tuple</code> <em>is</em> hashable.</p>
pandas
1
1,908,269
50,244,155
Generating a reverse-engineerable code to save game, python 3
<p>So I'm making a little text based game in Python and I decided for a save system I wanted to use the old "insert code" trick. The code needs to keep track of the players inventory (as well as other things, but the inventory is what I'm having trouble with).</p> <p>So my thought process on this would be to tie each item and event in the game to a code. For example, the sword in your inventory would be stored as "123" or something unique like that. </p> <p>So, for the code that would generate to save the game, imagine you have a sword and a shield in your inventory, and you were in the armory. </p> <p>location(armory) = abc</p> <p>sword = 123</p> <p>shield = 456</p> <p>When the player inputs the command to generate the code, I would expect an output something like: </p> <p>abc.123.456</p> <p>I think putting periods between items in the code would make it easier to distinguish one item from another when it comes to decoding the code. </p> <p>Then, when the player starts the game back up and they input their code, I want that abc.123.456 to be translated back into your location being the armory and having a sword and shield in your inventory. </p> <p>So there are a couple questions here:</p> <ol> <li>How do I associate each inventory item with its respective code?</li> <li>How do I generate the full code? </li> <li>How do I decode it when the player loads back in?</li> </ol> <p>I'm pretty damn new to Python and I'm really not sure how to even start going about this... Any help would be greatly appreciated, thanks!</p>
<p>So, if I get you correctly, you want to serialize info into a string which can't be "saved" but could be input in your program;</p> <p>Using dots is not necessary, you can program your app to read your code without them.. this will save you a few caracters in lenght.</p> <p>The more information your game needs to "save", the longer your code will be; I would suggest to use as short as possible strings.</p> <p>Depending on the amount of locations, items, etc. you want to store in your save code: you may prefer longer or shorter options:</p> <ul> <li>digits (0-9): will allow you to keep 10 names stored in 1 character each.</li> <li>hexadecimal (0-9 + a-f, or 0-9 + a-F): will allow you to keep from 16 to 22 names (22 if you make your code case sensitive)</li> <li>alphanum (0-9 + a-z, or 0-9 + a-Z): will allow you to keep from 36 to 62 names (62 if case sensitive)</li> <li>more options are possible if you decide to use punctuation and punctuated characters, this example will not go there, you will need to cover that part yourself if you need.</li> </ul> <p>For this example I'm gonna stick with digits as I'm not listing more than 10 items or locations.</p> <p>You define each inventory item and each place as dictionaries, in your source code:</p> <p>You can a use single line like I have done for places </p> <pre><code>places = {'armory':'0', 'home':'1', 'dungeon':'2'} # below is the same dictionary but sorted by values for reversing. rev_places = dict(map(reversed, places.items())) </code></pre> <p>Or for improved readability; use multiple lines:</p> <pre><code>items = { 'dagger':'0', 'sword':'1', 'shield':'2', 'helmet':'3', 'magic wand':'4' } #Below is the same but sorted by value for reversing. rev_items = dict(map(reversed, items.items())) </code></pre> <p>Store numbers as strings, for easier understanding, also if you use hex or alphanum options it will be required.</p> <p>Then also use dictionaries to manage in game information, <strong>below is just a sample of how you should represent your game infos that the code will produce or parse, this portion should not be in your source code, I have intentionally messed items order to test it.</strong>;</p> <pre><code>game_infos = { 'location':'armory', 'items':{ 'slot1':'sword', 'slot2':'shield', 'slot3':'dagger', 'slot4':'helmet' } } </code></pre> <p>Then you could generate your save code with following function that reads your inventory and whereabouts like so:</p> <pre><code>def generate_code(game_infos): ''' This serializes the game information dictionary into a save code. ''' location = places[game_infos['location']] inventory = '' #for every item in the inventory, add a new character to your save code. for item in game_infos['items']: inventory += items[game_infos['items'][item]] return location + inventory # The string! </code></pre> <p>And the reading function, which uses the reverse dictionaries to decipher your save code.</p> <pre><code>def read_code(user_input): ''' This takes the user input and transforms it back to game data. ''' result = dict() # Let's start with an empty dictionary # now let's make the user input more friendly to our eyes: location = user_input[0] items = user_input[1:] result['location'] = rev_places[location] # just reading out from the table created earlier, we assign a new value to the dictionary location key. result['items'] = dict() # now make another empty dictionary for the inventory. # for each letter in the string of items, decode and assign to an inventory slot. for pos in range(len(items)): slot = 'slot' + str(pos) item = rev_items[items[pos]] result['items'][slot] = item return result # Returns the decoded string as a new game infos file :-) </code></pre> <p>I recommend you play around with this working sample program, create a game_infos dictionary of your own with more items in inventory, add some places, etc. You could even add some more lines/loops to your functions to manage hp or other fields your game will require.</p> <p>Hope this helps and that you had not given up on this project!</p>
arrays|python-3.x
0
1,908,270
35,090,401
how to calculate the dot product of two arrays of vectors in python?
<p><code>A and B</code> are both arrays with <code>shape(N,3)</code>. They each contain N vectors such that <code>A[0] = a0 (vector), A[1] = a1...</code> and <code>B[0] = b0, B[1] = b1...</code></p> <p>I want to calculate the dot product of the N pairs of vectors an and bn. In other words, I want to obtain an array C with <code>shape(N,1)</code> such that <code>C[i] = np.dot(A[i],B[i]).</code> What is the most efficient way of doing this in python (e.g. using vectorized code)?</p>
<p>You can perform element-wise multiplication and then sum along the second axis, like so -</p> <pre><code>C = (A*B).sum(1) </code></pre> <p>These multiplication and summation operations can be implemented in one go with <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a>, like so -</p> <pre><code>C = np.einsum('ij,ij-&gt;i',A,B) </code></pre> <p>With <a href="https://numpy.org/doc/stable/reference/generated/numpy.matmul.html" rel="nofollow noreferrer"><code>np.matmul</code></a>/<code>@-operator</code> -</p> <pre><code>(A[:,None,:] @ B[...,None]).ravel() </code></pre>
python|numpy|scipy|vectorization|linear-algebra
8
1,908,271
34,959,455
Detect parking lot by opencv
<p>This program identifies the objects if it is single row (smaller image).</p> <pre><code>from __future__ import division from collections import defaultdict from collections import OrderedDict from cv2 import line import cv2 from matplotlib import pyplot as plt from networkx.algorithms import swap from numpy import mat from skimage.exposure import exposure import numpy as np from org import imutils from numpy.core.defchararray import rindex import sys def line(p1, p2): A = (p1[1] - p2[1]) B = (p2[0] - p1[0]) C = (p1[0]*p2[1] - p2[0]*p1[1]) return A, B, -C def intersection(L1, L2): D = L1[0] * L2[1] - L1[1] * L2[0] Dx = L1[2] * L2[1] - L1[1] * L2[2] Dy = L1[0] * L2[2] - L1[2] * L2[0] if D != 0: x = Dx / D y = Dy / D return x,y else: return False def comupteIntersect(hline,vline): hx1=hline[0];hy1=hline[1];hx2=hline[2];hy2=hline[3]; vx3=vline[0];vy3=vline[1];vx4=vline[2];vy4=vline[3]; return 0; input = sys.argv[1] # CascadeClassifier class to detect objects. cas1.xml will have the trained data face_cascade = cv2.CascadeClassifier(sys.argv[2]) # im will have the input in image format im = cv2.imread(input) im2=im # cvtColor Converts an image from one color space to another. gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) # apply diverse linear filters to smooth images using GaussianBlur blur = cv2.GaussianBlur(gray,(5,15),0) # apply segmentation # Application example: Separate out regions of an image corresponding to objects which we want to analyze. This separation is based on the variation of intensity between the object pixels and the background pixels. # To differentiate the pixels we are interested in from the rest (which will eventually be rejected), we perform a comparison of each pixel intensity value with respect to a threshold (determined according to the problem to solve). # Once we have separated properly the important pixels, we can set them with a determined value to identify them (i.e. we can assign them a value of 0 (black), 255 (white) or any value that suits your needs). ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) # Contours can be explained simply as a curve joining all the continuous points (along the boundary), having same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition. # # For better accuracy, use binary images. So before finding contours, apply threshold or canny edge detection. # findContours function modifies the source image. So if you want source image even after finding contours, already store it to some other variables. # In OpenCV, finding contours is like finding white object from black background. So remember, object to be found should be white and background should be black. contours, hierarchy = cv2.findContours(th3,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # by here skeleton would have been drawn #to draw the contour in the image enable the below line #img = cv2.drawContours(im, contours, -1, (0,255,0), 1) idx =0 for cnt in contours: x,y,w,h = cv2.boundingRect(cnt) if w-x&gt;900 and h-y&gt;100: roi=im[y:y+h,x:x+w] crop_rect=im[y:y+h,x:x+w] # cv2.imshow('crop_rect',crop_rect) # cv2.waitKey(0) idx+=1 cv2.imwrite('crp_contour'+str(idx) + '.jpg', crop_rect) im4=crop_rect im3=crop_rect gray=cv2.cvtColor(crop_rect,cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,15),0) ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) contours, hierarchy = cv2.findContours(th3,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) rect=None for cnt in contours: x1=[] y1=[] rect = cv2.minAreaRect(cnt) box = cv2.cv.BoxPoints(rect) box = np.int0(box) x1.append(box[0][0]); x1.append(box[1][0]); x1.append(box[2][0]); x1.append(box[3][0]); y1.append(box[0][1]); y1.append(box[1][1]); y1.append(box[2][1]); y1.append(box[3][1]); x=np.amin(x1) y=np.amin(y1) w=np.amax(x1) h=np.amax(y1) # re = cv2.rectangle([box]) # x,y,w,h = cv2.boundingRect(cnt) if w-x&gt;900 and h-y&gt;100: rect = cv2.minAreaRect(cnt) box = cv2.cv.BoxPoints(rect) box = np.int0(box) x,y,w,h = cv2.boundingRect(cnt) # crop_rect1=crop_rect[y:y+h,x:x+w] # cv2.imshow('crop_rect',crop_rect1) # cv2.waitKey(0) break #( top-left corner(x,y), (width, height), angle of rotation ) x=rect[0][0] y=rect[0][1] w=rect[1][0] h=rect[1][1] angle=rect[2] if rect[2]&lt;-45: angle += 90.0; temp=w w=h h=temp center=(x+w)/2,(y+h)/2 img=crop_rect.copy() rot_mat = cv2.getRotationMatrix2D(center, angle, 1); dst=cv2.warpAffine(crop_rect,rot_mat, (int(w),int(h))); # cv2.imshow('Rotated and Cropped Image',dst) # cv2.waitKey(0) horizontal = [] im6=dst im4=im6 im3=im6 gray=cv2.cvtColor(im6,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray,50,150,apertureSize = 3) # cv2.imshow('edges Image',edges) # cv2.waitKey(0) # Find the edge of the image # lines = cv2.HoughLines(edges,1,np.pi/95,40) lines = cv2.HoughLines(edges,1,np.pi/180,40) for rho,theta in lines[0]: pt1 = [] im5=im6 if (theta&lt;np.pi/180*95 and theta&gt;np.pi/180*88): if (rho==78.0): a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) pt1.append(x1) pt1.append(y1) pt1.append(x2) pt1.append(y2) horizontal.append(pt1) cv2.line(im5,(x1,y1),(x2,y2),(0,0,255),2) # cv2.imshow('for',im5) # cv2.waitKey(0) break # diff = h-y toty1 = diff+y1+20.0 toty2 = diff+y2+20.0 #cv2.line(im5,(int(x1),int(toty1)),(int(x2),int(toty2)),(0,0,255),2) pt1 = [] pt1.append(int(x1)) pt1.append(int(toty1)) pt1.append(int(x2)) pt1.append(int(toty2)) horizontal.append(pt1) minLineLength = 50 maxLineGap = 10 im7=im3 gray = cv2.cvtColor(im5, cv2.COLOR_BGR2GRAY) gray = cv2.bilateralFilter(gray, 11, 17, 17) edged = cv2.Canny(gray, 30, 200) m,n = gray.shape L=[] lines = cv2.HoughLines(edged, 2, np.pi/180,10,0,0)[0] # or theta&gt;np.pi/180*80 and theta&lt;np.pi/180*100 or theta&gt;np.pi/180*170 or theta&lt;np.pi/180*10 i=0 d = defaultdict(list) for (rho,theta) in lines: if(i&lt;1000): if(theta&gt;np.pi/180*170 or theta&lt;np.pi/180*10): if(theta!=0 and rho!=-795.0 and rho!=-745.0 and rho!=-749.0 and rho!=425.0 and rho!=251.0 and rho!=253.0): l=[] x0 = np.cos(theta)*rho y0 = np.sin(theta)*rho pt1 = ( int(x0 + (m+n)*(-np.sin(theta))), int(y0 + (m+n)*np.cos(theta)) ) pt2 = ( int(x0 - (m+n)*(-np.sin(theta))), int(y0 - (m+n)*np.cos(theta)) ) if (pt1[0]==-92 or pt1[0]==-27 or pt1[0]==65 or pt1[0]==154 or pt1[0]==315 or pt1[0]==409 or pt1[0]==469 or pt1[0]==519 or pt1[0]==549 or pt1[0]==573 or pt1[0]==592): # cv2.line(im3, pt1,pt2 ,(255,0,0), 2,cv2.cv.CV_AA) # cv2.imshow('img44',im3) # cv2.waitKey(0) #b=str(pt1)+","+str(pt2) l.append(pt1) l.append(pt2) L.append(l) d[pt1[0]].append(l) i+=1 else: break sdict=OrderedDict(sorted(d.items(), key=lambda t: t[0])) vertical = [] xcoordinates=[] ycoordinates=[] i=0;j=0; p=[] pt=[] for t in range(0,6): p.append(t) pt.append(p) ncars = 0 sub_image_point=[]; # process each full parking slot image for a in sdict: vx3=sdict[a][0][0][0];vy3=sdict[a][0][0][1];vx4=sdict[a][0][1][0];vy4=sdict[a][0][1][1]; pt[0]=[];pt[4]=[] pt[0].append(vx3);pt[0].append(vy3); pt[4].append(vx4);pt[4].append(vy4); j+=1; if (j!=1): for k in range(0,2): i+=1 pt1=pt[k+k*k] pt2=pt[k+2*2] L1=line(pt1,pt2) for hline in horizontal: pt3=[];pt4=[] hx1=hline[0];hy1=hline[1];hx2=hline[2];hy2=hline[3]; pt3.append(hx1);pt3.append(hy1); pt4.append(hx2);pt4.append(hy2); L2=line(pt3,pt4) R = intersection(L1, L2) if R: xcoordinates.append(R.__getitem__(0)) ycoordinates.append(R.__getitem__(1)) else: print "\n","No single intersection point detected" if i==2: i=0; pt[2]=pt[0];pt[5]=pt[4];p=[]; p.append(np.amin(ycoordinates));p.append(np.amax(ycoordinates)); p.append(np.amin(xcoordinates));p.append(np.amax(xcoordinates)); sub_image_point.append(p) # crop_rect=im3[np.amin(ycoordinates):np.amax(ycoordinates),np.amin(xcoordinates):np.amax(xcoordinates)] # cv2.imshow('Crop_Rect',crop_rect) # cv2.waitKey(0) xcoordinates=[] ycoordinates=[] else: pt[2]=[];pt[5]=[] pt[2]=pt[0];pt[5]=pt[4]; cv2.destroyAllWindows() i=0; pt=[] # process slice of each full parking slot image for p in sub_image_point: i+=1 x1=p[0];y1=p[1];x2=p[2];y2=p[3]; crop_rect=im3[x1:y1,x2:y2] cars = face_cascade.detectMultiScale(crop_rect, 1.1,5) for (x,y,w,h) in cars: cv2.rectangle(crop_rect,(x,y),(x+w,y+h),(0,0,255),2) ncars = ncars + 1 print "\n",ncars, "Car is detected in ",i," slot" pt.append(i) # show result # cv2.imshow("Result",crop_rect) # cv2.waitKey(0); i=0; pt1=[] print "\n","occupied slots: ",pt1 for p in pt: print " ",p </code></pre> <p>Classifier - <a href="https://github.com/abhi-kumar/CAR-DETECTION/blob/master/cas1.xml" rel="nofollow noreferrer">https://github.com/abhi-kumar/CAR-DETECTION/blob/master/cas1.xml</a></p> <p>Identifies the cars in image-1 with single row. <a href="https://i.stack.imgur.com/yPOwH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yPOwH.jpg" alt="enter image description here"></a></p> <p>But unable to identify the objects from the image with 2 rows? <a href="https://i.stack.imgur.com/TWLzV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TWLzV.jpg" alt="enter image description here"></a></p>
<p>I can find the rectangle of second image by two solutions.I solved the problem by c++, but you should be able to transform it to python at ease</p> <p>Solution 1 : threshold and countours.</p> <p>1 : Apply otsu threshold on the image</p> <p>2 : dilate the images</p> <p>3 : find contours</p> <p>4 : find valid rectangle</p> <p>The codes are</p> <pre><code>void identify_ob_by_edges(cv::Mat const &amp;img) { cv::Mat gray; cv::cvtColor(img, gray, CV_BGR2GRAY); cv::threshold(gray, gray, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); auto const kernel = cv::getStructuringElement(cv::MORPH_RECT, {7,7}); cv::dilate(gray, gray, kernel); std::vector&lt;std::vector&lt;cv::Point&gt;&gt; contours; cv::findContours(gray.clone(), contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE); cv::Mat img_copy = img.clone(); for(auto const &amp;contour : contours){ auto const rect = cv::boundingRect(contour); if(rect.area() &gt;= 2000 &amp;&amp; (rect.height / static_cast&lt;double&gt;(rect.width)) &gt; 1.0){ cv::rectangle(img_copy, rect, {255, 0, 0}, 3); } } cv::imshow("binarize", gray); cv::imshow("color", img_copy); cv::waitKey(); cv::imwrite("result.jpg", img_copy); } </code></pre> <p>The results are</p> <p><a href="https://i.stack.imgur.com/nO5bM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nO5bM.jpg" alt="enter image description here"></a></p> <p>But this do not work if not all of the lines can be seen, times for solution two.</p> <p>2 : use HoughLinesP and contours to find the rectangle</p> <pre><code>/** * Work if no critical lines are completely hide */ void identify_ob_by_lines(cv::Mat const &amp;img) { cv::Mat gray; cv::cvtColor(img, gray, CV_BGR2GRAY); cv::threshold(gray, gray, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); cv::Mat edges; cv::Canny(gray, edges, 30, 90); std::vector&lt;cv::Vec4i&gt; lines; cv::HoughLinesP(edges, lines, 1, CV_PI/180, 50, 50, 10); std::vector&lt;cv::Vec4i&gt; hor_lines; std::vector&lt;cv::Vec4i&gt; vec_lines; //remove lines with invalid angle for(auto const &amp;l : lines) { auto const p1 = cv::Point(l[0], l[1]); auto const p2 = cv::Point(l[2], l[3]); auto const angle = abs_line_angle(p1, p2); if(angle &gt;= 76){ vec_lines.emplace_back(l); }else if(angle &lt;= 5){ hor_lines.emplace_back(l); } } //remove_adjacent_lines(hor_lines, 1, 400); remove_adjacent_lines(vec_lines, 0, 30); //draw lines on blank image cv::Mat blank = cv::Mat::zeros(img.size(), CV_8U); draw_lines(blank, hor_lines, {255}); draw_lines(blank, vec_lines, {255}); //find the contours of blank image std::vector&lt;std::vector&lt;cv::Point&gt;&gt; contours; cv::findContours(blank.clone(), contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE); for(auto const &amp;contour : contours){ auto const rect = cv::boundingRect(contour); if(rect.area() &gt;= 2000 &amp;&amp; (rect.height / static_cast&lt;double&gt;(rect.width)) &gt; 1.0){ //cv::rectangle(img_copy, rect, {255, 0, 0}, 3); auto const min_rect = cv::minAreaRect(contour); cv::Point2f rect_points[4]; min_rect.points(rect_points); for(size_t j = 0; j &lt; 4; ++j){ cv::line(img, rect_points[j], rect_points[(j+1)%4], {255, 0, 0}, 2, 8); } } } cv::imshow("img copy", img); cv::waitKey(); cv::imwrite("result.jpg", blank); } </code></pre> <p>The results : </p> <p><a href="https://i.stack.imgur.com/wDGEy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wDGEy.jpg" alt="enter image description here"></a></p> <p>There are one rectangle do not drawn by this solution, this could be fixed if you pull the camera farther.Solution 2 should work for image 1 too if image 1 do not hide the horizontal line, I think in normal case, the line would not be hided like that. If it do, the you can measure the distance and draw the lines by yourself.</p> <p>I recommend you give <a href="http://blog.dlib.net/2014/02/dlib-186-released-make-your-own-object.html" rel="nofollow noreferrer">dlib</a> a try, the object detector of dlib is awesome.</p> <p>The source codes are located at <a href="https://github.com/stereomatchingkiss/blogCodes2/blob/master/forum_quest/so_obj_detect_00.cpp" rel="nofollow noreferrer">github</a>.</p>
python-2.7|opencv|opencv3.0
4
1,908,272
34,990,950
Creating list with dates
<p>I have created a function that extracts the &quot;date&quot; of each article that I have in a text file (4 or 5th row of each article). The challenge is now to create a text file with just the month and the year. Here is my function main:</p> <pre><code>def main(): for i in range(len(sections)): print(sections[i].split(&quot;\n&quot;)[4]) print(sections[i].split(&quot;\n&quot;)[5]) main() </code></pre> <p>Which gives me the following text:<a href="https://i.stack.imgur.com/48vvG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/48vvG.png" alt="enter image description here" /></a></p> <p>As it can be seen, the dates are not stored in every column. Moreover, the date format varies: those stored in row 4 of my original text appear with the date (first 6 of them), whereas those which were stored in column 5 appear without the date.</p> <p>Ideally the text file would look like:</p> <ol> <li><p>December 2005</p> </li> <li><p>December 2005</p> </li> <li><p>December 2005</p> </li> <li><p>December 2005</p> </li> <li><p>December 2005</p> </li> <li><p>November 2005</p> </li> <li><p>....</p> <p>Thanks a lot!</p> </li> </ol>
<p>Keeping as much as possible your code structure, this should be the solution you are looking for. It's meant to be easy to read and understand. However it is not the best solution, for that we need to know what selection looks like, or even better what your input file looks like.</p> <pre><code>def main(): with open('output.txt', 'w') as f: for i in range(len(sections)): date_row4 = sections[i].split("\n")[4].split(" ") date_row5 = sections[i].split("\n")[5].split(" ") print(date_row4) print(date_row5) month_row4 = date_row4[1] year_row4 = date_row4[3] month_row5 = date_row5[1] year_row5 = date_row5[3] if len(month_row4): # avoid to write empty lines in the output f.write("{} {}{}".format(month_row4,year_row4,'\n')) if len(month_row4): f.write("{} {}{}".format(month_row5,year_row5,'\n')) main() </code></pre>
python
2
1,908,273
26,596,714
Python: Writing to a single file with queue while using multiprocessing Pool
<p>I have hundreds of thousands of text files that I want to parse in various ways. I want to save the output to a single file without synchronization problems. I have been using multiprocessing pool to do this to save time, but I can't figure out how to combine Pool and Queue. </p> <p>The following code will save the infile name as well as the maximum number of consecutive "x"s in the file. However, I want all processes to save results to the same file, and not to different files as in my example. Any help on this would be greatly appreciated.</p> <pre><code>import multiprocessing with open('infilenamess.txt') as f: filenames = f.read().splitlines() def mp_worker(filename): with open(filename, 'r') as f: text=f.read() m=re.findall("x+", text) count=len(max(m, key=len)) outfile=open(filename+'_results.txt', 'a') outfile.write(str(filename)+'|'+str(count)+'\n') outfile.close() def mp_handler(): p = multiprocessing.Pool(32) p.map(mp_worker, filenames) if __name__ == '__main__': mp_handler() </code></pre>
<p>Multiprocessing pools implement a queue for you. Just use a pool method that returns the worker return value to the caller. imap works well:</p> <pre><code>import multiprocessing import re def mp_worker(filename): with open(filename) as f: text = f.read() m = re.findall("x+", text) count = len(max(m, key=len)) return filename, count def mp_handler(): p = multiprocessing.Pool(32) with open('infilenamess.txt') as f: filenames = [line for line in (l.strip() for l in f) if line] with open('results.txt', 'w') as f: for result in p.imap(mp_worker, filenames): # (filename, count) tuples from worker f.write('%s: %d\n' % result) if __name__=='__main__': mp_handler() </code></pre>
python|queue|multiprocessing|pool
45
1,908,274
56,779,960
Get the element for which the absolute difference between left half product and right half product is minimum
<p>I want to find the element in a given array (n elements) such that the absolute difference between the left half product and the right half product is minimum </p> <pre><code>(abs(arr[0]*arr[1]*...arr[x]-arr[x+1]*arr[x+2]...arr[n])) </code></pre> <p>the question also updates the values of the array regularly 'm' times. I want to get answers of all queries in O(m log n).</p> <p>I have tried an approach which takes O(n*m) time and it is not working due to TLE error.</p>
<p><strong>The only approach comes in my mind:</strong></p> <p>Multiplication of such a big number is hard.</p> <p>we can covert this as </p> <blockquote> <p>log10(A[1]<em>A[2]</em>...*A[x])- log10(A[x+1]<em>A[x+2]</em>..*A[n])<br> log10(A[1])+log10(A[2])+..+log10(A[x])-log10(A[x+1])+log10(A[x+2])+..+log10(A[n])</p> </blockquote> <p>Now these result are storable in double.</p> <p>As abs((A[1]<em>A[2]</em>...*A[x])- (A[x+1]<em>A[x+2]</em>..*A[n])) should be minimized, this equation will follow the rules of ternary search.</p> <p>So in each iternation of ternary search we need the result of </p> <blockquote> <p>log(A[1])+log(A[2])+..+log(A[x])<br> and<br> log(A[x+1])+log(A[x+2])+..+log(A[n])</p> </blockquote> <p>As there is some update, we need a data structure for finding them with lower complexity like segment tree.</p> <p>So overall complexity will be log(n)*log(n) for each query.</p>
python|c++|algorithm
1
1,908,275
45,014,195
Why doesn't the for loop execute here?
<p>I expected this code to create the <code>list_of_rows2 list</code>, then run the for loop. How come the for loop doesnt get executed? Is this just how <code>open</code> works?</p> <pre><code>infile = r"D:\temp.txt" with open(infile) as file2: list_of_rows2 = [x.split() for x in file2] for x in file2: print x </code></pre>
<p>Yes, that's how <code>open</code> works. It returns an iterator to the file object. You can only iterate over it once till exhaustion. </p> <p>The first iteration in the list comprehension exhausts the file iterator, so that by the time you're going over it again, there's nothing left to iterate over.</p> <p>This has the advantage of not loading the entire file, which could be sometimes large, all at once into memory, choking your program on memory. However, you can (if you need to) load the file into memory by calling the <code>readlines</code> method of the file object:</p> <pre><code>with open(infile) as file2: file2 = file2.readlines() # or list(file2) list_of_rows2 = [x.split() for x in file2] for x in file2: print x </code></pre> <p>Another option is to seek the file to its start position by calling <code>file2.seek(0)</code>, before iterating over it again.</p>
python|for-loop|text
5
1,908,276
61,283,826
Django UpdateView with ImageField
<p>Form validation isn't passing for some reason when i try to update a image on my model. I've also tried updating it without using <code>PIL</code> library, still doesn't work.</p> <pre><code>class UpdateProfile(UpdateView): template_name = 'dashboard/edit-profile.html' form_class = UserForm success_url = None def get_object(self, queryset=None): return User.objects.get(username=self.kwargs['username']) def form_valid(self, form): self.instance = form.save(commit=False) user = self.get_object() user.full_name = self.instance.full_name user.username = self.instance.username user.email = self.instance.email user.description = self.instance.description im = Image.new(self.instance.main_image) user.profile_image = im user.ig = self.instance.ig user.fb = self.instance.fb user.pinterest = self.instance.pinterest user.twitter = self.instance.twitter user.save() return render(self.request, self.template_name, self.get_context_data()) </code></pre> <p>Model <code>Image</code> attribute</p> <pre><code> profile_image = models.ImageField(upload_to=save_profile_image, default='/static/img/blog/avatars/user-01.jpg') def save_profile_image(instance, filename): if instance: return '{}/{}'.format(instance.id, filename) </code></pre> <p>form data from html.</p> <pre><code> &lt;form action="" class="tm-edit-product-form" method="post" enctype="multipart/form-data"&gt; &lt;div class="custom-file mt-3 mb-3"&gt; &lt;input id="fileInput" type="file" name="main_image" style="display: none" accept="image/*"/&gt; {{ form.profile_image }} &lt;/div&gt; &lt;/form&gt; </code></pre> <p>Anyway, the <code>POST</code> request comes throgh but the object isn't updated. The problem resides in the <code>ImageField</code>. Why the hell isn't it working as it should?</p>
<p>Have you tried to bind the model to the updateview: <a href="https://docs.djangoproject.com/en/3.0/ref/class-based-views/generic-editing/#updateview" rel="nofollow noreferrer">https://docs.djangoproject.com/en/3.0/ref/class-based-views/generic-editing/#updateview</a></p> <p>then you don't need the form_valid anymore</p> <pre><code>class UpdateProfile(UpdateView): template_name = 'dashboard/edit-profile.html' model = User form_class = UserForm success_url = None def get_object(self, queryset=None): return User.objects.get(username=self.kwargs['username']) </code></pre>
django|django-views|python-imaging-library|django-class-based-views
0
1,908,277
60,479,039
How can I change this code to make the progress bars appear for each file and the iteration be each loop?
<p>I am struggling with getting <code>tqdm</code>'s progress bar to stay and update as opposed to write to a new line. Note: I am using <code>multiprocessing</code> to parallelize my code, and <code>tqdm</code> is inside the function I am parallelizing. </p> <p>I added a <code>print</code> statement so the files will all appear in my terminal when running the program. Reproducible example below:</p> <pre class="lang-py prettyprint-override"><code>import multiprocessing import time from tqdm import tqdm from joblib import Parallel, delayed def run_file_analysis(text): cool = [] for i in tqdm(range(0, 10), position = 0, leave = True, desc = f'Text : {text}'): print('') cool.append(i) time.sleep(1) num_cores = multiprocessing.cpu_count() ls = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] if __name__ == "__main__": processed_list = Parallel(n_jobs=num_cores)(delayed(run_file_analysis)(i) for i in ls) </code></pre> <p>Current output: <a href="https://i.stack.imgur.com/jfzLm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jfzLm.png" alt="enter image description here"></a></p> <p>The desired output would be the ten text objects - 1, 2, 3, ... , 10 and a corresponding updating progress bar for each. Not 100 different ones. I have tried following many stackoverflow questions relating to the topic of <code>tqdm</code> and <code>multiprocessing</code> integration, but none of them are as straightforward as I would like them to be. Any help would be appreciated. </p>
<p>As already discussed in the comments, you don't want to add an extra new line with the print statement. Instead you want to use the position argument in tqdm. The use case for different threads is even mentioned in the <a href="https://tqdm.github.io/docs/tqdm/" rel="nofollow noreferrer">docs</a>.</p> <pre><code>position : int, optional Specify the line offset to print this bar (starting from 0) Automatic if unspecified. Useful to manage multiple bars at once (eg, from threads). </code></pre> <p>Currently, this argument is set to 0, so it will start the progress bar each time new. Instead you want to use the number of the thread. Because of simplicity, you can convert the given text to an integer and use this. But this is not recommended for production.</p> <pre class="lang-py prettyprint-override"><code>import multiprocessing import time from tqdm import tqdm from joblib import Parallel, delayed def run_file_analysis(text): cool = [] for i in tqdm(range(0, 10), position=int(text), leave=True, desc = f'Text : {text}'): cool.append(i) time.sleep(1) num_cores = multiprocessing.cpu_count() ls = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] if __name__ == "__main__": processed_list = Parallel(n_jobs=num_cores)(delayed(run_file_analysis)(i) for i in ls) </code></pre> <p>If the text's can not directly converted to integer, 'enumerate' can be used an the index can be passed to the function.</p> <pre class="lang-py prettyprint-override"><code>import multiprocessing import time from tqdm import tqdm from joblib import Parallel, delayed def run_file_analysis(text, job_number): cool = [] for i in tqdm(range(0, 10), position=job_number, leave=True, desc = f'Text : {text}'): cool.append(i) time.sleep(1) num_cores = multiprocessing.cpu_count() ls = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] if __name__ == "__main__": processed_list = Parallel(n_jobs=num_cores)(delayed(run_file_analysis)(text, i) for i, text in enumerate(ls)) </code></pre> <p><strong>Edit:</strong></p> <p>Some raceconditions can be reduced by setting <code>prefer='threads'</code> to the Parallel constructor:</p> <pre class="lang-py prettyprint-override"><code>if __name__ == "__main__": processed_list = Parallel(n_jobs=num_cores, prefer="threads")(delayed(run_file_analysis)(text, i) for i, text in enumerate(ls)) </code></pre>
python|python-3.x|multiprocessing|tqdm
3
1,908,278
58,062,184
Why is Python waiting, if it is not supposed to be?
<p>I made a game with Python 3 and PyGame. Now I wanted to add a new mob, which worked well, except one thing:</p> <p>I wanted to give the mob an animation, made of pictures, that switch.<br> That you see them switching I imported <code>time</code> and made this:</p> <pre class="lang-py prettyprint-override"><code>def walk(self): self.img_1 time.sleep(0.2) self.img_2 time.sleep(0.2) def update(self): # stuff self.walk() </code></pre> <p>When I run it, Python waits and hangs up. But I don't want it to wait. I just want it to wait between switching the pictures.</p>
<p><code>time.sleep()</code> pauses whatever thread runs it, so no other code will execute until the wait is completed. </p> <p>What you'll want to do is to store information on the state of the animation and change it by calling <code>time.time()</code> or something similar to measure how much time has passed and update the picture based on that.</p>
python|python-3.x|visual-studio-code|pygame
4
1,908,279
57,742,320
Getting datetime format from String?
<p>In Python there are multiple DateTime parser's which can parse a date string automatically without proving the datetime format. e.g. <a href="https://dateparser.readthedocs.io/en/v0.3.4/" rel="nofollow noreferrer">DateParser</a>, <a href="https://dateutil.readthedocs.io/en/stable/" rel="nofollow noreferrer">DateUtils</a>. However, There is no option in any of them where the format in which the date was parsed is returned. What should be done to get the format with which automatic parser's parsed the date as in the example below? e.g parse("2019/05/20") -- > [datetime(2019,5,20,0,0) , "%Y/%m/%d"]</p>
<p>If you want the format string to be able to format datetime objects the same way, I don’t think this is possible, because these parsers (at least dateparser) can parse dates that simply cannot be expressed as a format string.</p> <p>There is a <a href="https://github.com/scrapinghub/dateparser/issues/409" rel="nofollow noreferrer">feature request for it</a>, though. Maybe it can be implemented in some way, or for a subset of all possible inputs.</p> <p>If you want this for debugging purposes, to understand how a given string could cause a given datetime, I don’t think there is an easy way at the moment either. But if you are getting unexpected results, there are <a href="https://dateparser.readthedocs.io/en/latest/index.html#settings" rel="nofollow noreferrer">settings</a> you can use to influence different parsing aspects to get the desired results. Date order, input format strings and locales can make quite a difference.</p>
python|datetime|python-datetime|dateparser
1
1,908,280
56,206,579
SciKit Classification Metric
<p>I am running random forest and gradient boosting using sklearn on a classification problem.I got Classification Accuracy: 0.770 (0.048) what does the number in brackets mean?</p> <pre><code>models = [] models.append(('DT', DecisionTreeClassifier(criterion = "gini", random_state = 10, max_depth=3, min_samples_leaf=2))) models.append(('RF', RandomForestClassifier(n_estimators=500, criterion='gini', max_features='auto',min_samples_split=2))) models.append(('XT', ExtraTreesClassifier(n_estimators=500,max_features= 8,criterion= 'entropy',min_samples_split= 2, max_depth= 5, min_samples_leaf= 3))) models.append(('GB', GradientBoostingClassifier(learning_rate=0.1,n_estimators=700, min_samples_split=2,min_samples_leaf=3,max_depth=4, max_features='sqrt',subsample=0.6,random_state=10))) models.append(('ADB', AdaBoostClassifier(n_estimators=500,learning_rate=0.2,random_state=0))) # evaluate each model in turn results = [] names = [] for name, model in models: kfold = model_selection.KFold(n_splits=10, random_state=seed) cv_results = model_selection.cross_val_score(model, x_train, Y_train, cv=kfold, scoring=scoring) results.append(cv_results) names.append(name) msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print(msg) </code></pre>
<p>You are running 10-fold cross validation.</p> <p>The number in brackets is the standard deviation in the model accuracy over all 10 folds. It comes from the following line of code:</p> <pre><code>msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) </code></pre>
python|machine-learning|scikit-learn|bigdata|data-science
1
1,908,281
18,396,051
Python Regex : find zip from html content
<p>i have a email template which is having email context in html formate,</p> <p>now i wanted to find the zip number from the email html content, </p> <p>for that i have used regex to search the zip code, the content is like <strong>Formate 1:</strong></p> <pre><code>helllo this is the mail which will converted in the lead &amp;#13; and here is some addresss which will not be used.. &amp;#13; and the zip: 364001 city: New york </code></pre> <p><strong>formate 2:</strong></p> <pre><code>&lt;p&gt;&lt;b&gt;Name&lt;/b&gt;&lt;/p&gt;&lt;br/&gt; fname &lt;p&gt;&lt;b&gt;Last Name&lt;/b&gt;&lt;/p&gt;&lt;br/&gt; lname &lt;p&gt;&lt;b&gt;PLZ&lt;/b&gt;&lt;/p&gt;&lt;br/&gt; 71392 &lt;p&gt;&lt;b&gt;mail&lt;/b&gt;&lt;/p&gt;&lt;br/&gt; heliconia72@mail.com </code></pre> <p>the code looks like,</p> <pre><code>regex = r'(?P&lt;zip&gt;Zip:\s*\d\d\d\d\d\d)' zip_match = re.search(regex, mail_content) # find zip zip_match.groups()[0] </code></pre> <p>this is searching for fomate 2 only, how can i write a regex so it work for both the formate.</p>
<p>If you really need to use regex for this (I would probably use <code>BeautifulSoup</code> for the second), you could use this for example:</p> <pre><code>regex = r'(?:zip:\s*|PLZ&lt;/b&gt;&lt;/p&gt;&lt;br/&gt;\n)(\d{5})' zip_match = re.search(regex1, mail_content) zip_match.groups()[0] </code></pre>
python|regex
1
1,908,282
71,688,793
Find out the most popular male/famale name from dataframe
<p><a href="https://i.stack.imgur.com/UOTSp.png" rel="nofollow noreferrer">DaraFrame</a></p> <p>Decision which came to my mind is:</p> <pre><code>dataset['Name'].loc[dataset['Sex'] == 'female'].value_counts().idxmax() </code></pre> <p>But here is not such ordinary decision because there are names of female's husband after Mrs and i need to somehowes split it</p> <p>Input data:</p> <pre><code>df = pd.DataFrame({'Name': ['Braund, Mr. Owen Harris', 'Cumings, Mrs. John Bradley (Florence Briggs Thayer)', 'Heikkinen, Miss. Laina', 'Futrelle, Mrs. Jacques Heath (Lily May Peel)', 'Allen, Mr. William Henry', 'Moran, Mr. James', 'McCarthy, Mr. Timothy J', 'Palsson, Master. Gosta Leonard', 'Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)', 'Nasser, Mrs. Nicholas (Adele Achem)'], 'Sex': ['male', 'female', 'female', 'female', 'male', 'male', 'male', 'male', 'female', 'female'], }) Task 4: Name the most popular female name on the ship. 'some code' Output: Anna #The most popular female name Task 5: Name the most popular male name on the ship. 'some code' Output: Wilhelm #The most popular male name </code></pre>
<p>IIUC, you can use a regex to extract either the first name, or if <code>Mrs.</code> the name after the parentheses:</p> <pre><code>s = df['Name'].str.extract(r'((?:(?&lt;=Mr. )|(?&lt;=Miss. )|(?&lt;=Master. ))\w+|(?&lt;=\()\w+)', expand=False) s.groupby(df['Sex']).value_counts() </code></pre> <p>output:</p> <pre><code>Sex Name female Adele 1 Elisabeth 1 Florence 1 Laina 1 Lily 1 male Gosta 1 James 1 Owen 1 Timothy 1 William 1 Name: Name, dtype: int64 </code></pre> <p><a href="https://regex101.com/r/ZgL9vD/1" rel="nofollow noreferrer">regex demo</a></p> <p>once you have <code>s</code>, to get the most frequent female name(s):</p> <pre><code>s[df['Sex'].eq('female')].mode() </code></pre>
python|pandas
0
1,908,283
42,516,429
(django-testing) assertIs error
<p>I have tried a simple test and got this error message in the console: </p> <pre><code> AIL: test_get (navbar.test.ContextManagerTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/media/me/049C11249C1111B2/backup me/Freizeit/Django Projekte/mysitetest/lib/navbar/test.py", line 16, in test_get self.assertIs(cm.get('hi/du',0), 'hi') AssertionError: 'hi' is not 'hi' </code></pre> <p>We can see in the last line, <code>cm.get('hi/du',0)</code> returned <code>'hi'</code>. But why the test has failed than?</p> <hr> <p>First, I thaught there could be an error, but neither that code line:</p> <pre><code>self.assertIs('hi','hi') </code></pre> <p>nor this one:</p> <pre><code>self.assertIs(['hi'][0],'hi') </code></pre> <p>nor this one:</p> <pre><code>self.assertIs(cm.get('hi',0),'hi') </code></pre> <p>failed.</p> <hr> <p>For better understanding, I add the code of <code>cm.get(mypattern,number)</code>:</p> <pre><code>def get(self, mypattern, number): parts = mypattern.split('/').strip() return parts[number] </code></pre> <hr> <p>This is the code of the test that failed:</p> <pre><code>def test_get(self): cm = context.ContextManager([]) self.assertIs(cm.get('hi',0), 'hi') self.assertIs(cm.get('hi/du',0), 'hi') #this line failed self.assertIs(cm.get('hi/du',1), 'du') </code></pre> <p>It looks like there was some trouble with the <code>split()</code> function, but, at least, <code>cm.get('hi/du',0)</code> returned <code>'hi'</code>, as we can the in the stacktrace above.</p> <p>For remembering I add the relevant lines:</p> <pre><code>self.assertIs(cm.get('hi/du',0), 'hi') AssertionError: 'hi' is not 'hi' </code></pre> <hr> <p>Small detail (I don't know whether this is important): I started the test with <code>python3 manage.py test lib/navbar</code>.</p> <hr> <p>So you know why that failed? Or do you have at least some guesses? Thank your for reading this!</p>
<p>The assertion method you need is <code>assertEqual</code> not <code>assertIs</code>.</p> <p><code>assertEqual(a, b)</code>: Compares the values of a and b</p> <p><code>assertIs(a, b)</code>: Checks whether a and b point to the same object, i.e. id of both a and b is the same</p>
python|django|automated-tests|assertions|django-testing
3
1,908,284
59,314,926
Convert list of nested dictionary into dictionary in Python
<p>I have a list of nested dictionary as below. There is list inside the dictionary as well. I don't want to change the inner list but to turn the entire list into dictionary. The list is as below:</p> <pre><code>[{"id" : "A", "data" : [{"key_1" : 012},{"key_2" : 123}, {"key_3" : 234}]}] </code></pre> <p>I only want to change the list itself to dictionary without changing the inner list as below:</p> <pre><code>{{"id" : "A", "data" : [{"key_1" : 012},{"key_2" : 123}, {"key_3" : 234}]}} </code></pre> <p>Appreciate your help in this.</p>
<p>Use a dictionary comprehension and <code>zip</code> the list of dictionaries up with whatever list of keys you want. Here is an example using a subset of ascii lowercase letters:</p> <pre class="lang-py prettyprint-override"><code>{ pair[0]: pair[1] for pair in list(zip([*string.ascii_lowercase[0:len(input)]], input))} </code></pre> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; foo = [ { 'Age': 32, 'Emp_id': 'A', 'Gender': 'M', 'Result': [ {'Incentive': 3000, 'Month': 'Aug'}, {'Incentive': 3500, 'Month': 'Sep'}, {'Incentive': 2000, 'Month': 'Oct'}]}, { 'Age': 35, 'Emp_id': 'B', 'Gender': 'M', 'Result': [{'Incentive': 1500, 'Month': 'Aug'}]}, { 'Age': 31, 'Emp_id': 'C', 'Gender': 'F', 'Result': [ {'Incentive': 5000, 'Month': 'Aug'}, {'Incentive': 2400, 'Month': 'Sep'}]}] &gt;&gt;&gt; { pair[0]: pair[1] for pair in list(zip([*string.ascii_lowercase[0:len(input)]], input))} &gt;&gt;&gt; { 'a': { 'Age': 32, 'Emp_id': 'A', 'Gender': 'M', 'Result': [ {'Incentive': 3000, 'Month': 'Aug'}, {'Incentive': 3500, 'Month': 'Sep'}, {'Incentive': 2000, 'Month': 'Oct'}]}, 'b': { 'Age': 35, 'Emp_id': 'B', 'Gender': 'M', 'Result': [{'Incentive': 1500, 'Month': 'Aug'}]}, 'c': { 'Age': 31, 'Emp_id': 'C', 'Gender': 'F', 'Result': [ {'Incentive': 5000, 'Month': 'Aug'}, {'Incentive': 2400, 'Month': 'Sep'}]}} </code></pre> <p>note: you can pretty print code as follows:</p> <pre><code>import pp = pprint.PrettyPrinter(indent=4) pp.pprint(data) </code></pre>
json|python-3.x|dictionary
0
1,908,285
59,114,683
Python Code that returns true while key is pressed down false if release?
<p>I need a code in python that returns an if statement to be true if a key is pressed and held down and false if it is released. I would like this code to be able to be executed whenever the key is pressed and held down. </p>
<p>On some systems keyboard can repeate sending key event when it is pressed so with <code>pynput</code> you would need only this (for key 'a')</p> <pre><code>from pynput.keyboard import Listener, KeyCode def get_pressed(event): #print('pressed:', event) if event == KeyCode.from_char('a'): print("hold pressed: a") with Listener(on_press=get_pressed) as listener: listener.join() </code></pre> <p>But sometimes repeating doesn't work or it need long time to repeate key and they you can use global variable for key to keep True/False</p> <pre><code>from pynput.keyboard import Listener, KeyCode import time # --- functions --- def get_pressed(event): global key_a # inform function to use external/global variable instead of local one if event == KeyCode.from_char('a'): key_a = True def get_released(event): global key_a if event == KeyCode.from_char('a'): key_a = False # --- main -- key_a = False # default value at start listener = Listener(on_press=get_pressed, on_release=get_released) listener.start() # start thread with listener while True: if key_a: print('hold pressed: a') time.sleep(.1) # slow down loop to use less CPU listener.stop() # stop thread with listener listener.join() # wait till thread ends work </code></pre>
python|if-statement|while-loop
0
1,908,286
53,923,310
How to convert string to list of numbers
<p>I have a problem of converting list from string to numbers in Python.</p> <p>I read a file and need to extract the coordinate data from it.</p> <p>The file contains these coordinates:</p> <pre><code>(-5 -0.005 -5) (-4.9 -0.005 -5) (-4.8 -0.005 -5) (-4.7 -0.005 -5) (-4.6 -0.005 -5) (-4.5 -0.005 -5) (-4.4 -0.005 -5) (-4.3 -0.005 -5) (-4.2 -0.005 -5) (-4.1 -0.005 -5) </code></pre> <p>First, I read the file and get the coordinates using this code:</p> <pre><code>f = open("text.txt", 'r') if f.mode == 'r': contents = f.readlines() </code></pre> <p>After that, if i called contents[0], it showed (-5 -0.005 -5) as a string.</p> <p>I tried manipulating the contents.</p> <pre><code>coor = contents[0] # picking 1 list of coordinates allNumber = coor[1:-2] # delete the open and close brackets print(list(map(int, allNumber))) # hopefully get the integers mapped into x, y, and z coordinates :( </code></pre> <p>I got results like this:</p> <pre><code>ValueError: invalid literal for int() with base 10: '-' </code></pre> <p>I want something like <code>[-5, -0.005, -5]</code> so I can extract each number inside it.</p>
<p>You can do it like this:</p> <pre><code>with open('test.txt') as f: lines = (line.strip()[1:-1] for line in f) values = (tuple(map(float, line.split())) for line in lines) data = list(values) print(data) # [(-5.0, -0.005, -5.0), (-4.9, -0.005, -5.0), (-4.8, -0.005, -5.0), # (-4.7, -0.005, -5.0), (-4.6, -0.005, -5.0), (-4.5, -0.005, -5.0), # (-4.4, -0.005, -5.0), (-4.3, -0.005, -5.0), (-4.2, -0.005, -5.0), (-4.1, -0.005, -5.0)] </code></pre> <p>Use <code>with open()...</code> to make sure that the file gets closed whatever happens.</p> <p><code>lines</code> is a generator, it iterates on the lines of the file and yields each line stripped of the newline, after cutting the first and last character, the parenthesis.</p> <p><code>values</code> generate a tuple for each of these cleaned lines, by splitting it and turning the values to floats, as they aren't all integers.</p> <p>We then make a list out of it.</p>
python|python-3.x|parsing
0
1,908,287
58,515,437
What is the difference between None and boolean (True, False) in python's default argument values?
<p>In function definitions, one can define a boolean default argument's values as <code>argument=None</code> or <code>argument=False</code>.</p> <p>An example from pandas concat:</p> <pre><code>def concat( objs, axis=0, join="outer", join_axes=None, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=None, copy=True, ): </code></pre> <p>While both usages can be found, why would one be using one over the other? </p> <p>Is there any PEP on this?</p>
<p><code>True</code> and <code>False</code> are specific <code>bool</code> values. Use default <code>False</code> when you have a <code>bool</code> field and you want the default to be <code>False.</code>Don't use <code>False</code> as a value for a non-<code>bool</code> field.</p> <p><code>None</code> is used as a generic placeholder when the value will be set later. It can be typed as <code>Optional[T]</code>, which is equivalent to <code>Union[T, None]</code>.</p> <p>You might be thinking of <code>None</code> and <code>False</code> as similar because they're both "falsy" (<code>bool(x)</code> returns <code>False</code>), but the same is true of several other values, <code>[] () {} 0 0.0</code>, etc and we don't use them like <code>None</code> either.</p> <p>In your example, <code>True</code>/<code>False</code> are used where the field takes a boolean value. <code>None</code> is used where the field takes an <code>Optional[List]</code>. (The exception is <code>sort: Optional[bool]</code>, which is being used temporarily as an ad-hoc compatibility tool for a deprecated behavior.)</p>
python
11
1,908,288
58,493,003
Can't compare a list of strings with a datetime object
<p>I imported a worksheet from a google sheets which happens to have a timestamp in string format in the ['Timestamp'] column. To filter the date by comparison and select some rows, I've created a variable which takes today's date (diaHoy) and another which is from the day before (diaAyer)</p> <p>Then I'm trying to apply a mask which compares diaHoy and diaAyer with each timestamp element, but I can't because diaHoy and diaAyer are datetime elements and each timestamp cell is a string. I've tried applying strptime to ['Timestamp'] column but i can't because it's a list</p> <p>Sample data:</p> <pre><code>df = pd.DataFrame ({'16/10/2019 14:56:36':['A','B'],'21/10/2019 14:56:36':['C','D'],'21/10/2019 14:56:36':['E','F'] diaHoy = 2019/10/21 diaAyer = 2019/10/20 </code></pre> <pre><code>import pandas as pd diaHoy = datetime.today().date() diaAyer = diaHoy + timedelta(days = -1) wks1 = gc.open_by_url("CODE_URL").sheet1 df1 = wks1.get_all_values() df1.pop(0) mask1 = (df1 &gt; diaAyer) &amp; (df1 &lt;= diaHoy) pegado1 = df1.loc[mask1] </code></pre> <p>I expect that the mask filters out rows by the dates in the first column, by comparing them with diaHoy and diaAyer</p> <p>Filter: between 21/10/2019 and 20/10/2019</p> <p>Expected result:</p> <pre><code>df = pd.DataFrame ({'21/10/2019 14:56:36':['C','D'],'21/10/2019 14:56:36':['E','F'] </code></pre>
<p>you can convert the tuple of timestamp strings to a list of datetime objects:</p> <pre><code>import pandas as pd df2 = pd.DataFrame({pd.to_datetime(key):df[key] for key in df}) </code></pre>
python|pandas|datetime|gspread
0
1,908,289
45,469,327
How to create computed field in Odoo Studio using Python code?
<p>I am using <code>Studio in Odoo version 10.0</code>. I successfully created the field with the name <code>x_studio_field_dZVpy</code> that appears in the <code>product.template</code> GUI. </p> <p>When I try to edit the product name in the <code>product.template</code> GUI it gives me a <code>Value Error: forbidden opcode(s) in 'lambda'</code>.</p> <p>I checked the "readonly" and "stored" check boxes. In the "dependencies" field I entered "name". I entered the following into the "compute" field in "Advanced Properties" section of the field. </p> <p>I entered the following into the "compute" field in "Advanced Properties" section of the field. </p> <pre><code>def compute_product_dimension(self): for record in self: if product.name[:2] == 'LG': product_specs = product.name.split('-') product_dimension = float(product_specs[6]) x_studio_field_dZVpy = product_dimension / 2 else: x_studio_field_dZVpy = "" </code></pre> <p>For example</p> <pre><code>product.name= LG-611-40M-3UM-95P-8.000 </code></pre> <p>If the first 2 characters of the <em>product.name</em> is "LG" the code splits the string into an array and divides the 6th element in the array by 2. In this example this should divide 8.000 by 2. The "x_studio_field_dZVpy" field should then display 4.000.</p> <p><img src="https://i.stack.imgur.com/t15x0.jpg" alt="screenshot of Odoo Studio GUI with code"></p>
<p>Instead of: </p> <pre><code>for record in self: if name[:2] == 'LG': </code></pre> <p>Try:</p> <pre><code>for product in self: if product.name[:2] == 'LG': </code></pre>
python|openerp|field|odoo-10
1
1,908,290
45,537,312
Extract dates in different formats from string using regex in python
<p>I need to extract dates from strings using regex in python and the dates can be in one of many formats, and between some random text.</p> <p>The date formats are:</p> <pre><code>04/20/2009; 04/20/09; 4/20/09; 4/3/09 Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009; 20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009 Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009 Feb 2009; Sep 2009; Oct 2010 6/2008; 12/2009 2009; 2010 </code></pre> <p>After extract the dates I need to sort them ascending.</p> <p>I've tried to use those 6 regex patterns but it seems that it's not doing all the job.</p> <pre><code>pattern1 = r'((?:\d{1,2}[- ,./]*)(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*[- ,./]*\d{4})' pattern2 = r'((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*[ ,./-]*\d{1,2}[ ,./-]*\d{4})' pattern3 = r'((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*[ ,./-]*\d{4})' pattern4 = r'((?:\d{1,2}[/-]\d{1,2}[/-](?:\d{4}|\d{2})))' pattern5 = r'(?:(\s\d{2}[/-](?:\d{4})))' pattern6 = r'(?:\d{4})' </code></pre>
<p>It might be useful to set up some intermediate variables.</p> <pre><code>import re short_month_names = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ) long_month_names = ( 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ) short_month_cap = '(?:' + '|'.join(short_month_names) + ')' long_month_cap = '(?:' + '|'.join(long_month_names) + ')' short_num_month_cap = '(?:[1-9]|1[12])' long_num_month_cap = '(?:0[1-9]|1[12])' long_day_cap = '(?:0[1-9]|[12][0-9]|3[01])' short_day_cap = '(?:[1-9]|[12][0-9]|3[01])' long_year_cap = '(?:[0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3})' short_year_cap = '(?:[0-9][0-9])' ordinal_day = '(?:2?1st|2?2nd|2?3rd|[12]?[4-9]th|1[123]th|[123]0th|31st)' formats = ( r'(?P&lt;month_0&gt;{lnm}|{snm})/(?P&lt;day_0&gt;{ld}|{sd})/(?P&lt;year_0&gt;{sy}|{ly})', r'(?P&lt;month_1&gt;{sm})\-(?P&lt;day_1&gt;{ld}|{sd})\-(?P&lt;year_1&gt;{ly})', r'(?P&lt;month_2&gt;{sm}|{lm})(?:\.\s+|\s*)(?P&lt;day_2&gt;{ld}|{sd})(?:,\s+|\s*)(?P&lt;year_2&gt;{ly})', r'(?P&lt;day_3&gt;{ld}|{sd})(?:[\.,]\s+|\s*)(?P&lt;month_3&gt;{lm}|{sm})(?:[\.,]\s+|\s*)(?P&lt;year_3&gt;{ly})', r'(?P&lt;month_4&gt;{lm}|{sm})\s+(?P&lt;year_4&gt;{ly})', r'(?P&lt;month_5&gt;{lnm}|{snm})/(?P&lt;year_5&gt;{ly})', r'(?P&lt;year_6&gt;{ly})', r'(?P&lt;month_6&gt;{sm})\s+(?P&lt;day_4&gt;(?={od})[0-9][0-9]?)..,\s*(?P&lt;year_7&gt;{ly})' ) _pattern = '|'.join( i.format( sm=short_month_cap, lm=long_month_cap, snm=short_num_month_cap, lnm=long_num_month_cap, ld=long_day_cap, sd=short_day_cap, ly=long_year_cap, sy=short_year_cap, od=ordinal_day ) for i in formats ) pattern = re.compile(_pattern) def get_fields(match): if not match: return None return { k[:-2]: v for k, v in match.groupdict().items() if v is not None } tests = r'''04/20/2009; 04/20/09; 4/20/09; 4/3/09 Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009 20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009 Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009 Feb 2009; Sep 2009; Oct 2010 6/2008; 12/2009 2009; 2010''' for test_line in tests.split('\n'): for test in test_line.split('; '): print('{!r}: {!r}'.format(test, get_fields(pattern.fullmatch(test)))) print('') </code></pre> <p>Which outputs:</p> <pre><code>'04/20/2009': {'month': '04', 'day': '20', 'year': '2009'} '04/20/09': {'month': '04', 'day': '20', 'year': '09'} '4/20/09': {'month': '4', 'day': '20', 'year': '09'} '4/3/09': {'month': '4', 'day': '3', 'year': '09'} 'Mar-20-2009': {'month': 'Mar', 'day': '20', 'year': '2009'} 'Mar 20, 2009': {'month': 'Mar', 'day': '20', 'year': '2009'} 'March 20, 2009': {'month': 'March', 'day': '20', 'year': '2009'} 'Mar. 20, 2009': {'month': 'Mar', 'day': '20', 'year': '2009'} 'Mar 20 2009': {'month': 'Mar', 'day': '20', 'year': '2009'} '20 Mar 2009': {'day': '20', 'month': 'Mar', 'year': '2009'} '20 March 2009': {'day': '20', 'month': 'March', 'year': '2009'} '20 Mar. 2009': {'day': '20', 'month': 'Mar', 'year': '2009'} '20 March, 2009': {'day': '20', 'month': 'March', 'year': '2009'} 'Mar 20th, 2009': {'month': 'Mar', 'day': '20', 'year': '2009'} 'Mar 21st, 2009': {'month': 'Mar', 'day': '21', 'year': '2009'} 'Mar 22nd, 2009': {'month': 'Mar', 'day': '22', 'year': '2009'} 'Feb 2009': {'month': 'Feb', 'year': '2009'} 'Sep 2009': {'month': 'Sep', 'year': '2009'} 'Oct 2010': {'month': 'Oct', 'year': '2010'} '6/2008': {'month': '6', 'year': '2008'} '12/2009': {'month': '12', 'year': '2009'} '2009': {'year': '2009'} '2010': {'year': '2010'} </code></pre> <p>The main part is the <code>formats</code> variable, where all the different formats are defined. It matches slightly more than what is defined, and can easily be extended.</p> <p>The overall pattern ends up being:</p> <pre><code>'(?P&lt;month_0&gt;(?:0[1-9]|1[12])|(?:[1-9]|1[12]))/(?P&lt;day_0&gt;(?:0[1-9]|[12][0-9]|3[01])|(?:[1-9]|[12][0-9]|3[01]))/(?P&lt;year_0&gt;(?:[0-9][0-9])|(?:[0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3}))|(?P&lt;month_1&gt;(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\\-(?P&lt;day_1&gt;(?:0[1-9]|[12][0-9]|3[01])|(?:[1-9]|[12][0-9]|3[01]))\\-(?P&lt;year_1&gt;(?:[0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3}))|(?P&lt;month_2&gt;(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)|(?:January|February|March|April|May|June|July|August|September|October|November|December))(?:\\.\\s+|\\s*)(?P&lt;day_2&gt;(?:0[1-9]|[12][0-9]|3[01])|(?:[1-9]|[12][0-9]|3[01]))(?:,\\s+|\\s*)(?P&lt;year_2&gt;(?:[0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3}))|(?P&lt;day_3&gt;(?:0[1-9]|[12][0-9]|3[01])|(?:[1-9]|[12][0-9]|3[01]))(?:[\\.,]\\s+|\\s*)(?P&lt;month_3&gt;(?:January|February|March|April|May|June|July|August|September|October|November|December)|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))(?:[\\.,]\\s+|\\s*)(?P&lt;year_3&gt;(?:[0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3}))|(?P&lt;month_4&gt;(?:January|February|March|April|May|June|July|August|September|October|November|December)|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\\s+(?P&lt;year_4&gt;(?:[0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3}))|(?P&lt;month_5&gt;(?:0[1-9]|1[12])|(?:[1-9]|1[12]))/(?P&lt;year_5&gt;(?:[0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3}))|(?P&lt;year_6&gt;(?:[0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3}))|(?P&lt;month_6&gt;(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\\s+(?P&lt;day_4&gt;(?=(?:2?1st|2?2nd|2?3rd|[12]?[4-9]th|1[123]th|[123]0th|31st))[0-9][0-9]?)..,\\s*(?P&lt;year_7&gt;(?:[0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3}))' </code></pre> <p>Which would have been virtually impossible to write by hand.</p> <p>The bounds for the "between random text" can be added around <code>_pattern</code>.</p> <p>I would suggest <code>_pattern = r'\b(?:{})\b'.format(_pattern)</code>.</p>
python|regex|pandas
3
1,908,291
45,570,661
Parse Nagios / Icinga Config with Python Regex
<p>I'm trying to parse a Nagios / Icinga config so I can do further processing on it with Python. Since I could not find a working library to do that (<a href="http://pynag.org/" rel="nofollow noreferrer">pynag</a> does not seem to work at all), I'm trying to write a simple Python script using regexes to do so.</p> <p>Basically I want to get from this configfile (it uses tabs for indentation):</p> <pre><code>define host { address 123.123.123.123 passive_checks_enabled 1 } define service { service_description Crondaemon check_command check_nrpe_1arg!check_crondaemon } </code></pre> <p>to something like this Python tuple:</p> <pre><code>( ('host', ('address', '123.123.123.123'), ('passive_checks_enabled', '1')), ('service', ('service_description', 'Crondaemon'), ('check_command', 'check_nrpe_1arg!check_crondaemon')) ) </code></pre> <p>This is my full script with parsing logic including an example to test:</p> <pre><code>import re # white spaces are tabs! TEST_STR = """ define host { address 123.123.123.123 passive_checks_enabled 1 } define service { service_description Crondaemon check_command check_nrpe_1arg!check_crondaemon } """ cfg_all_regex = re.compile( r'define\s+(\w+)\s*\{' '(.*?)' '\t}', re.DOTALL ) # basic regex works print(re.findall(cfg_all_regex, TEST_STR)) cfg_all_regex = re.compile( r'define\s+(\w+)\s*{\n' '(\t(.*)?\t(.*)?\n)*' '\t}', re.DOTALL ) # more specific regex to extract all key values fails print(re.findall(cfg_all_regex, TEST_STR)) </code></pre> <p>Unfortunately I cannot get the full parsing to work, it always matches everything or nothing. Can you please give me a hint how to fix my regex so I can extract all key value pairs from my Icinga config?</p>
<p>re module doesn't support repeated captures, so </p> <pre><code>'(\t(.*)?\t(.*)?\n)*' </code></pre> <p>only preserves last group capture. </p> <p>Likewise I would transform this like that</p> <pre><code>'\t(\w+)\s+([^\n]*)\n\' </code></pre> <p>So a possible solution, given the structure of your data, can be creates a regular expression that will match either pattern:</p> <pre><code>regex = r'define\s+(\w+)\s+\{\n|\t(\w+)\s+([^\n]*)\n|\t\}' matches = re.finditer(regex, TEST_STR, re.DOTALL) </code></pre> <p>With a for loop you can iterate over the groups</p> <pre><code>for match in matches: for groupNum in range(0, len(match.groups())): groupNum = groupNum + 1 if match.group(groupNum): print("Group {}: {}".format(groupNum, match.group(groupNum))) </code></pre> <p>return:</p> <pre><code>Group 1: host Group 2: address Group 3: 123.123.123.123 Group 2: passive_checks_enabled Group 3: 1 Group 1: service Group 2: service_description Group 3: Crondaemon Group 2: check_command Group 3: check_nrpe_1arg!check_crondaemon </code></pre>
python|regex|nagios|icinga
1
1,908,292
56,908,269
Problem with my odoo installation on ubuntu server
<p>After installing odoo 12 on ubuntu server I tried to check odoo status with systemctl status odoo. Here's what I got in the output:</p> <pre><code>odoo.service - Odoo Open Source ERP and CRM Loaded: loaded (/lib/systemd/system/odoo.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Fri 2019-07-05 21:04:51 CEST; 10s ago Process: 10541 ExecStart=/usr/bin/odoo --config /etc/odoo/odoo.conf --logfile /var/log/odoo/odoo-server.log (code=exited, status=1/FAILURE Main PID: 10541 (code=exited, status=1/FAILURE) Jul 05 21:04:51 vps706653 odoo[10541]: from . import db, graph, loading, migration, module, registry Jul 05 21:04:51 vps706653 odoo[10541]: File "/usr/lib/python3/dist-packages/odoo/modules/loading.py", line 17, in Jul 05 21:04:51 vps706653 odoo[10541]: import odoo.modules.migration Jul 05 21:04:51 vps706653 odoo[10541]: File "/usr/lib/python3/dist-packages/odoo/modules/migration.py", line 12, in Jul 05 21:04:51 vps706653 odoo[10541]: from odoo.modules.module import get_resource_path Jul 05 21:04:51 vps706653 odoo[10541]: File "/usr/lib/python3/dist-packages/odoo/modules/module.py", line 12, in Jul 05 21:04:51 vps706653 odoo[10541]: import pkg_resources Jul 05 21:04:51 vps706653 odoo[10541]: ModuleNotFoundError: No module named 'pkg_resources' Jul 05 21:04:51 vps706653 systemd[1]: odoo.service: Main process exited, code=exited, status=1/FAILURE Jul 05 21:04:51 vps706653 systemd[1]: odoo.service: Failed with result 'exit-code'. </code></pre> <p>Please help<br> Thanks</p>
<p>It seems you are missing <code>pkg_resources</code>. So to install the module <code>pkg_resources</code>(which is part of <code>setuptools</code>) on your server, you can do this with <code>pip install setuptools</code>. </p>
python|ubuntu|odoo
0
1,908,293
25,875,131
Python:Write list value into the file
<p>Need help in the below code:</p> <pre><code>langs=['C','Java','Cobol','Python'] f1=open('a.txt','r') f2=open('abc.txt','w') for index in range(len(langs)): for line in f1: f2.write(line.replace('Frst languag','langs[index]')) f1.close() f2.close() </code></pre> <p>Line #4: Not sure if the syntax is correct, all i want is the loop to run for n number of times where n is no. of values inside the list.</p> <p>Line 6: All I need is everytime the loop to run and each time <code>langs[0]</code> value #should be written to the file, then <code>langs[1]</code> value and so on...</p>
<pre><code>f2.write(line.replace('Frst languag','{}'.format(langs[index])) </code></pre>
python
1
1,908,294
25,493,766
pyodbc fetchall() returns no results when a column returned by the query contains too much data
<p>Setup:I am using Python 3.3 on a Windows 2012 client. I have a select query running using <a href="https://code.google.com/p/pyodbc/" rel="nofollow">pyodbc</a> which is not returning any results via fetchall(). I know the query works fine because i can take it out and run it from Microsoft SQL Management Studio without any issues.<br> I can also remove one column from the select list and the query will return results. For the database row in question, this column contains a large amount of XML data (> 10,000 characters), so it seems as though there is some buffer overflow issue going on causing fetchall() to fail, though it doesn't throw any exceptions. I have tried googling around and i have seen rumors of a config option to raise the buffer size, but i haven't been able to nail down exactly how to do it, or what a workaround would be. </p> <p>Is there a configuration option that I can use, or any alternative to pyodbc.</p> <blockquote> <p>Disclaimer: I have only been using python for about 2 weeks now so i am still quite the noob, though i have made every attempt to research my problems thoroughly this one has proven to be elusive:</p> </blockquote> <p>On a side note, i tried using odbc instead of pyodbc but the same query throws this oddball error which google isn't helping me solve either</p> <blockquote> <p>[ERROR] An exception while executing the Select query: [][Negative size passed to PyBytes_FromStringAndSize]</p> </blockquote>
<p>It seems this issue was resolved by changing my SQL connection string</p> <p>FROM:</p> <pre><code>DRIVER={SQL Server Native Client 11.0} </code></pre> <p>TO:</p> <pre><code>DRIVER={SQL Server} </code></pre>
python-3.x|pyodbc
1
1,908,295
44,819,073
Launch python file from PHP on LINUX server
<p>I tried many solutions but nothing it works :</p> <pre><code>echo '&lt;pre&gt;'; shell_exec("python /home/folder/python/mapfile_compress.py"); shell_exec("sudo -u wwwexec python escapeshellcommand(/home/folder/python/mapfile_compress.py) $uid"); shell_exec("sudo chmod +x /home/folder/python/mapfile_compress.py"); system("bash /home/folder/python/mapfile_compress.py"); passthru("bash /home/folder/python/mapfile_compress.py"); passthru("/home/folder/python/mapfile_compress.py"); exec("bash /home/folder/python/mapfile_compress.py"); echo '&lt;/pre&gt;'; </code></pre> <p>I launched indivdually them but in all cases, Firebug returned : <code>'&lt;pre&gt;'</code></p> <p>So I tried this code founded on Stack Overflow :</p> <p><code>$command = escapeshellcmd('chmod +x /home/folder/python/mapfile_compress_test.py'); echo $command; $output = shell_exec($command); echo $output;</code></p> <p>But firebug returned nothing. My python file begin with <code>#!/usr/bin/env python</code> and if I launch it on server that works !</p> <p>Do you knwo how can I launch my python file from PHP file ?</p>
<p><code>chmod</code> will return 0 on success and > 0 on error.</p> <p>Make sure that the file is able to run by just executing it as the web user. When +x is properly set, you can execute it by just calling <code>$ /path/to/your/file.py</code>, the shebang in the first line in your script <code>#!/usr/bin/env python</code> should define the correct python based on your env.</p> <p>You can test this by running:</p> <pre><code>$ /usr/bin/env python /path/to/your/file.py </code></pre> <p>So check your file permissions to check if the file is executable by the user that runs the php script.</p> <p>Just to test, you can just print a few lines in your python file </p> <pre><code>#!/usr/bin/env python print "test line 1" print "test line 2" </code></pre> <p>Then if you have verified permissions and the correct use of python, you can do this in your php.</p> <pre><code>$command = escapeshellcmd('/path/to/your/file.py'); $output = shell_exec($command); // get all output or use passthrough, exec will only return the last line. echo "&lt;pre&gt;{$output}&lt;/pre&gt;; </code></pre>
php|python|linux
1
1,908,296
24,108,063
matplotlib two different colors in the same annotate
<p>I am trying to create a figure in python and make is so that the same annonate text will have two colors, half of the annonate will be blue and the other half will be red.</p> <p>I think the code explain itself. I have 3 lines 1 green with green annonate, 1 blue with blue annonate. </p> <p>The 3rd is red its the summation of plot 1 and plot 2, and I want it to have half annonate blue and half green.</p> <p>ipython -pylab</p> <pre><code>x=arange(0,4,0.1) exp1 = e**(-x/5) exp2 = e**(-x/1) exp3 = e**(-x/5) +e**(-x/1) figure() plot(x,exp1) plot(x,exp2) plot(x,exp1+exp2) title('Exponential Decay') annotate(r'$e^{-x/5}$', xy=(x[10], exp1[10]), xytext=(-20,-35), textcoords='offset points', ha='center', va='bottom',color='blue', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='-&gt;', connectionstyle='arc3,rad=0.95', color='b')) annotate(r'$e^{-x/1}$', xy=(x[10], exp2[10]), xytext=(-5,20), textcoords='offset points', ha='center', va='bottom',color='green', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='-&gt;', connectionstyle='arc3,rad=-0.5', color='g')) annotate(r'$e^{-x/5} + e^{-x/1}$', xy=(x[10], exp2[10]+exp1[10]), xytext=(40,20), textcoords='offset points', ha='center', va='bottom', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='-&gt;', connectionstyle='arc3,rad=-0.5', color='red')) </code></pre> <p>Is it possible?</p>
<p>You can use <code>r'$\textcolor{blue}{e^{-x/5}} + \textcolor{green}{e^{-x/1}}$'</code> to make the text half blue, half green. Using your own code for example:</p> <p><a href="https://i.stack.imgur.com/hxUlU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hxUlU.png" alt="enter image description here"></a></p> <p>The image is generated by the following code. Testd with matplotlib v2.1.2 with the default <code>matplotlibrc</code> settings.</p> <pre><code>import matplotlib as matplotlib matplotlib.use('pgf') matplotlib.rc('pgf', texsystem='pdflatex') # from running latex -v preamble = matplotlib.rcParams.setdefault('pgf.preamble', []) preamble.append(r'\usepackage{color}') from numpy import * from matplotlib.pyplot import * x=arange(0,4,0.1) exp1 = e**(-x/5) exp2 = e**(-x/1) exp3 = e**(-x/5) +e**(-x/1) figure() plot(x,exp1) plot(x,exp2) plot(x,exp1+exp2) title('Exponential Decay') annotate(r'$e^{-x/5}$', xy=(x[10], exp1[10]), xytext=(-20,-25), textcoords='offset points', ha='center', va='bottom',color='blue', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='-&gt;', connectionstyle='arc3,rad=0.95', color='b')) annotate(r'$e^{-x/1}$', xy=(x[10], exp2[10]), xytext=(25,20), textcoords='offset points', ha='center', va='bottom',color='green', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='-&gt;', connectionstyle='arc3,rad=-0.5', color='g')) annotate(r'$\textcolor{blue}{e^{-x/5}} + \textcolor[rgb]{0.0, 0.5, 0.0}{e^{-x/1}}$', xy=(x[10], exp2[10]+exp1[10]), xytext=(40,20), textcoords='offset points', ha='center', va='bottom', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='-&gt;', connectionstyle='arc3,rad=-0.5', color='red')) savefig('test.png') </code></pre> <p>It is mainly your code with the following changes:</p> <ol> <li>You need to use a <code>pgf</code> backend.</li> <li>Usepackage <code>color</code> in <code>pgf.preamble</code></li> <li>There's some overlapping with the 1st and 2nd annotations, so <code>xytext</code> is changed.</li> <li>The <code>color='g'</code> in te 2nd annotation actually didn't use the pure "Green" color like (0, 255, 0) of rgb. <code>\textcolor[rgb]{0.0, 0.5, 0.0}</code> makes it looking alike.</li> </ol>
python|matplotlib
24
1,908,297
36,112,273
Disable order email in Django-oscar
<p>I built a simple e-commerce site with django-oscar.</p> <p>After a successful order placement an email is sent to client regardless of settings. I found the code located at <code>oscar/apps/customer/utils.py:Dispatcher.dispatch_order_messages</code></p> <p>Is it possible to turn this behavior off?</p>
<p>You should fork the <code>checkout</code> app (as described <a href="https://django-oscar.readthedocs.org/en/releases-1.1/topics/customisation.html#fork-the-oscar-app" rel="nofollow">here</a>) and override the <code>handle_successful_order</code> method of the <code>OrderPlacementMixin</code>. You can copy the code from the oscar app and simply comment out the line where the confirmation message is sent.</p> <pre><code># self.send_confirmation_message(order, self.communication_type_code) </code></pre>
python|django|e-commerce|django-oscar
3
1,908,298
15,307,531
Getting Input from Radiobutton
<p>I am using a mix of Tkinter and graphics.py (a wrapper on Tkinter) to create a fairly basic integrator (find the area under a graph) with a GUI. As of now, the main "control panel" for the integrator is separate from the actual graph (which is made by using graphics.py). I am using Tkinter's <code>Radiobutton()</code> for the choice selection of the integration type (Left Rectangular, Right Rectangular, Trapezoidal, or Simpson's Approximation).</p> <p>My problem is that I am unable to get the output from the radiobuttons. I was using the example from <a href="http://www.tutorialspoint.com/python/tk_radiobutton.htm" rel="nofollow noreferrer">TutorialsPoint: Tkinter Radiobutton</a>.</p> <p>Here is my code:</p> <pre><code>class FunctionInput: def __init__(self, master, window, items): self.window = window self.items = items self.runProgram = True self.typeChoice = tk.StringVar() self.frame = tk.Frame(master) self.typeFrame = tk.Frame(self.frame) self.quitButton = tk.Button(self.frame, text = 'Quit', command = self.frame.quit) self.optLabel = tk.Label(self.frame, text = 'Type of Approximation: ') self.optL = tk.Radiobutton(self.typeFrame, text = 'Left Rectangular', variable = self.typeChoice, value = 'l') self.optR = tk.Radiobutton(self.typeFrame, text = 'Right Rectangular', variable = self.typeChoice, value = 'r') self.optT = tk.Radiobutton(self.typeFrame, text = 'Trapezoidal', variable = self.typeChoice, value = 't') self.optS = tk.Radiobutton(self.typeFrame, text = 'Simpsons Rule', variable = self.typeChoice, value = 's') self.optL.grid(row = 1, column = 1, padx = 5, pady = 5) self.optR.grid(row = 1, column = 2, padx = 5, pady = 5) self.optT.grid(row = 2, column = 1, padx = 5, pady = 5) self.optS.grid(row = 2, column = 2, padx = 5, pady = 5) self.optLabel.grid(row = 4) self.typeFrame.grid(row = 5) self.quitButton.grid(row = 6) # there were numerous other widgets and frames, but I only included the relevant ones self.frame.grid() def getInput(self): type_integration = self.typeChoice.get() self.frame.quit() return type_integration def main(): # some other code, win and axisLabels are defined prior to this root = tk.Tk(className = ' Function Grapher') app = FunctionInput(root, win, axisLabels) root.rowconfigure(0, weight = 1) root.columnconfigure(0, weight = 1) root.mainloop() # there is a button to exit the mainloop in my GUI typeIntegration = app.getInput() print typeIntegration # trying to debug it if __name__ == '__main__': main() </code></pre> <p>However, it doesn't not print the variable. It prints an empty string, so execution is not a problem. <code>root.mainloop()</code> does not get stuck in an infinite loop, because I have a button in my GUI (not shown here because it is irrelevant) that exits it. An error is not raised, so I'm guessing that the issue is with setting the option to the variable. Any help is greatly appreciated.</p> <p>Also, on a side note, whenever I run the program, the 'Right Rectangular', 'Trapezoidal', and 'Simpson's Rule' radiobuttons are grayed out, like such: </p> <p><img src="https://i.stack.imgur.com/dUjFJ.jpg" alt=""></p> <p>This grayness goes away if I click on one of the radiobuttons, but until then, it stays. If there is some way to fix this, please let me know.</p> <p>Thanks!</p>
<p>The problem was that since I was using multiple other widgets, I had to set <code>StringVar()</code>s <code>master</code> parameter as <code>self.typeFrame</code>:</p> <pre><code>class FunctionInput: def __init__(self, master, window, items): self.window = window self.items = items self.runProgram = True self.frame = tk.Frame(master) self.typeFrame = tk.Frame(self.frame) self.typeChoice = tk.StringVar(self.typeFrame) self.quitButton = tk.Button(self.frame, text = 'Quit', command = self.frame.quit) self.optLabel = tk.Label(self.frame, text = 'Type of Approximation: ') self.optL = tk.Radiobutton(self.typeFrame, text = 'Left Rectangular', variable = self.typeChoice, value = 'l') self.optR = tk.Radiobutton(self.typeFrame, text = 'Right Rectangular', variable = self.typeChoice, value = 'r') self.optT = tk.Radiobutton(self.typeFrame, text = 'Trapezoidal', variable = self.typeChoice, value = 't') self.optS = tk.Radiobutton(self.typeFrame, text = 'Simpsons Rule', variable = self.typeChoice, value = 's') self.optL.grid(row = 1, column = 1, padx = 5, pady = 5) self.optR.grid(row = 1, column = 2, padx = 5, pady = 5) self.optT.grid(row = 2, column = 1, padx = 5, pady = 5) self.optS.grid(row = 2, column = 2, padx = 5, pady = 5) self.optLabel.grid(row = 4) self.typeFrame.grid(row = 5) self.quitButton.grid(row = 6) # there were numerous other widgets and frames, but I only included the relevant ones self.frame.grid() def getInput(self): type_integration = self.typeChoice.get() self.frame.quit() return type_integration def main(): # some other code, win and axisLabels are defined prior to this root = tk.Tk(className = ' Function Grapher') app = FunctionInput(root, win, axisLabels) root.rowconfigure(0, weight = 1) root.columnconfigure(0, weight = 1) root.mainloop() # there is a button to exit the mainloop in my GUI print app.getInput() if __name__ == '__main__': main() </code></pre> <p>Also, as @A. Rodas said, to get rid of the grayness, I did:</p> <pre><code>self.typeFrame = tk.Frame(self.frame) self.typeChoice = tk.StringVar(self.typeFrame) self.typeChoice.set(None) </code></pre>
python|tkinter
1
1,908,299
15,253,412
SQLAlchemy Installation in PyPy
<p>I have a database project that could greatly benefit from the speed boost PyPy provides. I have been unable to install one of the core libraries I am using, sqlalchemy, under PyPy, however. I drop it into the Site-Packges directory but then PyPy squawks at me, saying it also needs PyODBC, whose default source code does not include python files, but only .CPP files and headers. Any and all help is greatly appreciated.</p>
<p>As far as I know standard pyodbc package currently can not run with PyPy without patches. </p> <p>However, you can try <a href="https://code.google.com/p/pypyodbc" rel="nofollow">pypyodbc</a>, which is similar to pyodbc, and it enables running SQLAlchemy under PyPy. <a href="http://code.google.com/p/pypyodbc/wiki/Enable_SQLAlchemy_on_PyPy" rel="nofollow">This how-to</a> describes the 4 steps to enable it. </p> <p>Disclaimer: I'm the maintainer of pypyodbc.</p>
python|database|sqlalchemy|pypy
4