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 |
|---|---|---|---|---|---|---|
10,000 | 35,480,682 | Publishing on a specific partition of a topic using pykafka | <p>How is it possible in <code>pykafka</code>to publish a message on a specific partition of a topic. In the following piece of code test topic has four partitions and I'm intending to write each message in one of them but apparently it's not working that way.</p>
<pre><code>from pykafka import KafkaClient
import lo... | <p>Key is what determines "which partition" a message is going to end up in.<br>
If you don't supply a key, then Kafka puts messages in a round-robin fashion, where each partition gets roughly the same amount of messages.</p>
<p>If you provide the key, then Kafka calculates the hash and puts the message in a resulting... | python|apache-kafka|producer|kafka-python|message-bus | 6 |
10,001 | 59,012,385 | Need to filter dates by month in pandas dataframe | <p>Have data on temperature that spans multiple years in 2010-01-01 format. I want to isolate the temps from June and am unsure how to filter this. Typically the method I use would be
<code>df[df['date'] == 2016]</code> but this only parses out by year. </p> | <p>IIUC, you can use a datetime method ontop of your datetime to access the month</p>
<pre><code>impot pandas as pd
rng = pd.date_range('2010-01-01','2011-01-01',freq='D')
df = pd.DataFrame({'dates':rng})
</code></pre>
<h3>Print Head of DataFrame.</h3>
<pre><code>print(df.head(5))
dates
0 2010-01-01
1 2010-01-0... | python|pandas|date|dataframe|filter | 2 |
10,002 | 31,400,769 | bounding box of numpy array | <p>Suppose you have a 2D numpy array with some random values and surrounding zeros.</p>
<p>Example "tilted rectangle":</p>
<pre><code>import numpy as np
from skimage import transform
img1 = np.zeros((100,100))
img1[25:75,25:75] = 1.
img2 = transform.rotate(img1, 45)
</code></pre>
<p>Now I want to find the smallest ... | <p>You can roughly halve the execution time by using <code>np.any</code> to reduce the rows and columns that contain non-zero values to 1D vectors, rather than finding the indices of all non-zero values using <code>np.where</code>:</p>
<pre><code>def bbox1(img):
a = np.where(img != 0)
bbox = np.min(a[0]), np.m... | python|arrays|numpy|transformation | 93 |
10,003 | 48,979,909 | Pytorch: TypeError 'torch.LongTensor' object is not reversible | <p>I'm trying to do a NLP task by pytorch and I used following code to pack my batch of sentences.</p>
<pre><code>for iter in range(0, n_iters, batch_size):
# batch size * max length Variable
input_batch = input_data[iter:iter + batch_size]
target_batch = target_data[iter:iter + batch_size]
# batch si... | <p>PackedInput is coded with the expectation a list of longs. </p>
<p>If you want to use a Variable(LongTensor([list])).cuda() for indexes, then you have to bring it back to the cpu, and numpy it, then put it back in.</p>
<pre><code>packed_in= pack_padded_sequence(embedded, seqs_len.data.cpu().numpy(), batch_first=T... | pytorch | 0 |
10,004 | 25,218,465 | Working on multidimensional arrays | <p>I'm trying to scale the colors of images to predefined ranges. Based on least-squared error from palette's range of colors, a color is assigned to output pixel.</p>
<p>I have written the code in python loops is there a better vectorized way to do this?</p>
<pre><code>import numpy as np
import skimage.io as io
pal... | <p>Don't loop over all pixels, but over all colors:</p>
<pre class="lang-py prettyprint-override"><code>import pylab as pl
palette = pl.array([[180, 0, 0], [255, 150, 0], [255, 200, 0], [0, 128, 0]])
img = pl.imread('lena.jpg')[:, :, :3].astype('float')
R, G, B = img[:, :, 0].copy(), img[:, :, 1].copy(), img[:, :, 2... | python|image-processing|numpy|scikit-image | 0 |
10,005 | 70,781,482 | Python script inside bash script. How to not print log error on console? | <p>I have a python script running inside a bash script as below:</p>
<pre><code>var=$(python <<EOF
try:
import sys
import gflags
var = Dummy.get_dummy_var()
if var == so_n_so:
print "found"
else:
print "unknown"
except Exception as e:
pass
EOF
)
</code></pre>
<p>Inside get_... | <ul>
<li>One way is to redirect logs to <a href="https://docs.python.org/3/library/logging.handlers.html#nullhandler" rel="nofollow noreferrer"><code>NullHandler</code></a> (python >= 3.1)</li>
</ul>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash
var=$(python3 <<EOF
import logging
logging.basicCo... | python|bash|logging | 0 |
10,006 | 60,224,264 | How to find pair of numbers in a list which makes a sum as given number | <p>A few days back I encountered a problem which says that there is a list of numbers and a value called total. Now we need to write a program that gives a list of tuples (only 2 elements in the tuple) and sum of each tuple should be equal to the value of total. Example: Following is the input:</p>
<pre><code>input = ... | <p>Using a list-comprehension with <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow noreferrer"><code>itertools.combinations</code></a>:</p>
<pre><code>>>> import itertools
>>> inpt = [1,2,3,4,6,7,8,9]
>>> total = 10
>>> [p for p in ite... | python|python-3.x|list|tuples|combinations | 3 |
10,007 | 59,957,958 | Adding Decimal Places | <pre><code>d = {'col1': [999, 1000]}
df = pd.DataFrame(data=d)
</code></pre>
<p>How would I loop through this data frame and add a decimal two places from the right for values higher than 200. For example, 999 is greater than 200 so make that 9.99</p> | <blockquote>
<p><strong>If you want apply in all columns <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask</code></a>:</strong></p>
</blockquote>
<pre><code>df = df.mask(df.ge(200),df.div(100))
</code></pre>
<p>If you want ... | python|pandas | 0 |
10,008 | 2,696,644 | how to make a thread of never stop, and write something to database every 10 second | <p>i using gae and django</p>
<p>this is my code:</p>
<pre><code>class LogText(db.Model):
content = db.StringProperty(multiline=True)
class MyThread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self, name=threadname)
def run(self,request):
log=LogText()
... | <p>It's impossible to do in GAE since all requests (including cron job) have <a href="http://googleappengine.blogspot.com/2009/02/skys-almost-limit-high-cpu-is-no-more.html" rel="nofollow noreferrer">30 seconds deadline</a>.</p> | python|django|google-app-engine|multithreading | 1 |
10,009 | 2,919,528 | Writing a post search algorithm | <p>I'm trying to write a free text search algorithm for finding specific posts on a wall (similar kind of wall as Facebook uses). A user is suppose to be able to write some words in a search field and get hits on posts that contain the words; with the best match on top and then other posts in decreasing order according... | <p>Yes. There are many normalization methods you could use. This is a well-researched field!</p>
<p>Take a look at <a href="http://en.wikipedia.org/wiki/Vector_space_model" rel="nofollow noreferrer">the vector space model</a> . TDF/IDF could be relevant to what you're doing. It's not strictly related to the method you... | python|full-text-search|levenshtein-distance | 1 |
10,010 | 5,941,113 | Looking for Python package for numerical integration over a tessellated domain | <p>I was wondering if anyone knew of a numpy/scipy based python package to numerically integrate a complicated numerical function over a tessellated domain (in my specific case, a 2D domain bounded by a voronoi cell)? In the past I used a couple of packages off of the matlab file exchange, but would like to stay within... | <p>This integrates over triangles directly, not the Voronoi regions, but should be close. (Run with different numbers of points to see ?) Also it works in 2d, 3d ...</p>
<pre><code>#!/usr/bin/env python
from __future__ import division
import numpy as np
__date__ = "2011-06-15 jun denis"
#............................... | python|numpy|scipy|numerical-integration | 5 |
10,011 | 67,760,785 | Why am I getting multiple outputs? | <p>I am currently trying to write numbers into an textfile and output the number as an string but when I for example take the number 150 as an input I get multiple outputs.</p>
<p><strong>My output when taking the number 150 as an input:</strong></p>
<pre><code>one
five
fifteen
fifty
one hundret and fifty
</code></pre>... | <p>Question:
Is "5" in "150" -> Yes it is!</p>
<p>That causes your functions to trigger for every number that is found in your line.
It seems like you "hard coded" the answers for which case I would have used a dictionary to simplify the code and use less repetitions.</p>
<pre class="la... | python|python-3.x | 0 |
10,012 | 30,548,794 | Are there Guarded Commands in Python / What are they? | <p>Are there any <a href="http://en.wikipedia.org/wiki/Guarded_Command_Language" rel="nofollow">guarded commands</a> in Python? And what are they?
I've searched every where, but i can't find it. </p> | <p>The only preprocessor directive I was able to fine was the <code>__debug__</code> statement as explained by <a href="https://stackoverflow.com/questions/482014/how-would-you-do-the-equivalent-of-preprocessor-directives-in-python">this answer</a>.</p>
<p>It compiles to <code>True</code> when running python without a... | python|command | 0 |
10,013 | 67,143,112 | Is there any way to connect custom Signal(int) with Push-Button directly in PySide2? | <p>I want to connect a trigger generated from PushButton to my custom signal with an argument(Signal(int)).</p>
<p>It is possible to connect a signal without an argument to the Button. Currently, I am creating an extra slot to emit the Signal(int) triggered from Signal() and Button. Is there any simple way to this?</p>... | <p>The reason this won't work:</p>
<pre class="lang-py prettyprint-override"><code>self.button.clicked.connect(self.sig_y(self.value))
</code></pre>
<p>is because <code>connect()</code> needs to be passed a function (or, more precisely anything that can be <em>called</em>). But written like this, you're not passing it ... | python|signals-slots | 1 |
10,014 | 42,887,598 | Multiple conditions and outcomes in list comprehension? | <p>Can anyone correct this? See where I'm going wrong?</p>
<pre><code>row_length = 4
ic = 1
pc = 2
newlist = [('') if not x == ic and not x == pc else ('RESERVED ID')
if x == ic ('RESERVED PARENT') if x == pc for x in range(row_length)]
</code></pre>
<p>Should end up with:</p>
<pre><code>newlist = ['RESERVED ID', '... | <p>Is this what you are looking for?</p>
<pre><code>newlist = [''] * row_length
newlist[ic-1] = 'RESERVED ID'
newlist[pc-1] = 'RESERVED PARENT'
</code></pre>
<p>Not everything has to be done in a list comprehension. My code is not only more efficient but what is more important is easy to read.</p>
<hr>
<p><strong>E... | python|python-3.x | 1 |
10,015 | 65,785,163 | find the errors and fix them. this program is to find the sum of multiples of 3 in array | <p>this program is to find the sum of multiples of 3 in array. help me located the erros to make it work.</p>
<pre><code>values = [1,3,"5",7,8,9]
multiples_of_three = []
total_of_threes = 0
while not (i > values.lenght):
if (values[i] modulo 3) ==0:
multiples_of_three[i] == values[i]
... | <p>I don't know exactly what you want.</p>
<p>For now, I made a prediction and wrote the answer.</p>
<p>If not the result you want, write the details in the comments.</p>
<p>Try this code (python style):</p>
<pre><code>values = [1, 3, "5", 7, 8, 9]
result = 0
for value in values:
if int(value) % 3 == 0:
... | python-3.x|list|error-handling | 0 |
10,016 | 65,757,722 | How do I query the best solution of a pyGAD GA instance? | <p>I've trained a population of neural networks using using the genetic algorithm implementation provided by the pyGAD Python Library. <strong>The code I've written so far is given below:</strong></p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pygad.gann
import time
import ... | <p>Thanks for using <a href="https://pygad.readthedocs.io" rel="nofollow noreferrer">PyGAD</a>.</p>
<p>I see that you built the example correctly. You can easily use the best solution to make predictions using simple 3 steps.</p>
<p>Please note that after each generation, the <code>population</code> attribute is update... | python|machine-learning|artificial-intelligence|genetic-algorithm | 4 |
10,017 | 65,832,933 | AttributeError: 'TikTokApi' object has no attribute 'width' | <p>I'm trying to use the library TikTokApi to download TikTok data but when I call any method, it throws:</p>
<pre class="lang-none prettyprint-override"><code>AttributeError: 'TikTokApi' object has no attribute 'width'
</code></pre>
<p>Here is an example of the code I'm running:</p>
<pre><code>from TikTokApi import Ti... | <p>I have the same problem. As David said, this error means that python-playwright or selenium is not launching correctly.
What I did is</p>
<ol>
<li>Check the version of your chrome
Right upper corner -> help -> About Google Chrome</li>
<li>Download the chromedriver from <a href="https://chromedriver.chromium.o... | python|python-3.x|api|tiktok | 2 |
10,018 | 65,794,606 | Pandas: Get index number based on a condition | <p>how can I grab the index number of a dataframe only if the values of a column match the values of another column in another df?</p>
<p>For instance, if I have a df_1 with a column of some words and in the other columns some values, and a df_2 with a list of words in a column and some other columns with other values... | <p>In this particular case you would need to pre-filter the df and then use <code>.index.tolist()</code> to get the index values as a list.</p>
<pre><code>output = df_1[df_1['Word'].isin(df_2['Word'].values)].index.tolist()
</code></pre>
<p>The first part of the code is keeping only the rows in which the <code>Word</co... | python|pandas | 0 |
10,019 | 50,898,341 | How to display a set of files with MatPlotLib in a loop | <p>I have a set of <code>.txt</code> named <code>"occupancyGrid_i"</code>, <code>i</code> being a number from <code>0-100</code>.
What I'd like to do is to open every one of them and show them for <em>3</em> seconds. The data of the <code>.txt</code> is a <code>[N x M] matrix</code>.</p>
<pre><code>import numpy
import... | <p>You can try something like this, adapting the code suggested <a href="https://stackoverflow.com/questions/11874767/real-time-plotting-in-while-loop-with-matplotlib?noredirect=1&lq=1">in this answer</a>:</p>
<pre><code>import os
import numpy as np
import pylab as plt
N_IMAGES = 100
VMIN, VMAX = 0, 1 # range of... | python|matplotlib|matrix | 1 |
10,020 | 50,882,161 | Python, How do I get the average from a tuple from MySQL? | <p>I'm fetching some temperature data from MySQL which i receive in a tuple like this:
((Decimal('28.7'),), (Decimal('28.7'),), (Decimal('28.6'),))</p>
<p>I can't seem to figure out how to get the average of these values out.</p>
<p>Hoping anyone knows and it's an easy fix? :)</p>
<p>Sometimes these tuples contain ... | <p>If you want to get the average without fetching the data you can use the <a href="https://www.w3schools.com/sql/func_mysql_avg.asp" rel="nofollow noreferrer">AVG MYSQL function </a> directly in your query</p> | mysql|python-3.x|raspberry-pi3 | 0 |
10,021 | 50,459,326 | How do you add folding to QsciLexerCustom subclass? | <p>Consider this snippet:</p>
<pre><code>import sys
import textwrap
import re
from PyQt5.Qt import * # noqa
from PyQt5.Qsci import QsciScintilla
from PyQt5.Qsci import QsciLexerCustom
from lark import Lark, inline_args, Transformer
class LexerJson(QsciLexerCustom):
def __init__(self, parent=None):
s... | <p>I can't fix your lexer code, but I can give you a working example for the same</p>
<pre><code>import sys
from PyQt5.Qt import *
from PyQt5.Qsci import QsciScintilla, QsciLexerCPP
from PyQt5.Qsci import QsciLexerCustom
if sys.hexversion < 0x020600F0:
print('python 2.6 or greater is required by this program'... | python|pyqt|pyqt5|qscintilla|lark-parser | 12 |
10,022 | 56,847,807 | Loss of Multi-Output Model in Pytorch | <p>I have a multi-output model in PyTorch when I train them using the same loss and then to backpropagate I combine the loss of both the output but when one output loss decreases others increase and so on. How can I fix the problem?</p>
<pre class="lang-py prettyprint-override"><code>def forward(self, x):
#neural ... | <p>If you have two different loss functions, and you finish the <code>forwards</code> for both of them separately, it is smart to do </p>
<pre><code>(loss1 + loss2).backward()
</code></pre>
<p>This is computationally efficient.</p>
<p>What you should achieve is to make your model learn, how to minimize the loss.
So... | machine-learning|deep-learning|pytorch | -1 |
10,023 | 56,809,010 | An Error: ElementNotInteractableException in Selenium Python | <p>I have a problem with finding a WebElement in Selenium. I tried to fill the input field, this is the html: </p>
<pre><code><div class="container">
<div class="tp-fl" id="btnSearchStockAutoComplete">
<span class="tp-icon tp-search tp-co-3 "></span>
<... | <p>When you write the CSS selector <code>app-content#txt_search</code>, that means the HTML is something like <code><app-content id='txt_search'>...</app-content></code>. Joined together with no space between means they are all part of the same element. What you want is either <code>app-content > #txt_se... | python|selenium|selenium-webdriver | 1 |
10,024 | 61,395,380 | How to dynamically run some tests in parallel in Pytest 3.0.7 | <p>I am using Pytest 3.0.7 (in Python 2.7) and I need to be able to dynamically run selected tests in parallel without modifying the tests. Take the example code below:</p>
<pre><code>import time
import logging
import pytest
logger = logging.getLogger('test1')
logger.setLevel(logging.DEBUG)
formatter = logging.Forma... | <p>I was able to skip a test by setting a marker dynamically with the pytest_collection_finish hook like this:</p>
<pre><code>import _pytest.mark
def pytest_collection_finish(session):
for itm in session.session.items:
if itm.name == 'test_test2':
itm.own_markers = [_pytest.mark.Mark(name='ski... | python|parallel-processing|pytest | 0 |
10,025 | 61,475,874 | Convert a sparse matrix to dataframe | <p>I have a sparse matrix that stores computed similarities between a set of documents. The matrix is an ndarray.</p>
<pre><code> 0 1 2 3 4
0 1.000000 0.000000 0.000000 0.000000 0.000000
1 0.000000 1.000000 0.067279 0.000000 0.000000
2 ... | <p>Convert the dataframe to an array:</p>
<pre><code>x = df.to_numpy()
</code></pre>
<p>Get a list of non-diagonal non-zero entries from the sparse symmetric distance matrix:</p>
<pre><code>i, j = np.triu_indices_from(x, k=1)
v = x[i, j]
ijv = np.concatenate((i, j, v)).reshape(3, -1).T
ijv = ijv[v != 0.0]
</code></p... | pandas|numpy|sparse-matrix | 2 |
10,026 | 60,710,134 | My script are not going to next page for scraping | <p>I wrote a code for web scraping everything is ok except next page activity. When I run my code to <strong>scrape</strong> data from the website it just <strong>scraping</strong> first page not moving forward to scrape other pages data. Actually I'm new to web scraping using python so please guide me. could you pleas... | <p>I started trying to find out why it wasn't loading the next page correctly, but before I found the answer I found another way to get the data you are looking for. On the page there is an option to change how many results you want to return. I changed this to 10000, and now all items from the collection load on one p... | python|web-scraping|beautifulsoup | 1 |
10,027 | 60,540,400 | Sort Cyrillic strings before Latin in python | <p>In my database, I have records in both Cyrillic and Latin characters. By default, they are listed alphabetically with Latin records first:</p>
<blockquote>
<p>abc... bcd... cde... абв...</p>
</blockquote>
<p>I would like to put the Cyrillic to the first place:</p>
<blockquote>
<p>абв... abc... bcd... cde...</... | <p>One way to do this is to use the <a href="https://pypi.org/project/transliterate/" rel="nofollow noreferrer"><code>transliterate</code> module</a> or maybe <a href="https://pypi.org/project/cyrtranslit/" rel="nofollow noreferrer"><code>cytranslit</code></a> and use a sort key that transliterates everything to the de... | python|sorting|unicode|collation | 2 |
10,028 | 57,985,434 | Django TemplateSyntaxError: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag? | <p>I'm unsure where my syntax error is, if you can please spot it that would be great.</p>
<pre><code>{% extends 'budget/base.html' %}
{% block content %}
<ul class="z-depth-1">
{% for transaction in transaction_list %}
<li>
<div class="card-panel z-d... | <p>you did a small mistake, please remove the $ sign from the {% endfor $} and add % instead. and in last line of your code replace {% endblock content %} with {% endblock %} so your code will look like as below:</p>
<pre><code> {% extends 'budget/base.html' %}
{% block content %}
<ul class="z-depth-... | python|django|for-loop | 1 |
10,029 | 57,923,640 | Python Pychef: Not able to search attributes using class chef.Search | <p>I am trying to get list of nodes on my chef server that has a cookbook with specific name.</p>
<pre><code> nodes_list = Search('node', 'cookbooks:<cookbook_name')
for row in nodes_list:
print(row['ipaddress'])
</code></pre>
<p>It doesnt return any result. How can i search nodes with a specific cookbook n... | <p>You could do this with a bash one-liner for loop :</p>
<pre><code>for nodes in $(knife node list); do knife node show $nodes -r; done
</code></pre>
<p>If you want to see only nodes with specific cookbook :</p>
<pre><code>for nodes in $(knife node list); do knife node show $nodes -r | grep COOKBOOK; done
</code></... | python|chef-infra|pychef | 1 |
10,030 | 57,899,150 | Why is my matplotlib.pyplot.hist not binning my data | <p>I am attempting to create a histogram out of an array I made. When I plot the histogram it does not plot like a regular histogram it just gives me lines where my data points are. </p>
<p>I have attempted to set bins = [0,10,20,30,40,50,60,70,80,90] including with 0 and 100 on the ends. I've tried bins = range() and... | <p>You create a 2D array with one row and 100 columns. Hence you get 100 histograms, each with one bin.</p>
<p>Use a 1D vector of data instead.</p>
<pre><code>array2 = np.random.uniform(10.0,100.0,size=100)
</code></pre> | python|matplotlib|histogram | 1 |
10,031 | 56,347,042 | Extracting gene location from FASTA file | <p>I am trying to extract the gene location from a fasta file using BioPython but the function .location is not working. I would like to avoid regex because this function will have to work with different files and the all have slightly different headers.</p>
<p>The header looks like:
>X dna:chromosome chromosome:GRCh... | <p>If the headers of your different fasta files always end with '<strong>...chr:start:end:strand</strong>' and the different parts are separated by '<strong>:</strong>' you could try to split .description by <code>.split(":")</code> and select the penultimate and antepenultimate position of the resulting list. </p>
<... | python|python-3.x|biopython | 1 |
10,032 | 18,653,278 | Django get url regex by name | <p>I have a case where I have defined some Django url patterns and now I want to retrieve the regular expression associated with a given pattern. I want that because I want to pass these regular expressions to the client so I can check urls in client as well ( I'm talking about browser side history manipulation ) and f... | <p>So I've tried few things and finally I came up with my own solution. First I convert urlpatterns into a form which JavaScript understands:</p>
<pre><code>import re
converter = re.compile(r"\?P<.*?>")
def recursive_parse(urlpatterns, lst):
for pattern in urlpatterns:
obj = {
"pattern":... | python|regex|django | 2 |
10,033 | 71,689,286 | Any workaround to pass multiple arguments to defaultdict's default_factory? | <p>I have a factory method called <code>create_food</code>, which takes in multiple string parameters like below:</p>
<pre><code>def create_food(self, meat: str, vege: str) -> str:
</code></pre>
<p>I have another dictionary called <code>__kitchen</code> which uses string as key & value like below:</p>
<pre><code... | <p>What would you pass? <code>key</code> is the dish, which is distinct from the ingredients.</p>
<p>What you can do is instantiate a <code>defaultdict</code> with a function that calls <code>create_food</code> with default arguments</p>
<pre><code>self.__kitchen = defaultdict(lambda: self.create_food('ham', 'egg'))
</... | python|python-3.x|dictionary|factory|defaultdict | 0 |
10,034 | 55,451,107 | How to fix opencv import for TVL1 opticalflow algorithm | <p>I'm asking you a very simple question. I want to use the TVL1 function for computing opticalflow with openCV (and python). But here is what I get :</p>
<pre><code>AttributeError: 'module' object has no attribute 'DualTVL1OpticalFlow_create'
Traceback (most recent call last):
File "opticalFlowModel.py", line 50, i... | <p>I found the solution <a href="https://github.com/Rhythmblue/i3d_finetune/issues/2" rel="nofollow noreferrer">here</a>.</p>
<p>The way to call the function is different with the latest openCV version. Here is what to do :</p>
<p>Replace</p>
<pre><code>optical_flow = cv2.DualTVL1OpticalFlow_create()
</code></pre>
... | python|opencv|opticalflow | 4 |
10,035 | 55,566,841 | findall returning whole regular expression match as its first index even if there is one group present in it | <p>I was using findall method using a regular expression object but i got entire expression match of my string although i had a group present in it.</p>
<p>I am using python 3.7.3</p>
<pre><code>import re
def emailfinder(spam):
emailregx=re.compile(r'''(
[a-zA-Z0-9%_+-.]+
@
[a-zA-Z0-9.-]+
(\.[a-zA-Z]{2... | <p>You have redundant parenthesis, resulting two groups. Fixing it works:</p>
<pre><code>import re
def emailfinder(spam):
emailregx=re.compile(r'''
[a-zA-Z0-9%_+-.]+
@
[a-zA-Z0-9.-]+
(\.[a-zA-Z]{2,4}
)''',re.VERBOSE)
return emailregx.findall(spam)
print(emailfinder('tara9090@gmail.com blah monkey... | python|regex|findall | -1 |
10,036 | 57,542,088 | How to import column names in jupyter notebook, when column names are number (not letter)? | <p>I have an excel file in which the name of columns are numbers (like: 01_Jan_2019). I could not write this in jupyter and it says: </p>
<pre><code>Syntax error: invalid token
</code></pre>
<p>Does anyone can help me how to solve this problem?</p>
<p>Thanks in advance</p> | <p>Use the column name as index instead of property</p>
<p>Both the lines below returns same series</p>
<pre><code>data.column_name
data['column_name']
</code></pre>
<p>So change your statement to </p>
<pre><code> data['01_jan_18']
</code></pre> | python|jupyter-notebook | 0 |
10,037 | 57,322,379 | Python Splitting a setence based on several tokens | <p>I want to split a sentence based on several keywords:</p>
<pre><code>p = r'(?:^|\s)(standard|of|total|sum)(?:\s|$)'
re.split(p,'10-methyl-Hexadecanoic acid of total fatty acids')
</code></pre>
<p>This outputs:</p>
<pre><code>['10-methyl-Hexadecanoic acid', 'of', 'total fatty acids']
</code></pre>
<p>Expected out... | <p>You may use</p>
<pre><code>import re
p = r'(?<!\S)(standard|of|total|sum)(?!\S)'
s = '10-methyl-Hexadecanoic acid of total fatty acids'
print([x.strip() for x in re.split(p,s) if x.strip()])
# => ['10-methyl-Hexadecanoic acid', 'of', 'total', 'fatty acids']
</code></pre>
<p>See the <a href="https://ideone.co... | python|regex|split | 3 |
10,038 | 57,326,545 | Assigning values to parameters using read_excel from pandas in python | <p>I want to read an Excel file using pandas. I want to assign specific cells to certain parameters. </p>
<p>So my Excel contains 4 columns. First columns contains locations "s", 2nd contains the time "t" in years and 3rd and 4th column are 2 different materials that are available at this certain location at a certain... | <p>I would use the <code>pivot</code> function and return the pivotized frame as a dictionaries. We need to remove the keys with empty values from the dictionary and iterate to unite the dictionaries.</p>
<pre><code>df_pivot = pd.pivot_table(df, columns=['s','t'], index='Biomasse', values='KWS')
lst= [{k: v for k, v i... | python|pandas|python-2.7 | 1 |
10,039 | 57,313,358 | How do I ignore the header column and row in a csv file imported into python? | <p>I imported a csv file into python using Pandas, I am using the given matrix in csv to preform an astar algorithm.
The problem is when I import the csv file it has a header column and row with 1...173 and the row of 1 1.1...1.123
and the columns and rows are continuing
my code is only looking for 0s and 1s and the... | <p>use skiprows=1</p>
<pre><code>df = pd.read_csv(r'C:\Users\605760\Desktop\path rec\matrix.csv',skiprows=1)
</code></pre> | python|arrays|pandas|matrix|a-star | 0 |
10,040 | 54,010,853 | How can I create just three threads or a fixed number of threads and distribute X of lists to them | <p>Suppose that there is a method receiving data from somewhere. In this method we should create three threads or a fixed number of threads. Every piece of received data will be assigned to a thread.</p>
<p>In other words, if you will receive 10 lists of data (Note that the number of data items not fixed and can't be ... | <p>You can create a fixed number of threads and use a thread-safe global work queue to store tasks. While there are tasks, worker threads poll one and work on it. Once the work queue is empty, threads can re-join main.</p>
<p>Since Python's interpreter is <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel... | python|multithreading|networking | 1 |
10,041 | 53,830,833 | Accessing a variable from another file that's in a loop in Python | <p>I have a file that is reading measurements in the main. This function is in a while True loop. Inside this loop I want to change a variable as it goes through the process. No problems with setting that up. The issue I have is accessing this variable from another file. </p>
<p>File 1:</p>
<pre><code>def main()
... | <p>You can use something called as generators which will "Yield" a value once, and then you can use the next() function to get the next value from the generator.</p>
<p>File_1:</p>
<pre><code>def Generator():
i = 0
while True:
print("******LOOP******" + str(i))
i += 1
yield i
</code></... | python|function|loops|variables | 0 |
10,042 | 22,926,323 | Key error in dictionary - python | <p>I have two dictionaries:
One is : </p>
<pre><code>data_obt={'Sim_1':{'sig1':[1,2,3],'sig2':[4,5,6]},'Sim_2':{'sig3':[7,8,9],'sig4':[10,11,12]},'Com_1':{'sig5':[13,14,15],'sig6':[16,17,18]},'Com_2':{'sig7':[19,20,21],'sig9':[128,23,24]}}
</code></pre>
<p>Other one is:</p>
<pre><code>simdict={'sig1':'Bit 1','sig2':... | <p>As I understand, <code>return_data</code> is another dict. If so, it doesn't (as of yet) have a key named <code>fpath</code> (which is 'sig9'). Hence, the error. </p>
<p>To avoid it, you should either use <a href="https://stackoverflow.com/questions/5900578/how-collections-defaultdict-work">defaultdict</a>, or init... | python|dictionary | 0 |
10,043 | 45,328,311 | Simplifying Python List Comprehension | <p>Can someone simplify the logic behind this piece of code:</p>
<pre><code>scores=[(similarity(prefs,person,other),other)
for other in prefs if other!=person ]
</code></pre>
<p>I tried implementing it like this</p>
<pre><code>for others in prefs:
if others!=person:
scores=[similarity(prefs,person, other... | <p>That would be the same as making repeated <em>appends</em> of the tuples to a list:</p>
<pre><code>scores = []
for others in prefs:
if others!=person:
scores.append((similarity(prefs, person, others), others))
</code></pre> | python|python-2.7|logic|list-comprehension | 5 |
10,044 | 28,819,566 | Python List To Dictionary - Without Value Overwrite | <pre><code>Keys = [1,2,3]
Values = [["a",1],["b",2],["c",3],["d",1]]
Dictionary = dict.fromkeys(Keys)
for d in Dictionary:
for value in Values:
if value[1] == d:
# Add to dictionary
Dictionary.update({d:value})
# else
# Do Nothing
print(Dictionary)
</code></p... | <p>Use the <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> object.</p>
<pre><code># -*- coding: utf-8 -*-
from collections import defaultdict
values = [["a", 1], ["b", 2], ["c", 3], ["d", 1]]
d = defaultdict(list)
for x, y in values:
... | python|dictionary|key|append | 4 |
10,045 | 28,774,914 | Cleanest iteration/functional application on Pandas Dataframe regardless of length | <p>I constantly struggle with cleanly iterating or applying a function to Pandas DataFrames of variable length. Specifically, a length 1 DataFrame slice (Pandas Series).</p>
<p>Simple example, a DataFrame and a function that acts on each row of it. The format of the dataframe is known/expected.</p>
<pre><code>def str... | <p>There is no generic way to write a function which will seemlessly handle both
DataFrames and Series. You would either need to use an <code>if-statement</code> to check
for type, or use <code>try..except</code> to handle exceptions.</p>
<p>Instead of doing either of those things, I think it is better to make sure yo... | python|pandas|apply | 3 |
10,046 | 14,457,723 | Can I raise a signal from python? | <p>The topic basically tells what I want to to.</p>
<p>I read the documentation, which tells me how to handle signals but not how I can do signalling by myself.</p>
<p>Thanks!</p> | <p>Use <a href="http://docs.python.org/3/library/os.html#os.kill" rel="noreferrer"><code>os.kill</code></a>. For example, to send <code>SIGUSR1</code> to your own process, use</p>
<pre><code>import os,signal
os.kill(os.getpid(), signal.SIGUSR1)
</code></pre> | python|signals|ipc | 26 |
10,047 | 68,810,795 | Filter rows in DataFrame where certain conditions are met? | <p>I have a DataFrame with relevant stock information that looks like this.</p>
<p><a href="https://i.stack.imgur.com/A8aKr.png" rel="nofollow noreferrer">Screenshot of my dataframe</a></p>
<p>I need it so that if the 'close' from one row is different from the 'open' in the next row a new dataframe will be created stor... | <p>This can be accomplished using <code>Series.shift</code></p>
<pre class="lang-py prettyprint-override"><code>>>> df['close'] != df['open'].shift(-1)
0 2020-01-01 False
1 2020-01-01 False
2 2020-01-01 True
3 2020-01-02 True
4 2020-01-02 True
5 2020-01-02 False
6 2020-01-03 Tru... | python|pandas | 0 |
10,048 | 41,358,778 | Can I make the pytest doctest module ignore a file? | <p>We use pytest to test our project and have enabled <code>--doctest-modules</code> by default to collect all of our doctests from across the project.</p>
<p>However there is one <code>wsgi.py</code> which may not be imported during test collection, but I cant get pytest to ignore it.</p>
<p>I tried putting it in th... | <p>As <a href="https://stackoverflow.com/a/41374309/4731718">MasterAndrey</a> has mentioned, <code>pytest_ignore_collect</code> should do the trick. Important to note that you should put <code>conftest.py</code> to root folder (the one you run tests from).<br>
Example:</p>
<pre><code>import sys
def pytest_ignore_coll... | python|pytest|doctest | 7 |
10,049 | 53,841,913 | Perform feature selection using pipeline and gridsearch | <p>As part of a research project, I want to select the <em>best</em> combination of preprocessing techniques and textual features that optimize the results of a text classification task. For this, I am using Python 3.6.</p>
<p>There are a number of methods to combine features and algorithms, but I want to take full ad... | <p>This solution is very rough based on your description and specific to the answer depending on the type of data used. Before making the pipeline, lets understand how the <code>CountVectorizer</code> works on the <code>raw_documents</code> that are passed in it. Essentially, <a href="https://github.com/scikit-learn/sc... | python|scikit-learn|pipeline|feature-selection|grid-search | 2 |
10,050 | 44,663,718 | Replacing multiple entires in a text file using a regular expression | <p>I have a structured text file containing a number of multi-line records. Each record should have a key unique field. I need to read through a series of these files, finding the non-unique key fields and replacing the key value with unique values. </p>
<p>My script is identifying all the fields which need replacing.... | <p>Take a look and read through the comments. Let me know if anything doesn't make sense:</p>
<pre><code>import re
def replace(text, replacements):
# Make a copy so we don't destroy the original.
replacements = replacements.copy()
# This is essentially what you had already.
regex = re.compile("|".joi... | python|regex|python-3.x | 1 |
10,051 | 61,758,494 | Django3.0 : GDALException while accessing model form | <p>I am trying to save shops with the geo locations in Django project. And I am able to save the data from admin UI but getting exception when I access the saved data.</p>
<p>In my django app (shop) I have following <strong>models.py</strong></p>
<pre><code>from django.contrib.gis.db import models
class Shop(models.... | <p>I have a similar issue. Check your GDAL version with</p>
<pre><code>gdalinfo --version
GDAL 3.0.4, released 2020/01/28
</code></pre>
<p>Support for GDAL 3.x has just been added to django but has not yet been released as of 5/13/2020: <a href="https://github.com/django/django/commit/58f1b07e49a98bb391c9e38b91f078ab... | python|django|django-models|geodjango|django-leaflet | 0 |
10,052 | 61,729,853 | How to check with GTK3 in python that the window exists and possibly update the data in it? | <p>I have a class that calls up a window with content to display(Gtk.ApplicationWindow), I would like to check if the window exists. If it exists it updates the data, if not, it creates a new instance of a new window. How to check if a window exists?</p>
<p>Edit:</p>
<p>My code:</p>
<pre class="lang-py prettyprint-o... | <p>Couldn't run the below code, so may be erroneous!</p>
<pre><code>class LogListener:
def __init__(self):
print('do sth')
app.alert_view.set_label("TEST")
class AlertView(Gtk.ApplicationWindow):
def __init__(self):
super().__init__()
self.builder = Gtk.Builder()
self.b... | python|gtk3|pygtk | 0 |
10,053 | 24,029,290 | python throwing an error HTTP 401 while accessing https://stream.twitter.com/1.1/statuses/filter.json | <p>This is the Code I am running to get the stream of tweets using Streaming API by accessing the stream.twitter url mentioned in title. but it is throwing an error (HTTP error 401)
In the code I am trying to track multiple terms</p>
<pre><code>import time
import pycurl
import urllib
import json
import oauth2
API_END... | <p>You could try updating your clock.</p>
<pre><code>sudo ntpdate ntp.ubuntu.com
</code></pre>
<p>From: <a href="http://lembra.wordpress.com/2012/03/08/twitter-stream-mysterious-401unauthorized-status-with-oauth-and-clock-issue/" rel="nofollow">http://lembra.wordpress.com/2012/03/08/twitter-stream-mysterious-401unaut... | python|pycurl | 0 |
10,054 | 15,066,947 | Wildcard domain with federated type application on GAE | <p>I have used <a href="https://stackoverflow.com/questions/14695812/programatically-setting-subdomain-on-google-app-engine/14709839#14709839">Steps</a> to make wildcard sub-domain to work on Google app engine, Godaddy and amazon route. Its working nicely for application with the authentication type (found in applicati... | <p>The issue found out was not related to application authentication type. But, there was problem with app.yaml file. </p> | python|google-app-engine|webapp2 | 0 |
10,055 | 46,192,946 | Tkinter - Class containing buttons | <p>I have a <code>Tkinter</code> app in which I would like to include some buttons in a frame, and then place this frame in the main window. </p>
<p>However running the code returns just an empty window. So I guess I miss completely how to build a <code>Tkinter</code> app with modular classes.. The atomic code is:</p>... | <p>The problem is that you don't pack (or grid or place) your <code>MainApplication</code> instance.
Since your <code>MainApplication</code> extends the <code>tk.Frame</code> class, its instances are widgets, and thus need to be packed into their master.</p>
<pre><code>def main():
root = tk.Tk()
app = MainAppl... | python|tkinter | 5 |
10,056 | 46,310,034 | How to test that a custom excepthook is installed correctly? | <p>My app logs unhandled exceptions. </p>
<pre><code># app.py
import logging
import sys
logger = logging.getLogger(__name__)
def excepthook(exc_type, exc_value, traceback):
exc_info = exc_type, exc_value, traceback
if not issubclass(exc_type, (KeyboardInterrupt, SystemExit)):
logger.error('Unhandled... | <p>Python won't call <code>sys.excepthook</code> until an exception actually propagates all the way through the whole stack and no more code has an opportunity to catch it. It's one of the very last things that happen before Python shuts down in response to the exception.</p>
<p>As long as your test code is still on t... | python|testing|logging|exception-handling|pytest | 5 |
10,057 | 49,539,771 | python - using global and local variables in the same function | <p>In python when I try this:</p>
<pre><code>admin = "Vaibhav"
def print_admin(default):
# global admin
if default == "default":
print(admin)
else:
admin = "other"
print(admin)
print_admin("")
print_admin("default")
</code></pre>
<p>It gives me an error:</p>
<pre><code>error:Unbou... | <p>Talking about the scope of a variable:</p>
<pre><code>admin = "Vaibhav"
def print_admin(default):
if default == "default":
## This is global
global admin
print(admin)
else:
## This is local to your function
print_admin.admin = "other"
print(print_admin.admin)
... | python | 1 |
10,058 | 21,009,439 | py2neo Cypher transactions failing | <p>I'm trying to batch import millions of nodes through Py2Neo.
I don't know what's faster, the <code>BatchWrite</code> or the <code>cipher.Transaction</code>, but the latter seemed the best option as I need to split my batches.
However, when I try to execute a simple transaction, I receive a weird error.</p>
<p>The ... | <p>The problem you're seeing is due to a last minute alteration in the way that Cypher transaction errors are reported by the Neo4j server. Py2neo 1.6 was built against M05/M06 and when a few features changed in RC1/GA, Py2neo broke in a few places.</p>
<p>This has been fixed for Py2neo 1.6.2 (<a href="https://github.... | python|neo4j|cypher|py2neo | 2 |
10,059 | 62,575,143 | How to transfer information between classes of windows in tkinter? | <p>I want to transfer some of my user input in my main window to the toplevel window.</p>
<p>so far I have this:</p>
<pre><code>import tkinter as tk
from tkinter import filedialog
class Level1 :
def __init__(self, master):
## bunch of frames, labels and button instantiations
...........
self.info = fil... | <p>The most common solution is to pass the instance of the class with the data to the class that needs the data.</p>
<pre><code>class Level1 :
...
def go_to_level2(self):
...
self.app = Level2(self.level_2, self)
...
class Level2:
def __init__(self, master, level1):
...
... | python|oop|tkinter | 1 |
10,060 | 54,769,989 | Saving process data on another table in the database | <p>I'm working on a process for my company. Doing this i have found it necesary to store data that is being inserted in the proccess. My process is working fine but instead of saving in my other model, it keeps on saving the data on the table that corresponds to the process and not my other model.</p>
<p>models.py:</p... | <p>All process views such as <code>CreateProcessView</code> or <code>UpdateProcessView</code> in Django Viewflow is connected to a <strong>Process model</strong>. This means that the view and the flow can keep track on meta data related to the process that gets added when you inherit from the <code>Process</code> model... | python|django|django-viewflow | 0 |
10,061 | 54,807,335 | Visualizing executable byte stream to a image file, why it is rotated 45 degrees? | <p>I'm trying to visualize malware executables for testing visual classification approach. Using Microsoft Malware Classification Challange <a href="https://www.kaggle.com/c/malware-classification/data" rel="nofollow noreferrer">dataset</a> .bytes files I have input such:</p>
<pre><code>00401000 56 8D 44 24 08 50 8B F... | <p>I think the line:</p>
<pre><code>image_buffer[i,j] = b_data[i+j]
</code></pre>
<p>needs to be:</p>
<pre><code>image_buffer[i,j] = b_data[(i*width)+j]
</code></pre>
<hr>
<p>I don't have your data to test with, nor the <code>import</code> statements which you didn't share for some reason, but I suspect the whole ... | python|numpy|python-imageio | 2 |
10,062 | 54,901,049 | Flask cross domain not working together with namespace | <p>After importing and CORS from flask_cors I get the flask server to support requests from localhost. But only if the request is under the api.route.</p>
<p>For any target under a namespace, I get <strong><em>Access to fetch at '<a href="http://127.0.0.1:5151/api/hello2" rel="nofollow noreferrer">http://127.0.0.1:515... | <p><strong>corydolphin</strong> commented on 18 Mar 2016
<a href="https://github.com/corydolphin/flask-cors/issues/128#issuecomment-198453999" rel="nofollow noreferrer">https://github.com/corydolphin/flask-cors/issues/128#issuecomment-198453999</a></p>
<p>"I expect what is happening is that Flask is silently redirecti... | python|flask|cors|namespaces|cross-domain | 2 |
10,063 | 54,899,259 | import error: cannot import name 'HTTPError' from urllib3.exceptions | <p>I had a .py file that used to work for web scraping gas prices from gasbuddy using selenium and phantomjs. It used to work, but it stopped all of a sudden. So I uninstalled and reinstalled selenium and phantomJS. I uninstalled and reinstalled Python 3 using homebrew. I even erased my MacBook and reinstalled Sierra o... | <p>I had the same problem after I renamed my main module to <code>email.py</code>. It started conflicting with libraries <code>requests</code> and <code>selenium</code>. After renaming from <code>email.py</code> to something more original the error was gone.</p> | python|python-3.x|selenium|selenium-webdriver|webdriver | 3 |
10,064 | 55,072,669 | How to replace 'x!' with 'math.factorial(x)' intelligently | <p>I am currently implementing a graphical calculator in Python, in a manner where you can type a natural expression and evaluate it. This is not a problem with most functions or operators, but as the factorial function is denoted by a <code>!</code> after the operand, this is more difficult.</p>
<p>What I have is a s... | <p>There's two levels of answer to your question: (1) solve your current problem; (2) solve your general problem.</p>
<p>(1) is pretty easy - the most common, versatile tool in general for doing string pattern matching and replacement is <a href="https://en.wikipedia.org/wiki/Regular_expression" rel="nofollow noreferr... | python|python-3.x|replace | 2 |
10,065 | 54,757,642 | Html alert box pop up on condition | <p>In my django project, I want to build one function in my html page to show the alert box if some output from the view.py equals to some number. Like, after clicking the button, the view.py function do the calculation and give the output, and if the number equals to one set in the html function, it will show the aler... | <p>Change </p>
<pre><code><p id="name"> number </p>
</code></pre>
<p>to </p>
<pre><code><p id="name"> {{ number }} </p>
</code></pre>
<p>Then in your javascript:</p>
<pre><code><script type = "text/javascript">
var a = '0';
var b = '{{ number }}';
function Warn() {
... | python|html|css|django | 2 |
10,066 | 21,556,623 | Regression with multi-dimensional targets | <p>I am using <em>scikit-learn</em> to do regression and my problem is the following. I need to do regression on several parameters (vectors). This works fine with some regression approaches such as <code>ensemble.ExtraTreesRegressor</code> and <code>ensemble.RandomForestRegressor</code>. Indeed, one can give a vector ... | <p>I interpret that what you have is a problem of <a href="http://en.wikipedia.org/wiki/Linear_regression">multiple multivariate regression</a>.</p>
<p>Not every regression method in scikit-learn can handle this sort of problem and you should consult the documentation of each one to find it out. In particular, neither... | python|scikit-learn | 24 |
10,067 | 24,804,829 | No module named 'winrandom' when using pycrypto | <p>I already spent 2 days trying to install pyCrypto for Paramiko module.</p>
<p>So, first issue I had faced was this:</p>
<pre><code>>>> import paramiko
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Python\lib\site-packages\paramiko\__init__.py... | <p>Problem is solved by editing string in crypto\Random\OSRNG\nt.py:</p>
<pre><code>import winrandom
</code></pre>
<p>to</p>
<pre><code>from . import winrandom
</code></pre> | python|windows|paramiko|pycrypto | 68 |
10,068 | 40,993,598 | Replicating Java password hashing code in Python (PBKDF2WithHmacSHA1) | <p>I have been trying to replicate the java password authenticate to python, however the resulted hash is different.</p>
<p>password: <strong>abcd1234</strong></p>
<p>password token (java): <strong>$31$16$sWy1dDEx52vwQUCswXDYMQMzTJC39g1_nmrK384T4-w</strong></p>
<p>generated password token (python): <strong>$pbkdf2$1... | <p>There's a bunch of things different between how that java code does things, and how passlib's pbkdf2_sha1 hasher does things. </p>
<ul>
<li><p>The java hash string contains a log cost parameter, which needs passing through <code>1<<cost</code> to get the number of rounds / iterations. </p></li>
<li><p>The sa... | java|python|encryption|hash|password-encryption | 3 |
10,069 | 41,058,609 | pysnmp how to load custom MIB modules which are in asn.1 format | <p>I am having trouble in figuring out how to load custom MIBs which with .txt extensions using <code>pysnmp</code> module</p>
<p>This is what I am doing currently</p>
<pre><code>b = builder.MibBuilder()
compiler.addMibCompiler(b, sources=[mib_location])
</code></pre>
<p>mib_location is folder on which all my MIBs a... | <p>MIB files should be found by MIB module name without any extension or with .txt one.</p>
<p>Here is an <a href="http://pysnmp.sourceforge.net/examples/v3arch/asyncore/manager/cmdgen/mib-tweaks.html#walk-agent-and-resolve-variables-at-mib" rel="nofollow noreferrer">example</a> that should work out of the box.</p>
<... | python|mib|pysnmp | 0 |
10,070 | 28,930,509 | Break string into words and phrases | <p>Supposing I have a string with several space-separated words, like</p>
<pre><code>words = "foo bar baz qux"
</code></pre>
<p>If I want a list of the words, I can just call <code>words.split()</code> and get</p>
<pre><code>['foo','bar','baz','qux']
</code></pre>
<p>But if I want to get each word <strong>and</stro... | <h3>Pretty "ugly" and with <code>itertools</code>:</h3>
<p>Combining <a href="https://stackoverflow.com/a/6670974">"Find all consecutive sub-sequences of length n in a sequence"</a> and <a href="https://stackoverflow.com/a/17142128">"concatenating sublists python"</a>:</p>
<pre><code>from itertools import chain
word... | python|python-2.7 | 1 |
10,071 | 28,909,450 | Ubuntu Installing Boto error | <p>I've installed Python 2.7.9, and I'm trying to install Boto with pip install boto, but I receive this error:</p>
<pre><code> Collecting boto
Using cached boto-2.36.0-py2.py3-none-any.whl
Installing collected packages: boto
Exception:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/di... | <p>Try running the command as follows:</p>
<pre><code> sudo pip install boto
</code></pre> | python|ubuntu|pip|boto | 3 |
10,072 | 8,373,599 | JSON.dump of a given object works in command line, not inside a script | <pre><code>object = {'score-set': [('SomeString', 1.0)], 'n': 10, 'num-found': 1, 'start': 0}
type(object) is dict.
</code></pre>
<p>When I do this in the command line
json.dump(object,f)</p>
<p>where f is an writable open file. I get the dump in the file perfectly.</p>
<p>But inside a program in a context like th... | <p>I'm guessing your <code>float</code> isn't really a <code>float</code>, but acts like it in certain ways. Try converting it to a <code>float</code> before serializing it:</p>
<pre><code>object['score-set'] = [(a, float(b)) for (a, b) in object['score-set']]
</code></pre> | python|json | 3 |
10,073 | 51,683,428 | Mongodb upsert document or $addToSet | <p>So I am trying to figure out the best way to do this. I have a dump of documents that I put into a collection. That includes a ID and a timestamp that is a array. Basically what I would like to accomplish is if there is collision on the ID I want to push the new timestamp to the array else I want to upsert the entir... | <p>The <a href="http://%20https://docs.mongodb.com/manual/reference/operator/update/addToSet/#up._S_addToSet" rel="nofollow noreferrer"><code>$addToSet</code> operator</a> can be used together with upsert if you want to keep unique timestamps as well. Otherwise, <a href="https://docs.mongodb.com/manual/reference/operat... | python-3.x|mongodb|pymongo|upsert | 0 |
10,074 | 51,974,380 | Print Hex With Spaces Between | <p>I'm trying to print my hex out in another way...</p>
<p>First I'm converting this (bytestring is the name of the variable):</p>
<pre><code>b'\xff\x00\xff\xff\xff'
</code></pre>
<p>to hex,</p>
<pre><code>print(bytestring.hex())
</code></pre>
<p>which outputs:</p>
<pre><code>ff00ffffff
</code></pre>
<p>but I've... | <p>just convert your array of bytes to hex strings, and join the result with space:</p>
<pre><code>>>> d=b'\xff\x00\xff\xff\xff'
>>> " ".join(["{:02x}".format(x) for x in d])
'ff 00 ff ff ff'
</code></pre>
<p>note that <code>" ".join("{:02x}".format(x) for x in d)</code> would also work, but forcing... | python|python-3.x|hex | 11 |
10,075 | 18,762,301 | Python loop database rows | <p>Table res_groups_users_rel:</p>
<pre><code> uid | gid
-----------------
4 3
4 12
4 9
</code></pre>
<p>Table res_groups:</p>
<pre><code> id | name | comment
------------------------------------
3 Employee All the Employees
9 Contact Creatio... | <p>You really shouldn't try to do this by getting all the results and iterating. It's a simple SQL query:</p>
<pre><code>cursor.execute('SELECT g.name FROM g.res_groups '
'JOIN res_groups_users_rel r ON r.gid = g.id '
'WHERE r.uid = %s AND g.comment LIKE "%%%s%%"',
(actual_... | python|database|openerp|nonetype | 1 |
10,076 | 18,998,352 | Adding xml prefix declaration with lxml in python | <p><strong>Short version</strong> :
How to add the xmlns:xi="http://www.w3.org/2001/XInclude" prefix decleration to my root element in python with lxml ? </p>
<p><strong>Context</strong> : </p>
<p>I have some XML files that include IDs to other files.</p>
<p>These IDs represent the referenced file names. </p>
<p>U... | <p><strong>Attribute <code>nsmap</code> is not writable</strong> gives me as error when I try your code. </p>
<p>You can try to register your namespace, remove current attributes (after saving them) of your root element, use <code>set()</code> method to add the namespace and recover the attributes.</p>
<p>An example:... | python|xml|namespaces|lxml|xinclude | 2 |
10,077 | 18,995,612 | Beginner Python: Saving an excel file while it is open | <p>I have a simple problem that I hope will have a simple solution.</p>
<p>I am writing python(2.7) code using the xlwt package to write excel files. The program takes data and writes it out to a file that is being saved constantly. The problem is that whenever I have the file open to check the data and python tries t... | <p>My experience is that sashkello is correct, Excel locks the file. Even OpenOffice/LibreOffice do this. They lock the file on disk and create a temp version as a working copy. ANY program trying to access the open file will be denied by the OS. The reason for this is because many corporations treat Excel files as dat... | python|excel|file|xlwt | 1 |
10,078 | 63,448,596 | How to convert attachment file to different format in odoo? | <p>How to add an observer on attachment upload in odoo to check for a certain file type and to do operation on this file? For example to convert to another format on upload.</p>
<p>EDIT</p>
<p><code>values</code> variable that is modified in my code still has no effect in <code>addons/web/controllers/main.py:upload_att... | <p>It seems that overwriting model's <code>write</code>/<code>create</code> functions is way to go. But for the reference here is how its done for Image field.</p>
<p><a href="https://github.com/odoo/odoo/blob/edacc0fc920e27b9759408887762fcba284ee391/odoo/fields.py#L2079" rel="nofollow noreferrer">https://github.com/od... | python|odoo|odoo-12|odoo-13 | 2 |
10,079 | 63,642,605 | python----The name of the error is'TypeError: not all arguments converted during string formatting'(っ °Д °;)っ | <p>I was making a program that inputs a number, distinguishes whether the number is prime, and prints it.</p>
<p>And when I type'o', I put the function to run the program once more.</p>
<p>Below is the program</p>
<pre class="lang-py prettyprint-override"><code>print('Prime number distinction')
print('=' * 50)
again = ... | <p>The problem is that it is trying to compute <code>pn % 2</code> when you have already converted <code>pn</code> to a <code>string</code></p>
<p><strong>Solution</strong> (check out the commented lines)</p>
<pre><code>print('Prime number distinction')
print('=' * 50)
again = 'o'
while again == 'o':
s = 0
a = ... | python | 1 |
10,080 | 36,343,431 | Python exit from all function and stop the execution | <p>I'm trying to develop a script that will connect to our switch and do some tasks.<br>
In this script I have a main function that calls a second function. In the second function I pass a list of switches that Python will start to connect one by one.<br>
The second function will call a third function. In the third fun... | <p>You can use</p>
<pre><code> import sys
sys.exit()
</code></pre>
<p>or</p>
<pre><code>raise SystemExit()
</code></pre>
<p>The parameters can be used to pass messages. If you are also dealing with loops, break also works really well.</p> | python|break | 2 |
10,081 | 13,518,222 | Django model naming conventions | <p>I have a pretty <em>stupid</em> question about model naming conventions in Django.</p>
<p>Imagine a farmstead which has buildings which have rooms.</p>
<p>Farmstead --> Buildings --> Rooms</p>
<p>With Farmstead it is ok, let's call it a <code>Farmstead</code>. Next one: <code>Building</code> or <code>FarmsteadBui... | <p>If all your instances of <code>Room</code> belongs to a <code>Building</code> (and there is no another kind of models like <code>Apartment</code>) and all your instances of <code>Building</code> belongs to a <code>Farmstead</code> (following the same idea), so just use the name of your models like <code>Farmstead</c... | python|django|django-models|naming-conventions | 6 |
10,082 | 16,716,158 | Django/Python control: "if form.is_valid ():" is equal to false if the form has an input type "button" | <p>I don't understand why if I have in my html page in a form: <code><input type="submit" class="btn btn-small btn-primary" id="execute"</code> value="Esegui">`</p>
<p>then the form is valid otherwise if I put a
<code><input class="btn btn-small btn-primary" type="button" id="execute"</code> value="Esegui">... | <p>This code is very confused. You have defined an Ajax function on your button triggered on the click event. So, when you click the button, that function is triggered, and it tries to submit the form. However, it cannot do so in a way that will make the form valid: the only field in the form is a required FileField, w... | javascript|html|django|json|python-2.7 | 0 |
10,083 | 17,093,326 | SQLAlchemy with on connection (python) | <p>I understand that with the standard <code>MySQLdb</code> driver, you usually use a <code>with</code> statement to ensure that the connection is closed with <code>__exit__</code>. </p>
<p>Is there an equivalent <code>with</code> statement that I need for SQLAlchemy <code>sessions</code> or maybe the <code>engine</co... | <p>Here is a quote from docs:</p>
<blockquote>
<p>Most web frameworks include infrastructure to establish a single
Session, associated with the request, which is correctly constructed
and torn down corresponding torn down at the end of a request. Such
infrastructure pieces include products such as Flask-SQLAlc... | python|sql|sqlalchemy | 1 |
10,084 | 16,899,597 | Can a django app have more than one views.py? | <p>I have just started learning Django. I was wondering if Django app can have more than one views file? Let's say, I have two separate classes. Should I keep them in one views file or can I make two views files? </p>
<p>Thanks in advance!</p> | <p>Yes, you can. A modular way of splitting would be to create a package - <code>views/</code></p>
<pre><code>- views/
- first.py
- second.py
- __init__.py
</code></pre>
<p>and in your <code>__init.py__</code> add the following:</p>
<pre><code>from .first import *
from .second import *
</code></pre>
<p... | python|django|django-views | 4 |
10,085 | 16,683,478 | Limit memory usage of phantomjs using selenium webdriver? | <p>I'm running phantomjs in Remote WebDriver mode with <code>phantomjs --webdriver 8910</code> and then getting many pages using the Selenium python bindings with something like:</p>
<pre><code>wd = webdriver.PhantomJS(port=8910)
for url in big_url_list:
wd.get(url)
# do something here, e.g. wd.save_screenshot... | <p>PhantomJS webpage close method calls by Ghostdriver only when you close WebDriver session.
You can try to use runit to restart PhantomJS when memory limit was reached. Create bash script as follows:</p>
<pre><code>#!/bin/sh
exec 2>&1
exec chpst -u your_user -m 104857600 /usr/bin/phantomjs --webdriver=8910
</... | python|selenium-webdriver|phantomjs | 1 |
10,086 | 43,486,192 | Logout from remote stuck paramiko ssh | <p>This problem is related to the <a href="https://stackoverflow.com/questions/43336007/taking-the-input-from-auto-execute-user-login-using-ssh-execute-command">Taking the input from auto-execute user login using ssh execute command</a> which I try to do another approach to solve my current problem.</p>
<p>Since the p... | <p>I ended up by using <a href="http://www.fabfile.org/" rel="nofollow noreferrer">fabric</a>.</p>
<pre><code>from fabric.tasks import execute
from fabric.api import run, settings, env
def remoteuser_login(self):
env.user = 'remoteuser'
env.password = 'remotepassword'
with settings(prompts={'>': 'q\n'}... | python|multithreading|ssh|paramiko | 0 |
10,087 | 54,463,897 | Refine OpenCV mask edge | <p>I'm in the process of scanning old photographs, and I would like to automate the process of extracting the photograph from the (noisy) solid white background of the scanner so that I have a transparent photograph. This part of the program now works, but I have one more small problem with this.</p>
<p>The photograph... | <p>By using the <code>erode</code> method, you could shrink the contour (<code>mask</code>), effectively removing the black edge.</p>
<p>Since this method supports in-place operation, the code would look something like this: <code>cv2.erode(mask, mask, kernel)</code>, where <code>kernel</code> is a kernel acquired usi... | python|opencv | 0 |
10,088 | 54,521,426 | why does "printing" occurs before "returning"? | <p>My Code:</p>
<pre><code>def f0():
return 1
def f1():
print("I don't deserve to be first :(")
print(f0(), f1())
</code></pre>
<p>Expected Output:</p>
<pre><code>1 I don't deserve to be first :(
None
</code></pre>
<p>Actual Output: </p>
<pre><code>I don't deserve to be first :(
1 None
</code></pre>
<p>... | <p>Has nothing to do with stdout, but rather with when values are printed. Your <code>f0</code> is called first, but it doesn't print anything. Your <code>f1</code> is called second, but it actually prints something.</p>
<p>The top-level <code>print()</code> call won't print anything until it has evaluated its argumen... | python|python-3.x | 7 |
10,089 | 39,233,935 | Using a variable as field name in MySQLdb, Python 2.7 | <p>This works when I replace the column variable with an actual column name. I do however need a variable. When I use a variable I get a MySQL syntax error. Can a field be a variable? If so, where is the error?</p>
<pre><code>conn = self.create_connection()
cur = conn[0]
db = conn[1]
cur.execu... | <p>The issue there is that Parameter substitution in the <code>execute</code> method is intended to be used for data only - as you found out.
That is not quite explicit in the <a href="https://www.python.org/dev/peps/pep-0249/" rel="noreferrer">documentation</a>, but it is how most database drivers implement it. </p>... | python|python-2.7|mysql-python | 5 |
10,090 | 52,787,791 | Formatting lists to display leading zero - Python 3.x | <p>I'm trying to create a matrix with 4 rows and 10 columns and display the leading 0 for all the single digit numbers that will randomly get generated later. This is what I would like it to look like: <img src="https://i.stack.imgur.com/t0twc.png" alt="1"> My teacher gave me this snippet as a way to format the numbers... | <p>you need a 0 in front .. i.e. {<strong>0</strong>:02}</p>
<pre><code>print('{0:02}'.format(variable))
</code></pre>
<p>This 0 refer to the index of the parameters passed in e.g. this should work too:</p>
<p>print('{<strong>2</strong>:02}'.format("x", "y", <strong>variable</strong>))</p>
<hr>
<p>Your code:</p>
... | python-3.x|list|matrix|format | 0 |
10,091 | 47,828,625 | Python sublist not working for long | <p>I am trying to sublist an list which contains long.</p>
<pre><code>a = [ -846930886, -1714636915, 424238335, -1649760492]
print(a[2:1])
</code></pre>
<p>This returns <code>[]</code>. What's happening? I could find only this way of sub listing.</p> | <p><code>a[2:1]</code> is not a valid <code>slicing</code> and will return <code>empty</code> list.</p>
<p>The correct syntax is <code>object[start:end:inteval]</code>. If you want to traverse in backward you should add <code>interval</code></p>
<pre><code>>>> print(a[2:1:-1])
[424238335]
</code></pre>
<p>A... | python|arrays|python-2.7 | 3 |
10,092 | 34,096,997 | Cut off end of file without creating a new one | <p>I have a program that spits out a very large text file that is 75% garbage at the end. Id like to be able to just cut the end off the file with out looping through each line and printing to a new file. Is there anyway to do this in python?</p>
<p>its hard to provide an example because it would be a very large file... | <p>Check <code>truncate()</code> method of file objects, it truncates the file from current position (or to a specified size, but your request implies you're actually reading the file when the decision to delete it's tail is made).</p>
<p>You can check the method documentation here:</p>
<p><a href="https://docs.pytho... | python|file|python-2.7 | 1 |
10,093 | 39,798,152 | LINE RESTful Messaging API - Error with wrong IP address | <p>I am using LINE Messaging API trying to push a message via bot. I've followed the configuration/setup detailed in <a href="https://business.line.me/en/" rel="nofollow">https://business.line.me/en/</a> and encountered this error - Access to this API denied due to the following reason: Your ip address [23.3.104.4] is ... | <p>I think that might be a bug and caused of "Server IP Whitelist" in your bot settings.
Try to remove the ip address you assigned.</p> | python|line | 0 |
10,094 | 39,757,805 | Using python requests and beautiful soup to pull text | <p>thanks for taking a look at my problem. i would like to know if there is any way to pull the data-sitekey from this text... here is the url to the page <a href="https://e-com.secure.force.com/adidasUSContact/" rel="noreferrer">https://e-com.secure.force.com/adidasUSContact/</a></p>
<pre><code><div class="g-recap... | <p>Ok now we have code, it is as simple as:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
soup = BeautifulSoup(requests.get("https://e-com.secure.force.com/adidasUSContact/").content, "html.parser")
key = soup.select_one("#ncaptchaRecaptchaId")["data-sitekey"]
</code></pre>
<p><em>data-sitekey</em> ... | python|python-requests|beautifulsoup | 13 |
10,095 | 31,855,249 | Creating a label dataset from a segmented image using Python | <p>I've labeled an image to produce a numpy array with labels e.g.</p>
<pre><code>array([[0, 1, 0, ..., 0, 0, 0],
[0, 1, 0, ..., 0, 0, 0],
[0, 1, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[2, 2, 0, ..., 0, 0, 0],
[2, 2, 0, ..., 0, 0, 0]], dtype=uint8)}
</code></pr... | <p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow"><code>np.meshgrid</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" rel="nofollow"><code>np.vstack</code></a> to create a <code>Nx3</code> numpy array having a s... | python|numpy|scikit-learn|scikit-image | 1 |
10,096 | 38,894,418 | How to name a dataframe column filled by numpy array? | <p>I am filling a DataFrame by transposing some numpy array :</p>
<pre><code> for symbol in syms[:5]:
price_p = Share(symbol)
closes_p = [c['Close'] for c in price_p.get_historical(startdate_s, enddate_s)]
dump = np.array(closes_p)
na_price_ar.append(dump)
print symbol
df = pd.DataFrame(na_pric... | <p>Instead of using a list of arrays and transposing, you could build the DataFrame from a dict whose keys are symbols and whose values are arrays of <em>column</em> values:</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(2016)
syms = 'abcde'
na_price_ar = {}
for symbol in syms[:5]:
# price_p ... | python|arrays|pandas|numpy|dataframe | 4 |
10,097 | 38,668,788 | Nested "ifs" on pandas df columns | <p>I have a pandas df called data.</p>
<p>I want to do something like:</p>
<pre><code>for i in range(data["col1"].count()):
if data["col1"][i] > 25:
count1 += 1
if data["col2"][i] > 35:
count2 += 1
</code></pre>
<p>and possibly with more columns so that I can keep track of when several conditio... | <p>This is a better way to go:</p>
<pre><code>cond1 = data.col1 > 25
cond2 = data.col2 > 35
count1 = cond1.sum()
count2 = (cond1 & cond2).sum()
</code></pre> | python|pandas | 3 |
10,098 | 9,767,773 | Calculating SimRank using NetworkX? | <p>I was wondering how can we can use the python module <code>networkX</code> to implement <a href="http://en.wikipedia.org/wiki/SimRank" rel="noreferrer">SimRank</a> to compare the similarity of 2 nodes? I understand that <code>networkX</code> provides methods for looking at neighbors, and link analysis algorithms suc... | <p><strong>Update</strong>
I implemented an networkx_addon library. SimRank is included in the library. Check out: <a href="https://github.com/hhchen1105/networkx_addon" rel="noreferrer">https://github.com/hhchen1105/networkx_addon</a> for details.</p>
<p>Sample Usage:</p>
<pre><code> >>> import network... | python|graph-algorithm|networkx | 16 |
10,099 | 1,692,107 | Performance difference in alternative switches in Python | <p>I have read a few articles around alternatives to the switch statement in Python. Mainly using dicts instead of lots of if's and elif's. However none really answer the question: is there one with better performance or efficiency? I have read a few arguments that if's and elifs would have to check each statement and ... | <p><code>dict</code>'s perfomance is typically going to be unbeatable, because a lookup into a <code>dict</code> is going to be O(1) except in rare and practically never-observed cases (where they key involves user-coded types with lousy hashing;-). You don't have to "create new modules" as you say, just arbitrary cal... | python|performance|switch-statement | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.