qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
42,289,722 | I have the python code where I pass the json file
```
def home():
with open('file.json', 'a+') as f:
return render_template('index.html', json_data=f.read())
```
The file look like this
```
{"hosts": [{"shortname": "serv1", "ipadr": "10.0.0.1", "longname": "server1"}, {"shortname": "serv2", "ipadr": "10... | 2017/02/17 | [
"https://Stackoverflow.com/questions/42289722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7528895/"
] | Try this : Here `DATEADD(yy, DATEDIFF(yy,0,getdate())` will give start month of the year
```
DA.Access_Date >= DATEADD(YEAR, -2, DATEADD(YY, DATEDIFF(YY,0,GETDATE()), 0))
``` | Your condition should be like below. `DATEADD(YEAR,DATEDIFF(YEAR, 0, GETDATE())-2,0)` this will returns first day of `2015` year.
```
DA.Access_Date >= DATEADD(YEAR,DATEDIFF(YEAR, 0, GETDATE())-2,0)
``` | 4,213 |
60,945,866 | I've created flask app and try to dockerize it. It uses machine learning libraries, I had some problems with download it so my Dockerfile is a little bit messy, but Image was succesfully created.
```
from alpine:latest
RUN apk add --no-cache python3-dev \
&& pip3 install --upgrade pip
WORKDIR /app
COPY . /app
FROM... | 2020/03/31 | [
"https://Stackoverflow.com/questions/60945866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9802634/"
] | The problem is here:
`RUN pip3 freeze > requirements.txt`
The `>` operator in bash overwrites the content of the file. If you want to append to your `requirements.txt`, consider using `>>` operator:
`RUN pip3 freeze >> requirements.txt` | Thank you All. Finally I rebuilded my app, simplified requirements, exclude alpine and use python 3.7 in my Dockerfile.
I could run app locally, but Docker probably could not find some file from path, or get some other error from app, that is why it stopped just after starting. | 4,217 |
43,648,081 | I have a pickle file that was created with python 2.7 that I'm trying to port to python 3.6. The file is saved in py 2.7 via `pickle.dumps(self.saved_objects, -1)`
and loaded in python 3.6 via `loads(data, encoding="bytes")` (from a file opened in `rb` mode). If I try opening in `r` mode and pass `encoding=latin1` to ... | 2017/04/27 | [
"https://Stackoverflow.com/questions/43648081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2682863/"
] | In short, you're hitting [bug 22005](http://bugs.python.org/issue22005) with `datetime.date` objects in the `RentalDetails` objects.
That can be worked around with the `encoding='bytes'` parameter, but that leaves your classes with `__dict__` containing bytes:
```
>>> library = pickle.loads(pickle_data, encoding='byt... | >
> **Question**: Porting pickle py2 to py3 strings become bytes
>
>
>
The given `encoding='latin-1'` below, is ok.
Your Problem with `b''` are the result of using `encoding='bytes'`.
This will result in dict-keys being unpickled as bytes instead of as str.
The Problem data are the `datetime.date values '\x07... | 4,218 |
26,963,534 | I'm trying to complete a dice game python (3.4) programming assignment for school and I'm having some trouble passing a variable from one function to another using a return statement, but when I run the program the variable "diesum" is interpreted as undefined.
```
import random
def RollDice():
die1 = random.rand... | 2014/11/16 | [
"https://Stackoverflow.com/questions/26963534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4259262/"
] | You are not passing the result of `RollDice` into `Craps`. Try this instead:
```
result = RollDice()
Craps(result)
```
There are some other issues in the snippet that you have pasted, but this is the main reason that your are seeing an error. The `return` statement returns a value from a function. You need to bind t... | There are many reasons since it does not work.. first simplify the problem! This is a working initial example:
```
import random
def RollDice():
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
diesum = die1 + die2
print(diesum)
return diesum
def Craps(diesum):
craps = [2, 3, 12]
n... | 4,220 |
64,575,063 | ```
import pandas as pd
data = pd.read_excel (r'C:\Users\royli\Downloads\Product List.xlsx',sheet_name='Sheet1' )
df = pd.DataFrame(data, columns= ['Product'])
print (df)
```
*****Error Message*****
```
Traceback (most recent call last):
File "main.py", line 3, in <module>
Traceback (most recent call last):
Fi... | 2020/10/28 | [
"https://Stackoverflow.com/questions/64575063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14526349/"
] | There are 3 ways to solve this:
1. If the git repository is on your Windows machine, [configure Beyond Compare as an external difftool](https://www.scootersoftware.com/support.php?zz=kb_vcs#gitwindows), then run
`git difftool --dir-diff` to launch a diff in the Folder Compare.
2. If you can install Beyond Compare for ... | I just faced a similar problem, and wrote a script to allow using Beyond Compare as a Git difftool, with BC being installed locally, and the Git workspace residing on a remote machine: <https://github.com/mbikovitsky/beyond-ssh>. | 4,221 |
69,792,060 | I'm fairly new to programming in general and have been learning python3 for the last week or so. I tried building a dice roller and ran into an issue when asking the user if they wanted to repeat the roller or end the program.
```
import random as dice
d100 = dice.randint(1,100)
d20 = dice.randint(1,20)
d10 = dice.ra... | 2021/11/01 | [
"https://Stackoverflow.com/questions/69792060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17296020/"
] | It's a problem of precedence: `repeat == 'Y' or 'y' or 'yes' or 'Yes'` is interpreted as `(repeat == 'Y') or 'y' or 'yes' or 'Yes'` and then it tries to check whether `'y'` counts as true, which it does (it's a non-empty string).
What you want is `while repeat in ('Y', 'y', 'yes', 'Yes'):`
By the way, you don't need ... | Two things
`continue` means go to the top of the loop (and then check whether to re-enter it), not guaranteed to go through the loop again. It might be better named skip because it really means "skip the rest of this iteration". Hence you don't need `if ... continue` because you're already at the end of the iteration.... | 4,222 |
71,164,536 | I'm just trying to make a very simple entry widget and grid it on the window but I keep getting an error. Anyway I can fix it?
code:
```
e = tk.Entry(root, borderwidth=5, width=35)
e.grid(root, row=0,column=0, columnspan=3, padx=10, pady=10)
```
Error:
```
Traceback (most recent call last):
File "C:\Users\mosta... | 2022/02/17 | [
"https://Stackoverflow.com/questions/71164536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You need to remove the argument `root` from the `grid` command.
```
e.grid(row=0,column=0, columnspan=3, padx=10, pady=10)
``` | By using the .place() method instead of the .grid() method, I have successfully gotten the Entry widget to work.
```
from tkinter import *
root = Tk()
e = Entry(root, borderwidth=5)
e.place(x=10, y=10, height=25, width=180)
```
I hope that this helps :-) | 4,223 |
26,313,761 | I know that [**si**](https://stackoverflow.com/questions/12160766/install-packages-with-portable-python "One Stack Overflow question.")[*mi*](https://stackoverflow.com/questions/16754614/adding-libraries-to-portable-python?rq=1 "Another Stack Overflow question.")[**la**](https://stackoverflow.com/questions/13119671/pyg... | 2014/10/11 | [
"https://Stackoverflow.com/questions/26313761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3787376/"
] | Implement your `Oggetto` class using standard JavaFX Properties:
```
import javafx.beans.property.BooleanProperty ;
import javafx.beans.property.IntegerProperty ;
import javafx.beans.property.SimpleBooleanProperty ;
import javafx.beans.property.SimpleIntegerProperty ;
public class Oggetto {
private final Integer... | ```
import javafx.beans.InvalidationListener;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
public class VerySimply implements ObservableValue<Integer> {
private int newValue;
public ChangeListener<Integer> listener = new ChangeListener<Integer>() {
@Override
... | 4,224 |
60,493,027 | I am reading the book Hacking: The art of exploitation and there is a format string exploit example which attempts to overwrite an address of the dtors
with the address of a shellcode environment variable.
I work on Kali Linux 64-bit and already found out that there are no dtors (destructors of a c program) and so now ... | 2020/03/02 | [
"https://Stackoverflow.com/questions/60493027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12737461/"
] | Relocations and low addresses like this one:
```
0000000000003de8 R_X86_64_RELATIVE *ABS*+0x0000000000001170
```
suggest that the executable has been built as PIE (position-independent executable), with full address space layout randomization (ASLR). This means that the addresses do not match the static view from `... | Probably, you can use 「-Wl,-z,norelro」 to disable RELRO. | 4,225 |
7,097,058 | >
> **Possible Duplicate:**
>
> [How to convert strings into integers in python?](https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python)
>
>
>
I need to change a list of strings into a list of integers how do i do this
i.e
('1', '1', '1', '1', '2') into (1,1,1,1,2). | 2011/08/17 | [
"https://Stackoverflow.com/questions/7097058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/899084/"
] | Use [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions):
```
strtuple = ('1', '1', '1', '1', '2')
intlist = [int(s) for s in strtuple]
```
Stuff for completeness:
=======================
As your “list” is in truth a [tuple](http://docs.python.org/library/stdtypes.html#type... | Use the `map` function.
```
vals = ('1', '1', '1', '1', '2')
result = tuple(map(int, vals))
print result
```
Output:
```
(1, 1, 1, 1, 2)
```
A performance comparison with the list comprehension:
```
from timeit import timeit
print timeit("map(int, vals)", "vals = '1', '2', '3', '4'")
print timeit("[int(s) for s ... | 4,226 |
429,648 | Is there a library to do pretty on screen display with Python (mainly on Linux but preferably available on other OS too) ? I know there is python-osd but it uses [libxosd](http://sourceforge.net/projects/libxosd) which looks quite old. I would not call it *pretty*.
Maybe a Python binding for [libaosd](http://cia.vc/st... | 2009/01/09 | [
"https://Stackoverflow.com/questions/429648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49808/"
] | Actually, xosd isn't all that old; I went to university with the original author (Andre Renaud, who is a superlative programmer). It is quite low level, but pretty simple - xosd.c is only 1365 lines long. It wouldn't be hard to tweak it to display pretty much anything you want. | Using PyGTK on X it's possible to scrape the screen background and composite the image with a standard Pango layout.
I have some code that does this at <http://svn.sacredchao.net/svn/quodlibet/trunk/plugins/events/animosd.py>. It's a bit ugly and long, but mostly straightforward. | 4,231 |
64,090,872 | I have a for loop in Pygame that is trying to slowly progress through a string, like how text scrolls in RPGs. I want it to wait around 7 milliseconds before displaying the next character in the string, but I don't know how to make the loop wait that long without stopping other stuff.
Please note that I am very new to ... | 2020/09/27 | [
"https://Stackoverflow.com/questions/64090872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14089022/"
] | You don't need the `for` loop at all. You have an application loop, so use it. The number of milliseconds since `pygame.init()` can be retrieved by [`pygame.time.get_ticks()`](https://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks). See [`pygame.time`](https://www.pygame.org/docs/ref/time.html) module.
```py
... | use this
```
@coroutine
def my_func():
from time import sleep
mainText = pygame.font.Font(mainFont, 40)
finalMessage = ""
for letter in msg:
finalMessage = finalMessage + letter
renderMainText = mainText.render(finalMessage, True, white)
screen.blit(renderMainText, (100, 100))
... | 4,234 |
60,775,172 | I used pyenv to install python 3.8.2 and to create a virtualenv.
In the virtualenv, I used pipenv to install `pandas`.
However, when importing pandas, I'm getting the following:
```
[...]
File "/home/luislhl/.pyenv/versions/poc-prefect/lib/python3.8/site-packages/pandas/io/common.py", line 3, in <module>
impo... | 2020/03/20 | [
"https://Stackoverflow.com/questions/60775172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3477266/"
] | On macOS Big Sur, to get pyenv ( via homebrew ) to work I had to install zlib and bzip2 via homebrew and then add the exports in my ~/.zshrc ( or ~/.bashrc for bash I guess). The answer above [by luislhl](https://stackoverflow.com/q/60775172/2117661) leads the way to my solution.
```
brew install zlib bzip2
#Add the ... | Ok, I have found the solution after some time. It was simple, but I took some time to realize it.
It turns out the problem was the `bzip2-devel` I had installed was a 32-bit version.
The compilation process was looking for the 64-bit one, and didn't find it.
So I had to specifically install the 64-bit version:
```
s... | 4,235 |
59,118,639 | On a **Ubuntu 18.04** machine I am trying to use **opencv 4.1.2** [facedetect](https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-bad/html/gst-plugins-bad-plugins-facedetect.html) in a **gstreamer 1.14.5** pipeline but unfortunately the plugin is not installed.
I downloaded the gstreamer [bad plugin... | 2019/11/30 | [
"https://Stackoverflow.com/questions/59118639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431063/"
] | Please don't dirty your Ubuntu. Prefer using any package manager in Ubuntu, that you like. If you use `apt`, just install ready and available package for you:
```
sudo apt install libgstreamer-plugins-bad1.0-dev
``` | I had the same problem, and my solution is if you want to use the GStreamer OpenCV Plugins described [here](https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-bad/html/gst-plugins-bad-plugins-plugin-opencv.html) and [here](https://gstreamer.freedesktop.org/documentation/opencv/?gi-language=c) you nee... | 4,240 |
57,502,112 | I am getting an attribute error while running the code given below:
```py
import base64
import subprocess
from __future__ import absolute_import, print_function
from pprint import pprint
import unittest
import webbrowser
import docusign_esign as docusign
from docusign_esign import AuthenticationApi, TemplatesApi,Envel... | 2019/08/14 | [
"https://Stackoverflow.com/questions/57502112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11929301/"
] | >
> this html code was built automatically by jquery so I can't add id or "onlick" event on this tag
>
>
>
If you can't control when that happens, you can still use event delegation to get involved in the click event:
```
$(document).on('click', '.fc-day-grid-event', function() {
...//
});
```
That works even i... | ```
<a onclick="doStuff(this)">Click Me</a>
``` | 4,241 |
64,525,357 | Hello i'm new to python.
i'm working with lists in python and i want to Convert a `list` named **graph** to `dictionnary` **graph** in `PYTHON`.
my have `list` :
```js
graph = [
['01 Mai',
[
['Musset', 5],
['Place 11 Decembre 1960', 4],
["Sidi M'hamed", 3],
['El Hamma (haut... | 2020/10/25 | [
"https://Stackoverflow.com/questions/64525357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11818297/"
] | A simple dict comprehension would do:
```py
as_dict = {k: dict(v) for k,v in graph}
```
[Playground](https://www.online-python.com/njzoZagLfc) | An easy solution would be:
```
for item in graph:
d[item[0]] = {record[0]: record[1] for record in item[1]}
``` | 4,246 |
57,532,371 | I have the following 8 (possibly non-unique) lists in python:
```
>>> a = [{9: {10:11}}, {}, {}]
>>> b = [{1:2}, {3:4}, {5:6}]
>>> c = [{}, {}, {}]
>>> d = [{1:2}, {3:4}, {5:6}]
>>> w = [{}, {}, {}]
>>> x = [{1:2}, {3:4}, {5:6}]
>>> y = [{}, {}, {}]
>>> z = [{1:2}, {3:4}, {5:6}]
```
I want to check if any combinatio... | 2019/08/17 | [
"https://Stackoverflow.com/questions/57532371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1742777/"
] | You can abuse [`frozenset`](https://docs.python.org/3/library/stdtypes.html#frozenset) by turning each list of dictionaries to a frozenset of frozensets, with the internal frozensets being each dictionary's items:
```
def freeze(li):
return frozenset(frozenset(d.items()) for d in li)
a = freeze(a)
b = freeze(b)
c... | @DeepSpace's answer works only if each sub-dict in a list is unique, since `[a, b, c, d]` should not be considered the same as `[a, a, b, c, d]`, but with @DeepSpace's use of the `set` constructor, they will be treated as the same.
To correctly account for possible duplicating items in the list, you can use `collectio... | 4,249 |
16,127,493 | This error broke my python-mysql installation on Mac 10.7.5. Here are the steps
1. The installed python is 2.7.1, mysql is 64 bit for 5.6.11.
2. The being installed python-mysql is 1.2.4, also tried 1.2.3
3. Configurations for the installation
```
1) sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql
2) Edit... | 2013/04/21 | [
"https://Stackoverflow.com/questions/16127493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351637/"
] | Try to Remove `cflags -Wno-null-conversion -Wno-unused-private-field` in
```
/usr/local/mysql/bin/mysql_config.
```
like:
```
cflags="-I$pkgincludedir -Wall -Os -g -fno-strict-aliasing -DDBUG_OFF -arch x86_64 " #note: end space!
``` | Wow, I've been spending a couple of hours on thistrying to 'pip install MySQL-python'. I have been re-installing Xcode 4.6.3, the Xcode command line tools seperatly (on Mac OS X 10.7.5), and installing Kenneth Reitz' stuff (<https://github.com/kennethreitz/osx-gcc-installer>) to no avail while I was ...
Altering the c... | 4,251 |
57,578,345 | Suppose i have the coefficients of a polynomial.How to write it in the usual form we write in pen and paper?E.g. if i have coefficients=1,-2,5 and the polynomial is a quadratic one then the program should print `x**2-2*x+5.
1*x**2-2*x**1+5*x**0` will also do.It is preferable that the program is written such that it wor... | 2019/08/20 | [
"https://Stackoverflow.com/questions/57578345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10444871/"
] | Here is a program that would work, without using the external packages. I have defined a Poly class and it has two methods: 1) evaluation 2) print the polynomial.
```
class Poly():
def __init__(self, coeff):
self.coeff = coeff
self.N = len(coeff)
def evaluate(self, x):
res = 0.0
... | For this task, you have to use python's symbolic module ([sympy](https://www.sympy.org/en/index.html)) since you specifically want your output to be a polynomial representation. The following code should do the job.
```
import sympy
from sympy import poly
x = sympy.Symbol('x') # Create a symbol x
coefficients = [1,... | 4,252 |
8,337,686 | Here is my `.bash_profile`
```
PYTHONPATH=".:/home/miki725/django/django:$PYTHONPATH"
export PYTHONPATH
```
So then I open python however the directory I add in `.bash_profile` is not the first one:
```
Python 2.4.3 (#1, Sep 21 2011, 20:06:00)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2
Type "help", "copyrig... | 2011/12/01 | [
"https://Stackoverflow.com/questions/8337686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485844/"
] | Your best bet is to modify `sys.path` at runtime. In a shared hosting enviroment it's common to do this in your .wsgi file. You could do something like this:
```
import sys
sys.path.insert(0, '/home/miki725/django/django')
```
If you add `export PYTHONSTARTUP=/home/miki725/.pythonrc` to your `.bash_profile`, you can... | I'd say that your `PYTHONPATH` is being modified when the [site](http://docs.python.org/release/2.4.3/lib/module-site.html) module is imported. Please have a look at the [user](http://docs.python.org/release/2.4.3/lib/module-user.html) module to provide user-specific configuration (basically just prepend the directorie... | 4,253 |
9,252,970 | It worked when I did the poll tutorial in linux, but I'm doing it again in Windows 7, and it does nothing.
I already set the environmental variables, and set the file association to my `python27.exe`
When I run `django-admin.py` startproject mysite from the DOS command prompt, it executes, but it's showing me all the... | 2012/02/12 | [
"https://Stackoverflow.com/questions/9252970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1159856/"
] | Try to run `python27 django-admin.py startproject mysite` from the command line,maybe a different (older) python.exe executes the `django-admin.py` file. If there's a program associated to the `.py` files, things mixes up, and your `path` environment variable doesn't matter.
I suggest you to use [virtualenv](http://p... | Great answers. But unfortunately it did not work for me. This is how I solved it
1. Opened `django_admin.py` as @wynston said. But the path at first line was already showing `#!C:\` correctly. So did not had to change it
2. I had to put `"..."` around `django-admin.py` address. Navigated to the project directory in `c... | 4,256 |
30,029,625 | I can't install [Rodeo](https://github.com/yhat/rodeo) with pip, on Ubuntu 14.04.2 LTS 64 bit (installed on a Virtual Box)
For information I'm a Python and Ubuntu beginner and I installed pip by following this [tutorial](http://www.liquidweb.com/kb/how-to-install-pip-on-ubuntu-14-04-lts/)
`pip -V`
`pip 6.1.1 from /u... | 2015/05/04 | [
"https://Stackoverflow.com/questions/30029625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2236787/"
] | You will need to install python-dev/libzmq-dev for the installation to succeed. The problem is that while you can install most Python libraries using pip, some of them depend on C or C++ libraries. These libraries cannot be downloaded using PIP, so they need to be installed manually.
As PIP will only install Python li... | As of Rodeo v2.0, it is no longer installable via pip. On Ubuntu, you can install it using the Rodeo apt repo, commands are below:
```
#### add the yhat public key and the repo
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 33D40BC6
sudo add-apt-repository -u "deb http://rodeo-deb.yhat.com/ rodeo main"
... | 4,266 |
21,592,965 | I am writing a small script for a Tic Tac Toe game in python. I store the Tic Tac Toe grid in a list like this (example of a empty grid): `[[' ', ' ', ' ',], [' ', ' ', ' ',], [' ', ' ', ' ',]]`. These are the following possible string for the list:
* `' '` no player has marked this field
* `'X'` player X
* `'O'` play... | 2014/02/06 | [
"https://Stackoverflow.com/questions/21592965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2911408/"
] | ```
x_lst = [' '] * size
lst = []
for y in range(size):
lst.append(x_lst)
```
All elements of `lst` are the same list object. If you want equal but independent lists, create a new list each time:
```
lst = []
for y in range(size):
lst.append([' '] * size)
``` | Your board consists of three references to a single row. You need to make three separate rows, like so:
```
lst = [[' ']*3 for _ in range(3)]
``` | 4,267 |
59,726,776 | My question :
I was working on my computer vision project. I use opencv(4.1.2) and python to implement it.
I need a faster way to pass the reading frame into image processing on my Computer(Ubuntu 18.04 8 cores i7 3.00GHz Memory 32GB). the `cv2.VideoCapture.read()` read frame (frame size : 720x1280) will take about ... | 2020/01/14 | [
"https://Stackoverflow.com/questions/59726776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9383559/"
] | This comes a bit late, but I was wondering this with my Logitech C920 HD Pro USB-camera on Ubuntu 20.04 and OpenCV. I tried to command the capture session to run Full HD @ 30 FPS but the FPS was fluctuating between 4-5 FPS.
The capture format for my camera defaulted as "YUYV 4:2:2". No matter how I tried to alter the ... | Long.
I checked using the following settings and somehow if you increase the frame size opencv will reduce the total fps. Maybe this is a bug.
1920x1080 : FPS: 5.0, Width: 1920.0, Height: 1080.0 , delay = 150ms
<https://imgur.com/Vab61cF>
1280x720 : FPS: 10.0, Width: 1280.0, Height: 720.0, delay = 60ms
<https://... | 4,268 |
1,475,193 | My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server.
Problem is that the server only handles one con... | 2009/09/25 | [
"https://Stackoverflow.com/questions/1475193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67022/"
] | This is an artifact of garbage collection. Even though the object is *out of scope*, it is not necessarily *collected* and therefore *destroyed* until a garbage collection run occurs -- this is not like C++ where a destructor is called as soon as an object loses scope.
You can probably work around this particular issu... | Ok, here's the final version. Explicitly close the socket objects when something gets borked.
```
import socket
class MyException(Exception):
pass
class MyClient(object):
def __init__(self, port):
self.sock = socket.create_connection(('localhost', port))
self.sockfile = self.sock.makefile()
... | 4,273 |
45,692,749 | Hello Python community I am angular and node.js developer and I want to try Python as backend of my server because I am new to python I want to ask you how to target the dist folder that contains all HTML and CSS and js files from the angular 4 apps in flask python server
Because my app is SPA application I have set r... | 2017/08/15 | [
"https://Stackoverflow.com/questions/45692749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6600549/"
] | Since I had this same problem, I hope this answer will help someone looking for it again.
1. First create your angular application and build it. (You will get all the required js files and index.html file inside the 'dist' folder.
2. Create your python + flask web app with required end points.
```
from flask import F... | I don't think that it's possible to access Angular 'dist' directory via a REST API. Any routing should be done on the client-side with Angular, and Flask should handle your end-points.
In terms of building your REST API, I'd recommend something like this:
```
from flask import Flask, jsonify
app = Flask(__name__)
... | 4,278 |
35,253,338 | I am able to import the pandas package within the spyder ide; however, if I attempt to open a new juypter notebook, the import fails.
I use the Anaconda package distribution on MAC OS X.
Here is what I do:
```
In [1]: import pandas
```
and this is the response I get:
```
---------------------------------------... | 2016/02/07 | [
"https://Stackoverflow.com/questions/35253338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3902319/"
] | You have more than one Python 2 engines installed. One in your main OS platform, another one inside Anaconda's virtual environment. You need to install Panda on the latter.
Run in your Bash prompt:
```
which python
```
Then run the following in Jupyter/IPython and compare the result with the output you got from th... | I had the same issue on Mac OS X with Anaconda (Python 2). I tried importing the pandas package in python repl, and got this error:
```
ValueError: unknown locale: UTF-8
```
Therefore, I've added the following lines to my ~/.bash\_profile:
```
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
```
And this has fix... | 4,279 |
67,558,323 | Here's the thing, I'm building a streamlit app to get the cohorts data. Just like explained here: <https://towardsdatascience.com/a-step-by-step-introduction-to-cohort-analysis-in-python-a2cbbd8460ea>. So, basically I'm now at the point where I have a dataframe with the cohort date (cohort), the number of customers tha... | 2021/05/16 | [
"https://Stackoverflow.com/questions/67558323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15317245/"
] | The function `enumerate` returns a tuple which is causing the `TypeError`. You can just keep a placeholder variable to separate the tuple into i and another placeholder variable, like this:
```
print(*[min(abs(i - j) for j in b) for i,_ in enumerate(a)])
```
Or alternatively, not use `enumerate` at all.
```
print(*... | the enumerate function is used to get the index and the data of the list at the same time.
so enumerate gives,
for data,index in enumerate(a) | 4,282 |
54,642,243 | I'm trying to make a program in python for a data networking class to read in a file that contains 8 characters such as 00111001 and put it in a packet to then be converted to ASCII. I want to iterate through the packet and if it's a 1 then add the number in the conversation\_list =[128,64,32,16,8,4,2,1] according to t... | 2019/02/12 | [
"https://Stackoverflow.com/questions/54642243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7092778/"
] | ```
int[][] winner = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}};
```
This is all possible cases when there is a winner. The first 3 is horizontal, the next 3 is vertical, the last 2 is diagonal, where the numbers are defined like this, indicated in the previous code:
``... | I am assuming you are asking about the for each loop:
```
for (int[] columnWinner : winner) {
```
The loop is called a for each loop that creates a variable and gives it a value for every iteration in the loop.
In this case, the loop creates an array of length 3 named columnWinner for each possible row, column, an... | 4,283 |
41,042,599 | I read that it is one of the advantages of xgboost, that you can train on an existing model. Say I trained my model for 100 iterations, and want to restart from there to finish another 100 iterations, instead of redoing everything from the scratch..
I found this in xgboost demo examples, from here <https://github.com/... | 2016/12/08 | [
"https://Stackoverflow.com/questions/41042599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/544102/"
] | figured it out, from this issue in xgboost repo <https://github.com/dmlc/xgboost/issues/235>
>
> Yes, this is something we overlooked when designing the interface, you should be able to set\_margin with flattened array.
>
>
>
`set_base_margin` expects a 1d array, so you just need to flatten the margined predictio... | Things have changed now....
```
bst = xgb.train(param, dtrain, 1, watchlist , xgb_model=bst )
``` | 4,285 |
21,613,906 | I've got a python script that writes some data to a pipe when called:
```
def send_to_pipe(s):
send = '/var/tmp/mypipe.pipe'
sp = open(send, 'w')
sp.write(json.dumps(s))
sp.close()
if __name__ == "__main__":
name = sys.argv[1]
command = sys.argv[2]
s = {"name":name, "command":command}
... | 2014/02/06 | [
"https://Stackoverflow.com/questions/21613906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3272993/"
] | I think I don't understand exactly what you want.
* Option A:
\*\* Signal R. Server: Hosted as a Windows Service
\*\* Signal R. Client: ASP.NET MVC Application.
* Option B
\*\* Signal R. Server: ASP.NET MVC Application.
\*\* Signal R. Client: Windows Service
If what you need is Option A. You might want to take... | This tutorial may help, and it also includes some sample code:
<http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-getting-started-with-signalr-20> | 4,286 |
49,835,559 | After installing Ubuntu as WSL(Windows Subsystem for Linux) I've run:
```
root@teclast:~# python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 ...
```
and try to access to this web server from my windows machine `http://0.0.0.0:8000` or `http://192.168.1.178:8000` but no success, web server available only by th... | 2018/04/14 | [
"https://Stackoverflow.com/questions/49835559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1441863/"
] | Please follow the steps mentioned in the [link](https://www.nextofwindows.com/allow-server-running-inside-wsl-to-be-accessible-outside-windows-10-host) shared by @erazerbrecht and run your HTTP server by providing your ip address (instead of using localhost) and port number.
example:
```
Serving HTTP on 192.168.1.178... | I followed [the answer by @toran-sahu](https://stackoverflow.com/a/51998308/8917310) about adding an inbound rule to Windows Defender Firewall but recently (after adding a 2nd wsl2 instance) it stopped working again. I came across [this issue thread](https://github.com/microsoft/WSL/issues/4204) and running the followi... | 4,291 |
39,878,262 | I have very large log file, which contains log of service restart messages. After I initiated service restart with external command I need to tail this log file from last occurrence of reboot message and check following messages to confirm correct restart procedure. I'm analysing messages by python, so only find last o... | 2016/10/05 | [
"https://Stackoverflow.com/questions/39878262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777415/"
] | give a generous buffer value, reverse, extract, reverse
```
$ tail -1000 file | tac | awk '1,/Rebooting/' | tac
```
or, replace `awk` script with `!p; /Rebooting/{p=1}` | Perhaps something like:
```
tail -fn +$(awk '/Rebooting/ { line = NR } END { print(line) }' log) log
```
which uses `awk` to find the line number of the last occurrence of the pattern and then tails starting at that line.
This still scans the entire file, though.
If you're really doing it from python, you can prob... | 4,301 |
18,520,203 | I just installed the 'eve demo' I can't get it to start working.
The error is:
>
> eve.io.base.ConnectionException: Error initializing the driver. Make sure the database serveris running. Driver exception: OperationFailure(u"command SON([('authenticate', 1), ('user', u'user'), ('nonce', u'cec66353cb35b6f5'), ('key'... | 2013/08/29 | [
"https://Stackoverflow.com/questions/18520203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615737/"
] | It looks like the MongoDB user/pw combo you configured in your `settings.py` has not been set at the db level. From the mongo shell type `use <dbname>`, then `db.system.users.find()` to get a list of authorized users for `<dbname>`. It is probably empty; add the user as needed (see the [MongoDB docs](http://docs.mongod... | 1. get your mongodb's dbname,username and password from setting.py,eg:
```
MONGO_USERNAME = 'username'
MONGO_PASSWORD = 'password'
MONGO_DBNAME = 'apitest'
```
2. login in mongod server with mongo,and make sure your username in dbname's system.user collection.you can query authenticated users in that database with ... | 4,302 |
74,618,712 | I want to read the data on an excel file within a F drive. I am using python on Visual Studio Code to try achieve this however I am getting an error as seen in the pictures below. I installed pandas but I still get an error. How can I fix this issue?
[Coding Error](https://i.stack.imgur.com/XFyH4.png)
[Installed Pand... | 2022/11/29 | [
"https://Stackoverflow.com/questions/74618712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20636206/"
] | You should try to open terminal in VS Code, and run `pip freeze` (and `pip3 freeze`). Check if you find pandas in the results, it won't. That must be because you'd have multiple installations of Python on your system. You may do any one of the below -
1. Get rid of all but one Python installation.
2. Install pandas on... | To read an Excel file with Python, you need to install the pandas library. To install pandas, open the command line or terminal and type:
pip install pandas
Once pandas is installed, you can read an Excel file like this:
import pandas as pd
df = pd.read\_excel('file\_name.xlsx')
print(df)
You should also make sur... | 4,303 |
23,516,150 | I created a thread for a keylogger that logs in parallel to another thread that produces some sounds ( I want to catch reaction times).
Unfortunately, the thread never finishes although i invoke killKey() and "invoked killkey()" is printed.
I allways get an thread.isActive() = true from this thread.
```
class KeyHan... | 2014/05/07 | [
"https://Stackoverflow.com/questions/23516150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2720827/"
] | PostQuitMessage has to be posted from the same thread. To do so you need to introduce a global variable `STOP_KEY_HANDLER`. If you want to quit then just set global `STOP_KEY_HANDLER = True` from any thread you want and it will quit with the next keystroke. Your key handler has to run on the main thread.
```
STOP_KEY... | I guess pbackup's solution is fine. Just to conclude I found a solution by simply sending a key myself instead of waiting for the user to input. It's proably not the best but was the fastest an goes parallel in my timing thread with the other timing routines.
```
STOP_KEY_HANDLER = True
# send key to kill han... | 4,304 |
60,961,248 | ```py
bigger_list_of_names = ['Jim', 'Bob', 'Fred', 'Cam', 'Reagan','Alejandro','Dee','Rana','Denisha','Nicolasa','Annett','Catrina','Louvenia','Emmanuel','Dina','Jasmine','Shirl','Jene','Leona','Lise','Dodie','Kanesha','Carmela','Yuette',]
name_list = ['Jim', 'Bob', 'Fred', 'Cam']
search_people = re.compile(r'\b({})\b... | 2020/03/31 | [
"https://Stackoverflow.com/questions/60961248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13176034/"
] | The second argument to a compiled regular expression is the position in the string to start searching, not flags to use with the regex (the third, also optional argument, is the ending position to search). See the docs for [Regular expression objects](https://docs.python.org/3/library/re.html?highlight=re#re.Pattern.se... | What you are trying to do, does not require a regex search. You can achieve the same as follows.
```py
search_result = []
targets = set(names_list)
for name in set(bigger_list_of_names):
if name in targets:
search_result.append(name)
print(f'Found name: {name}')
else:
print(f'Did not fi... | 4,305 |
41,965,187 | To test my tensorflow installation I am using the mnist example provided in tensorflow repository, but when I execute the convolutional.py script I have this output:
```
I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcublas.so.8.0 locally
I tensorflow/stream_executor/dso_loader... | 2017/01/31 | [
"https://Stackoverflow.com/questions/41965187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3094625/"
] | The important points in the output you have shown is this:
```
I tensorflow/core/common_runtime/gpu/gpu_device.cc:885] Found device 0 with properties:
name: GeForce GTX 980 Ti
major: 5 minor: 2 memoryClockRate (GHz) 1.2405
pciBusID 0000:03:00.0
Total memory: 5.93GiB
Free memory: 5.83GiB
```
i.e. the compute device ... | I encountered a similar error when I attempted to run the `classify_image.py` script that is part of [the image recognition tutorial](https://www.tensorflow.org/tutorials/image_recognition). Since I already had a running Python session (elpy) in which I had run some TensorFlow code, the GPUs were allocated there and th... | 4,307 |
39,775,489 | I'm trying to push a new git repo upstream using gitpython module. Below are the steps that I'm doing and get an error 128.
```
# Initialize a local git repo
init_repo = Repo.init(gitlocalrepodir+"%s" %(gitinitrepo))
# Add a file to this new local git repo
init_repo.index.add([filename])
# Initial commit
init_repo.i... | 2016/09/29 | [
"https://Stackoverflow.com/questions/39775489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2170456/"
] | I tracked it down with a similar approach:
```
class ProgressPrinter(git.RemoteProgress):
def line_dropped(self, line):
print("line dropped : " + str(line))
```
Which you can then call in your code:
```
init_repo.remotes.origin.push(progress=ProgressPrinter())
``` | You need to capture the output from the git command.
Given this Progress class:
```
class Progress(git.RemoteProgress):
def __init__( self ):
super().__init__()
self.__all_dropped_lines = []
def update( self, op_code, cur_count, max_count=None, message='' ):
pass
def line_droppe... | 4,308 |
19,546,631 | I'm trying to extract values from numerous text files in python. The numbers I require are in the scientific notation form. My result text files are as follows
```
ADDITIONAL DATA
Tip Rotation (degrees)
Node , UR[x] , UR[y] , UR[z]
21 , 1.0744 , 1.2389 , -4.3271
22 , -1.0744 , -1.2389 , -4.3271
53 ... | 2013/10/23 | [
"https://Stackoverflow.com/questions/19546631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739143/"
] | Is this format of file standard one? If so? you can get all your float values with another technic.
So, here is the code:
```py
str = """ ADDITIONAL DATA
Tip Rotation (degrees)
Node , UR[x] , UR[y] , UR[z]
21 , 1.0744 , 1.2389 , -4.3271
22 , -1.0744 , -1.2389 , -4.3271
53 , 0.9670 , 1.0307 ,... | I don't get the need for regex, to be honest. Something like this should do what you need:
```
with open(fileName) as f:
for line in f:
if line.startswith('Partition line'):
number=float(line.split(',')[1])
print number # or do whatever you want with it
# read other file con... | 4,309 |
58,033,457 | Hey im trying to create a postgresql db container, im running it using the command:
```
docker-compose up
```
on the following compose file:
```
version: '3.1'
services:
db:
image: postgres
restart: always
environment:
POSTGRES_USERNAME: admin
POSTGRES_PASSWORD: admin
POSTGRES_DB: d... | 2019/09/20 | [
"https://Stackoverflow.com/questions/58033457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5273907/"
] | Using POSTGRES\_USER instead of POSTGRES\_USERNAME solved this for me. | You should use POSTGRES\_USER instead of POSTGRES\_USERNAME.
Here is my postgres docker-compose configuration for your reference.
```
version: '3'
services:
postgres:
image: 'mdillon/postgis:latest'
environment:
- TZ=Asia/Shanghai
- POSTGRES_USER=postgres
- POS... | 4,310 |
46,708,708 | I'm looking at the best way to compare strings in a python function compiled using numba jit (no python mode, python 3).
The use case is the following :
```
import numba as nb
@nb.jit(nopython = True, cache = True)
def foo(a, t = 'default'):
if t == 'awesome':
return(a**2)
elif t == 'default':
... | 2017/10/12 | [
"https://Stackoverflow.com/questions/46708708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3640767/"
] | For newer numba versions (0.41.0 and later)
===========================================
Numba (since version 0.41.0) support [`str` in nopython mode](http://numba.pydata.org/numba-doc/0.42.0/reference/pysupported.html#str) and the code as written in the question will "just work". However for your example comparing the... | I'd suggest accepting @MSeifert's answer, but as a another option for these types of problems, consider using an `enum`.
In python, strings are often used as a sort of enum, and you `numba` has builtin support for enums so they can be used directly.
```
import enum
class FooOptions(enum.Enum):
AWESOME = 1
DE... | 4,311 |
33,009,295 | Got kinda surprised with:
```
$ node -p 'process.argv' $SHELL '$SHELL' \t '\t' '\\t'
[ 'node', '/bin/bash', '$SHELL', 't', '\\t', '\\\\t' ]
$ python -c 'import sys; print sys.argv' $SHELL '$SHELL' \t '\t' '\\t'
['-c', '/bin/bash', '$SHELL', 't', '\\t', '\\\\t']
```
Expected the same behavior as with:
```
$ echo $S... | 2015/10/08 | [
"https://Stackoverflow.com/questions/33009295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681785/"
] | Use `$'...'` form to pass escape sequences like `\t`, `\n`, `\r`, `\0` etc in BASH:
```
python -c 'import sys; print sys.argv' $SHELL '$SHELL' \t $'\t' $'\\t'
['-c', '/bin/bash', '$SHELL', 't', '\t', '\\t']
```
As per `man bash`:
>
> Words of the form `$'string'` are treated specially. The word expands to string, ... | In both python and node.js, there is a difference between the way `print` works with scalar strings and the way it works with collections.
Strings are printed simply as a sequence of characters. The resulting output is generally what the user expects to see, but it cannot be used as the representation of the string in... | 4,312 |
39,237,350 | How do I remove consecutive duplicates from a list like this in python?
```
lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
```
Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list.
I want the result to be like this:
```
newlst = [1,2,4,1,3,5]
```
Wou... | 2016/08/30 | [
"https://Stackoverflow.com/questions/39237350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5758484/"
] | [itertools.groupby()](https://docs.python.org/3/library/itertools.html#itertools.groupby) is your solution.
```
newlst = [k for k, g in itertools.groupby(lst)]
```
---
If you wish to group and limit the group size by the item's value, meaning 8 4's will be [4,4], and 9 3's will be [3,3,3] here are 2 options that do... | You'd probably want something like this.
```
lst = [1, 1, 2, 2, 2, 2, 3, 3, 4, 1, 2]
prev_value = None
for number in lst[:]: # the : means we're slicing it, making a copy in other words
if number == prev_value:
lst.remove(number)
else:
prev_value = number
```
So, we're going through the list,... | 4,313 |
44,859,860 | I want to implement the following function in python:
[](https://i.stack.imgur.com/MJfQu.png)
I will write the code using 2-loops:
```
for i in range(5):
for j in range(5):
sum += f(i, j)
```
But the issue is that I have 20 such si... | 2017/07/01 | [
"https://Stackoverflow.com/questions/44859860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7737948/"
] | You can use [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product) to get cartesian product (of indexes for your cases):
```
>>> import itertools
>>> for i, j, k in itertools.product(range(1, 3), repeat=3):
... print(i, j, k)
...
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2
... | Create Arrays by using Numpy .
```
import numpy as np
i = np.asarray([i for i in range(5)])
j = np.asarray([i for i in range(5)])
res = np.sum(f(i,j))
```
so you can avoide all loops. Important to note is that the function f needs to be able to work with array (a so called ufunc). If your f is mor... | 4,323 |
11,706,505 | I just started learning python and I am hoping you guys can help me comprehend things a little better. If you have ever played a pokemon game for the gameboy you'll understand more as to what I am trying to do. I started off with a text adventure where you do simple stuff, but now I am at the point of pokemon battling ... | 2012/07/29 | [
"https://Stackoverflow.com/questions/11706505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1364915/"
] | If I was to have `fight` as a instance method (which I'm not sure I would), I would probably code it up something like this:
```
class Pokemon(object):
def __init__(self,name,hp,damage):
self.name = name #pokemon name
self.hp = hp #hit-points of this particular pokemon
self.dama... | 1. You don't need the variables up the top. You just need them in the **init**() method.
2. The fight method should return a value:
```
def fight(self, target):
target.nHealth -= self.nAttack
return target
```
3. You probably want to also check if someone has lost the battle:
```
def checkWin(myPoke, target... | 4,324 |
4,414,767 | I'm trying to modify an existing [Django Mezzanine](http://mezzanine.jupo.org/) setup to allow me to blog in Markdown. Mezzanine has a "Core" model that has content as an HtmlField which is defined like so:
```
from django.db.models import TextField
class HtmlField(TextField):
"""
TextField that stores HT... | 2010/12/11 | [
"https://Stackoverflow.com/questions/4414767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147562/"
] | If you mean back references, then yes Java has this. You can refer to a capturing group inside a regular expression using the notation `\1` for the first group, `\2` for the second, etc. Note that inside a string literal the backslashes must be escaped. | The Java `java.util.regex.Pattern` class supports backreferences using the `\n` syntax.
See [the documentation](http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html) for more details. | 4,326 |
18,269,218 | I'm trying to use django's queryset API to emulate the following query:
```
SELECT EXTRACT(year FROM chosen_date) AS year,
EXTRACT(month FROM chosen_date) AS month,
date_paid IS NOT NULL as is_paid FROM
(SELECT (CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date,* FROM invoice_invoice) as t1... | 2013/08/16 | [
"https://Stackoverflow.com/questions/18269218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122757/"
] | Well here're some workarounds
**1.** In your particular case you could do it with one extra:
```
if use_date_due:
sum_qs = sum_qs.extra(select={
'year': 'EXTRACT(year FROM coalesce(date_due, date))',
'month': 'EXTRACT(month FROM coalesce(date_due, date))',
... | Would this work?:
```
from django.db import connection, transaction
cursor = connection.cursor()
sql = """
SELECT
%s AS year,
%s AS month,
date_paid IS NOT NULL as is_paid
FROM (
SELECT
(CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date, *
... | 4,327 |
67,800,225 | I have elastic search cluster.
Currently designing a python service for client for read and write query to my elastic search. The python service will not be maintained by me. Only internally python service will call our elastic search for fetching and writing
Is there any way to configure the elastic search so that w... | 2021/06/02 | [
"https://Stackoverflow.com/questions/67800225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8989219/"
] | ```
SELECT id
FROM books EXCEPT (
SELECT bookid FROM books_authors WHERE authorId='A2'
)
``` | ```
SELECT * FROM books
WHERE id NOT IN
(SELECT bookid FROM books_authors WHERE authorid = 'A2')
``` | 4,334 |
63,483,417 | Say I have a dataframe
```
id category
1 A
2 A
3 B
4 C
5 A
```
And I want to create a new column with incremental values where `category == 'A'`. So it should be something like.
```
id category value
1 A 1
2 A 2
3 B NaN
4 C NaN
5 A 3
```
Curre... | 2020/08/19 | [
"https://Stackoverflow.com/questions/63483417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1676881/"
] | The following code for GNU sed:
```
sed 's/EndHere/&\n/g; s/\(StartHere\)[^\n]*\(EndHere\|$\)/\1\2/g; s/\n//g' <<EOF
StartHere Word1 EndHere
StartHere Word2
StartHere Word2 EndHere something else
something else StartHere Word2 EndHere something else
EOF
```
outputs:
```
StartHereEndHere
StartHere
StartHereEndHere s... | Instead of using `sed`, you could do it with Perl, which supports [negative lookahead](http://www.regular-expressions.info/lookaround.html).
Using the example you gave in your comment:
```
$ echo "oooo StartHere=Yo9897 EndHereYo" \
| perl -pe 's/(StartHere) (?: .*(EndHere) | .*(?!EndHere) )/$1$2/x'
```
would outp... | 4,339 |
42,357,563 | I am thinking of different ways to take the sum of squares in python. I have found that the following works using list comprehensions:
```
def sum_of_squares(n):
return sum(x ** 2 for x in range(1, n))
```
But, when using lambda functions, the following does not compute:
```
def sum_of_squares_lambda(n):
re... | 2017/02/21 | [
"https://Stackoverflow.com/questions/42357563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4382972/"
] | Think about what `reduce` does. It takes the output of one call and uses it as the first argument when calling the same function again. So imagine n is 4. Suppose you call your lambda `f`. Then you are doing `f(f(1, 2), 3)`. That is equivalent to:
```
(1**2 + 2**2)**2 + 3**2
```
Because the first argument to your la... | You're only supposed to square each successive element. `x**2 + y**2` squares the running total (`x`) as well as each successive element (`y`). Change that to `x + y**2` and you'll get the correct result. Note that, as mentioned in comments, this requires a proper initial value as well, so you should pass `0` as the op... | 4,340 |
36,663,727 | I have two UI windows created with QT Designer. I have two separate python scripts for each UI. What I'm trying to do is the first script opens a window, creates a thread that looks for a certain condition, then when found, opens the second UI. Then the second UI creates a thread, and when done, opens the first UI.
Th... | 2016/04/16 | [
"https://Stackoverflow.com/questions/36663727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5897068/"
] | Checkout the docs here:
<https://code.visualstudio.com/Docs/customization/colorizer>
You basically either get one from the marketplace or generate a basic editable file with yeoman.
You can also add themes even from color sublime as described here:
<https://code.visualstudio.com/docs/customization/themes> | Install theme from extensions from which you wish to start.
Then find where the theme got installed. On Windows it would be `%USERPROFILE%\.vscode\extensions`, see details in [Installing extensions](https://code.visualstudio.com/docs/extensions/install-extension).
There you'll find folder with theme, inside is `theme... | 4,346 |
26,259,870 | I am new to java (well I played with it a few times), and I am wondering:
=> How to do *fast* independent prototypes ? something like one file projects.
The last few years, I worked with python. Each time I had to develop some new functionality or algorithm, I would make a simple python module (i.e. file) just for it... | 2014/10/08 | [
"https://Stackoverflow.com/questions/26259870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1206998/"
] | Definitely take a look at [Spring Boot](http://docs.spring.io/spring-boot/docs/1.2.2.RELEASE/reference/htmlsingle/#getting-started-introducing-spring-boot). Relatively new project. Its aim is to remove initial configuration phase and spin up Spring apps quickly. You can think about it as convention over configuration w... | What does "develop and run independent code in this context" mean?
Do you mean "small standalone example code snippets?"
* Use the Maven exec plugin
* Write unit/integration tests
* Bring your Maven dependencies into something like a JRuby REPL | 4,347 |
32,934,653 | I am trying to load a CSV file into HDFS and read the same into Spark as RDDs. I am using Hortonworks Sandbox and trying these through the command line. I loaded the data as follows:
```
hadoop fs -put data.csv /
```
The data seems to have loaded properly as seen by the following command:
```
[root@sandbox temp]# h... | 2015/10/04 | [
"https://Stackoverflow.com/questions/32934653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1002903/"
] | I figured the answer out. I had to enter the complete path name of the HDFS file as follows:
```
data = sc.textFile('hdfs://sandbox.hortonworks.com:8020/data.csv')
```
The full path name is obtained from conf/core-site.xml | Error `org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: file:/data.csv`
It is reading from you local file system instead of hdfs.
Try providing file path like below,
```
data = sc.textFile("hdfs://data.csv")
``` | 4,348 |
69,395,204 | I have a list of dict I want to group by multiple keys.
I have used sort by default in python dict
```
data = [
[],
[{'value': 8, 'bot': 'DB', 'month': 9, 'year': 2020}, {'value': 79, 'bot': 'DB', 'month': 10, 'year': 2020}, {'value': 126, 'bot': 'DB', 'month':8, 'year': 2021}],
[],
[{'value': 222, 'bot': 'GEMBOT', '... | 2021/09/30 | [
"https://Stackoverflow.com/questions/69395204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9538877/"
] | Maybe try:
```
from pprint import pprint
import datetime
output_dict = []
for i in data:
if i:
for j in i:
for key, val in sorted(j.items()):
if key == "bot":
temp["bot"] = val
elif key == "value":
temp["value"] = val
elif key == "month":
month = date... | Maybe try:
```
output = []
for i in data:
if not i:
pass
for j in i:
output.append(j)
```
And then if you want to sort it, then you can use `sorted_output = sorted(ouput, key=lambda k: k['bot'])` to sort it by `bot` for example. If you want to sort it by date, maybe create a value that calcu... | 4,350 |
1,586,423 | I wrote a basic [Hippity Hop](http://www.facebook.com/careers/puzzles.php?puzzle_id=7) program in C, Python, and OCaml. Granted, this is probably not a very good benchmark of these three languages. But the results I got were something like this:
* Python: .350 seconds
* C: .050 seconds
* *interpreted* OCaml: .040 seco... | 2009/10/19 | [
"https://Stackoverflow.com/questions/1586423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | Time under 0.05 can be a simple noise. Repeat the main program enough times to actually get ~1s of execution time in C. (I mean repeating it in a loop in the program itself, not by running it again)
Did you compile your code with optimisations turned on? Did you try reducing the number of branches? (and comparisons)
... | I would be interested to see how much time is spent in get\_count().
I'm not sure how much it would matter, but you're reading in a long as a string, which means the string cannot be larger than 20 bytes, or 10 bytes (2^64 = some 20 character long decimal number, or 2^32 = some 10 character long decimal number), so yo... | 4,353 |
47,489,567 | I've been stuck on this one for hours now.
I'm making a homemade smarthome terminal, and have been tinkering with kivy for about 2 weeks and it's been great so far. I'm at the point where I want to show the temperature inside a label inside a screen. I've made an actionbar with 4 buttons that slides through screens whe... | 2017/11/25 | [
"https://Stackoverflow.com/questions/47489567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4977709/"
] | there is no id TempLabel in your menu
first thing, you must add the TempLabel in your kv:
```
...
<ScreenThermo>:
Label:
id: TempLabel
text: "stuff1"
...
```
then update the right label:
```
...
class Menu(BoxLayout):
manager = ObjectProperty(None)
def __init__(self,**kwargs):
s... | use a StringProperty
```
<ScreenThermo>:
Label:
#this is where i want my label that shows the temperature my sensor reads
text: root.thermo_text
class ScreenThermo(BoxLayout):
thermo_text = StringProperty("stuff")
...
```
then any time you want to seet the text just do
```
my_screen.ther... | 4,362 |
60,036,522 | **I am learning 'Automate the Boring Stuff with Python',
here is the code in the book:**
```
import csv, os
os.makedirs('headerRemoved', exist_ok=True)
#Loop through every file in the current working directory)
for csvFilename in os.listdir('C://Users//Xinxin//Desktop//123'):
if not csvFilename.endswith('.csv'... | 2020/02/03 | [
"https://Stackoverflow.com/questions/60036522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12831792/"
] | >
> but when I move the python program out of the csv folder, and run the code, then it shows
>
>
>
1) This is the problem. Try adding the directory of the files to your removeheader.py (first line):
```
import sys
sys.path.append(r'C:/Users/Xinxin/Desktop/123')
```
2) Store the files in the same location as th... | You can need get current directory. Then add current directory with file name.
Example:
```
currentDir = os.getcwd()
currentFileCSV = currentDir +"//" + csvFilename
csvFileObj = open(currentFileCSV)
``` | 4,365 |
31,090,479 | I think I'm not understanding something basic about python's argparse.
I am trying to use the Google YouTube API for python script, but I am not understanding how to pass values to the script without using the command line.
For example, [here](https://developers.google.com/youtube/v3/docs/videos/insert) is the exampl... | 2015/06/27 | [
"https://Stackoverflow.com/questions/31090479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3449806/"
] | Whether it is the best approach or not is really for you to figure out. But using argparse without command line is **easy**. I do it all the time because I have batches that can be run from the command line. Or can also be called by other code - which is great for unit testing, as mentioned. argparse is especially good... | Calling `parse_args` with your own list of strings is a common `argparse` testing method. If you don't give `parse_args` this list, it uses `sys.argv[1:]` - i.e. the strings that the shell gives. `sys.argv[0]` is the strip name.
```
args = argparser.parse_args(['--foo','foovalue','barvalue'])
```
It is also easy to ... | 4,366 |
16,213,235 | a methodology question:
I have a "main" python script which runs on an infinite loop on my system, and I want to send information to it (a json data string for example) occasionally with some other python scripts that will be started later by myself or another program and will end just after sending the string.
I can... | 2013/04/25 | [
"https://Stackoverflow.com/questions/16213235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1112326/"
] | zeromq: <http://www.zeromq.org/> - is best solution for interprocess communications imho and have a excelent binding for python: <http://www.zeromq.org/bindings:python> | Since the "main" script looks like a service you can enhance it with a web API. [bottle](http://bottlepy.org/) is the perfect solution for this. With this additional code your python script is able to receive requests and process them:
```
import json
from bottle import run, post, request, response
@post('/process')... | 4,367 |
34,471,188 | Doing python exercises already I've a problem with string:
```
#!/usr/bin/python
str = 'mandarino'
indice = len(str)-1
#print ("indice is:",indice)
while indice > 0:
lett = str[indice]
print (lett)
indice = indice -1
```
Putting off "-1" the results is:
```
IndexError: string index out of ... | 2015/12/26 | [
"https://Stackoverflow.com/questions/34471188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4075480/"
] | ```
while indice > 0:
```
should be
```
while indice >= 0:
```
to print the first character (index `0`) at last.
---
BTW, if you use [`reversed`](https://docs.python.org/3/library/functions.html#reversed), you don't need to calculate index yourself:
```
s = 'mandarino'
for ch in reversed(s):
print(ch)
```
... | Though above answers are correct..this is more `pythonic` way...
```
string = 'mandarino'
indice = len(string)
while indice >= 0:
indice -= 1
print (string[indice]),
``` | 4,369 |
43,957,412 | Is it possible to extract the text information from a popup page automatically using python?
I have google play store app link :
<https://play.google.com/store/apps/details?id=com.facebook.katana>
If you scroll down to the "ADDITIONAL INFORMATION" section, you will find "Permissions". By clicking 'View details" underne... | 2017/05/13 | [
"https://Stackoverflow.com/questions/43957412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5090248/"
] | You'll need to do the following:
1) Set up a webdriver to control the website.
<https://sites.google.com/a/chromium.org/chromedriver/getting-started>
2) Right click "view details" and select inspect source. This will open the source code of the page. The highlighted portion corresponds to that button. You can right ... | This is going to be rather complicated: you'll have to dig through the HTML to find out what the button does (the link is actually a `button` element). The best would be to use a Google Play Store API, which doesn't exist as of right now. The easiest option would therefore be to go through a third-party API which would... | 4,373 |
9,687,922 | I recently built an application, for a client, which has several python files. I use ubuntu, and now that I am finished, I would like to give this to the client in a way that would make it easy for her to use in windows.
I have looked into py2exe with wine, as well as cx\_freeze and some other stuff, but cannot find a... | 2012/03/13 | [
"https://Stackoverflow.com/questions/9687922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1266969/"
] | [This page](http://bytes.com/topic/python/answers/26340-linux-wine-py2exe) appears to have a solution, as the asker didn't reply:
1. Install WINE.
2. Use WINE to install Python 2.3.
3. Use WINE to install py2exe.
4. Make a setup.py file for py2exe to compile your script:
>
>
> ```
> from distutils.core import setup... | py2exe will not work on linux. Try [pyinstaller](http://www.pyinstaller.org/) it is a pure python implementation that will work on linux, mac and windows. | 4,374 |
71,040,315 | I have two builds at the same time when doing PR.
[](https://i.stack.imgur.com/QqREB.png)
According to docs, that could be turned off via [web interface](https://docs.travis-ci.com/user/web-ui/#build-pushed-branches)
[.
```
hlo = []
for i in range(len(sh.col_values(8))):
if sh.cell(i, 1).value == sys.argv[1]:
hlo.append(sh.cell(i, 8).value)
```
How ... | 2009/10/29 | [
"https://Stackoverflow.com/questions/1643643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198894/"
] | [argparse](http://docs.python.org/dev/library/argparse.html) is another powerful, easy to use module that parses sys.argv for you. Very useful for creating command line scripts. | I believe this would work, and would avoid iterating over sys.argv:
```
hlo = []
for i in range(len(sh.col_values(8))):
if sh.cell(i, 1).value in sys.argv[1:]:
hlo.append(sh.cell(i, 8).value)
``` | 4,376 |
2,832,646 | my dir location,i am in a.py:
```
my_Project
|----blog
|-----__init__.py
|-----a.py
|-----blog.py
```
when i 'from blog import something' in a.py , it show error:
```
from blog import BaseRequestHandler
ImportError: cannot import name BaseRequestHandler
```
i think it impo... | 2010/05/14 | [
"https://Stackoverflow.com/questions/2832646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] | When you are in `a.py`, `import blog` should import the local `blog.py` and nothing else. Quoting the [docs](http://docs.python.org/tutorial/modules.html#the-module-search-path):
>
> modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the i... | what happens when you:
```
import blog
```
Try outputting your sys.path, in order to make sure that you have the right dir to call the module from. | 4,386 |
16,168,836 | Here's a python-code-snippet:
```
import re
VARS='Variables: "OUTPUTFOLDER=installers","SETUP_ORDER=Product 4,Product 4 Library","SUB_CONTENTS=Product 4 Library","SUB_CONTENT_SIZES=9364256","SUB_CONTENT_GROUPS=Product 4 Library","SUB_CONTENT_DESCRIPTIONS=","SUB_CONTENT_GROUP_DESCRIPTIONS=","SUB_DISCS=Product 4,Produ... | 2013/04/23 | [
"https://Stackoverflow.com/questions/16168836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446835/"
] | ```
$(document).ready(function(){
$('#commentform').submit(function(){
var postname = $('h2.post-title').text();
ga('send', 'event', 'Engagement', 'Comment', postname, 5);
});
});
```
First of all. This code assigns the text of a `h2` tag with class `post-title` found in the `document`. A way more reliable way to get... | Hard to tell without looking at an actual page, but likely the browser is redirecting to the form's submission before ga's network call is made. You'd need a way to wait for ga to finish, then finish submitting the form. | 4,387 |
71,672,487 | Can't import `Quartz` package.
I have installed it with this command `pip install pyobjc-framework-Quartz`. Tried reinstalling python, also tried `python -m pip install ...`. With `python2` or `sudo python3`, everything works fine but `python3` is giving me this error message every time I try importing `Quartz`
Pytho... | 2022/03/30 | [
"https://Stackoverflow.com/questions/71672487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16965639/"
] | For investigation purposes, can you try :
```
cd /tmp
python3 -m venv venv
source venv/bin/activate
pip install pyobjc-framework-Quartz
python your-script.py
```
Can you try this to see if it works :
```
env -i /Library/Frameworks/Python.framework/Versions/3.10/bin/python3 my_script.py
```
You may have files only... | You might need to try:
```py
python3 -m pip install [...]
```
Hope this will hope. | 4,388 |
40,909,099 | I'm new to image processing and I'm really having a hard time understanding stuff...so the idea is that how do you create a matrix from a binary image in python?

to something like this:

It not the same image though the point is there.... | 2016/12/01 | [
"https://Stackoverflow.com/questions/40909099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6019385/"
] | **Using cv2** -Read more [here](http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_image_display/py_image_display.html)
```
import cv2
img = cv2.imread('path/to/img.jpg')
resized = cv2.resize(img, (128, 128), cv2.INTER_LINEAR)
print pic
```
**Using skimage** - Read more [here](http://scikit-image.org/docs/de... | example I am currently working with.
====================================
```
"""
A set of utilities that are helpful for working with images. These are utilities
needed to actually apply the seam carving algorithm to images
"""
from PIL import Image
class Color:
"""
A simple class representing an RGB value.... | 4,389 |
67,740,573 | I have a huge file of around 5-10 GBs which has syntax as shown below.
"some text" condition1
"some text" condition2
"some text" condition3
"some text" condition1
"some text" condition4
& so on
The intent is to write a fast & efficient code to create separate files to store this text info based on conditions. Al... | 2021/05/28 | [
"https://Stackoverflow.com/questions/67740573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4991138/"
] | The first thing that comes to mind for me would be to use the append feature on Python file handlers. You could do something like this for each line of text:
```py
def writecond(text, cond):
fname = cond + '.txt'
with open(fname, 'a') as file:
file.write(text)
```
Another thing you could do is have a... | I figured out one option of handling objects dynamically and keeping track of it.
```
file_handler = {}
with open(file) as f:
for line in f:
if line.split()[1] not in file_handler.keys():
file_handler[line.split()[1]] = open(line.split()[1],"w")
file_handler[line.split()[1]].write(... | 4,390 |
42,349,982 | I am trying to read the JSON file in python and it is successfully however some top values are skipped. I am trying to debug the reason. Here is the the code.
```
data = json.load(open('pre.txt'))
for key,val in data['outputs'].items():
print key
print data['outputs'][key]['feat_left']
```
**EDIT**
Here is... | 2017/02/20 | [
"https://Stackoverflow.com/questions/42349982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7396273/"
] | No top values are skipped. There are 45875 items in your data['output'] object. Try the following code:
```
len(data['outputs'].items())
```
And there are exactly 45875 items in your JSON file. Just note that JSON object is an unordered collection in python, like `dict`. | If you just want to print the content of the file by using a for-loop, you can try like this:
```
data = json.load(open('pre.txt')
for key,val in data['outputs'].items():
print key
print val[0] #this will print the array and its values below "feat_left", if the json is consistent
```
A more robust soluti... | 4,391 |
52,318,106 | HTML: I have a 'sign-up' form in a modal (index.html)
JS: The form data is posted to a python flask function: /signup\_user
```
$(function () {
$('#signupButton').click(function () {
$.ajax({
url: '/signup_user',
method: 'POST',
data: $('#signupForm').serialize()
})
.done(function (data) {
... | 2018/09/13 | [
"https://Stackoverflow.com/questions/52318106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5632508/"
] | I would do something like this:
```
student_marks.group_by { |k, v| v }.map { |k, v| [k, v.map(&:first)] }.to_h
#=> { 50 => ["Alex", "Matt"], 54 => ["Beth"]}
``` | Another way could be
```
student_marks.each.with_object(Hash.new([])){ |(k,v), h| h[v] += [k] }
#=> {50=>["Alex", "Matt"], 54=>["Beth"]}
``` | 4,396 |
34,734,436 | I am using pip on EC2 now, python version is 2.7. 'sudo pip' suddenly doesn't work anymore.
```none
[ec2-user@ip-172-31-17-194 ~]$ sudo pip install validate_email
Traceback (most recent call last):
File "/usr/bin/pip", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/local/lib/python2.... | 2016/01/12 | [
"https://Stackoverflow.com/questions/34734436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5326788/"
] | first, `which pip` is not going to return the same result as `sudo which pip`, so you should check that out first.
you may also consider not running pip as sudo at all.
[Is it acceptable & safe to run pip install under sudo?](https://stackoverflow.com/questions/15028648/is-it-acceptable-safe-to-run-pip-install-under-s... | I fixed the same error ("The 'pip==6.1.1' distribution was not found") by using the tip of Wesm :
```
$> which pip && sudo which pip
/usr/local/bin/pip
/usr/bin/pip
```
So, it seels that "pip" of average user and of root are not the same. Will fix it later.
Then I ran "sudo easy\_install --upgrade pip" => succeed
... | 4,402 |
66,559,129 | I am writing table to mysql from python using pymysql to\_sql function.
I am having 1000 rows with 200 columns.
Query to connect to mysql is below:
```
engine = create_engine("mysql://hostname:password#@localhostname/dbname")
conn = engine.connect()
writing query: df.to_sql('data'.lower(),schema=schema,conn,'replace'... | 2021/03/10 | [
"https://Stackoverflow.com/questions/66559129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12249443/"
] | You can store the data with 3 methods-
1. Use localStorage
if you are using a json object then you can use localStorage.setItem("data123",JSON.stringify(data))
and fetch the data using JSON.prase(localStorage.getItem("data123"))
2. sessionStorgae
Syntax is same as localStaorage. Just replace localwith session
Dif... | I think the best way to save form data locally is to preserve it in your form handler class like you can create a new Handler class and create setter and getter in it which store the form fields data/values in object key, value pair which you always update whenever fields update. | 4,408 |
12,028,496 | How do I pass a query string to a HTML frame?
I have the following HTML in index.html:
```
<HTML>
<FRAMESET rows="200, 200" border=0>
<FRAMESET>
<FRAME name=top scrolling=no src="top.html">
<FRAME name=main scrolling=yes src="/cgi-bin/main.py">
</FRAMESET>
</FRAMESET>
</HTML>
```
The frame src is main.... | 2012/08/19 | [
"https://Stackoverflow.com/questions/12028496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65406/"
] | [This](https://stackoverflow.com/a/2880929/1273830) should help you get variables from the query string, which you can use to build your custom queryString. Or if you want to pass the query string as it is to the frame, then you could get it a simpler fashion.
`var queryString = window.location.href.split('index.html?... | Not sure if this will work (untested), but perhaps you can load the query parameters onload using jQuery? Here is a proof of concept:
```
<html>
<head>
//Load jquery here, then do the following:
<script type="text/javascript">
$(document).ready(functin(){
// navigator.href holds the current... | 4,409 |
22,447,986 | I have the following list of string
```
mystring = [
'FOO_LG_06.ip',
'FOO_LV_06.ip',
'FOO_SP_06.ip',
'FOO_LN_06.id',
'FOO_LV_06.id',
'FOO_SP_06.id']
```
What I want to do is to print it out so that it gives this:
```
LG.ip
LV.ip
SP.ip
LN.id
LV.id
SP.id
```
How can I do that in python?
I'm stuck w... | 2014/03/17 | [
"https://Stackoverflow.com/questions/22447986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1380929/"
] | If you want to do this in a manner similar to the one you know in perl, you can use `re.search`:
```
import re
mystring = [
'FOO_LG_06.ip',
'FOO_LV_06.ip',
'FOO_SP_06.ip',
'FOO_LN_06.id',
'FOO_LV_06.id',
'FOO_SP_06.id']
for soth in mystring:
matches = re.search(r'FOO_(\w+)_06(\.\w{2})', soth)
prin... | different regex:
>
>
> >
> >
> > >
> > > p='[^*]+*([A-Z]+)[^.]+(..\*)'
> > >
> > >
> > >
> >
> >
> >
>
>
>
```
>>> for soth in mystring:
... match=re.search(p,soth)
... print ''.join([match.group(1),match.group(2)])
```
Output:
LG.ip
LV.ip
SP.ip
LN.id
LV.id
SP.id | 4,410 |
1,942,295 | Noob @ programming with python and pygtk.
I'm creating an application which includes a couple of dialogs for user interaction.
```
#!usr/bin/env python
import gtk
info = gtk.MessageDialog(type=gtk.DIALOG_INFO, buttons=gtk.BUTTONS_OK)
info.set_property('title', 'Test info message')
info.set_property('text', 'Message t... | 2009/12/21 | [
"https://Stackoverflow.com/questions/1942295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234654/"
] | can you give me a last chance? ;)
there are some errors in your code:
* you did not close a bracket
* your syntax in `.set_property` is wrong: use: `.set_property('property', 'value')`
but i think they are copy/paste errors.
try this code, it works for me. maybe did you forget the `gtk.main()`?
```
import gtk
inf... | @mg
My bad. Your code is correct (and I guess my initial code was too)
The reason my dialog was remaining on the screen is because my gtk.main loop is running on a separate thread.
So all I had to was enclose your code (corrected version of mine) in between a
```
gtk.gdk.threads_enter()
```
and a
```
gtk.gdk.thre... | 4,411 |
15,852,455 | I need scipy on cygwin, so I figured the quickest way to make it work would have been installing enthought python. However, I then realized I have to make cygwin aware of enthought before I can use it, e.g. so that calling Python from the cygwin shell I get the enthought python (with scipy) rather than the cygwin one.
... | 2013/04/06 | [
"https://Stackoverflow.com/questions/15852455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714385/"
] | There are better options than periodically polling the value of the variable. Polling could miss a variable change, and it requires computational resources even if nothing is happening.
You could wrap the variable in a wrapper class and change it only through a setter.
If you're using Eclipse, you can ask the debugg... | Using a wrapper class for you variable like:
```
class VarWrapper{
private Object myVar;
public Object getMyVar() {
return myVar;
}
public void setMyVar(Object myVar) {
//[1],Here you'll know myVar changed
this.myVar = myVar;
}
}
``` | 4,412 |
30,023,898 | I'm creating a little calculator as a project And I want it to restart when it type yes when it's done. Problem is, I can't seem to figure out how. I'm not a whiz when it comes to python.
```
import sys
OPTIONS = ["Divide", "divide", "Multiply", "multiply", "Add", "add", "Subtract", "subtract"]
def useri... | 2015/05/04 | [
"https://Stackoverflow.com/questions/30023898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4861144/"
] | You don't need to restart your script, just have a little bit of thought about the design before you code. Taking the script you provided, there are two alterations for this issue:
```
def playagain():
while True:
again = input("Again? Yes/No: ")
if again == "Yes" or again == "yes":
r... | Use os.execv()....
[Restarting a Python Script Within Itself](http://blog.petrzemek.net/2014/03/23/restarting-a-python-script-within-itself/) | 4,415 |
15,612,362 | Here is python code:
```
def is_palindrome(s):
return revers(s) == s
def revers(s):
ret = ''
for ch in s:
ret = ch + ret
return ret
print is_palindrome('RACECAR')
# that will print true
```
when i convert that function to php.
```
function is_palindrome($string){
if (strrev($string) =... | 2013/03/25 | [
"https://Stackoverflow.com/questions/15612362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/740182/"
] | Replace
```
$output .= $c;
```
with
```
$output = $c . $output;
``` | strrev() is a function that reverses a string in PHP.
<http://php.net/manual/en/function.strrev.php>
```
$s = "foobar";
echo strrev($s); //raboof
```
If you want to check if a word is a palindrome:
```
function is_palindrome($word){ return strrev($word) == $word }
$s = "RACECAR";
echo $s." is ".((is_palindrome($s)... | 4,418 |
24,931,465 | Hi I am very new to python, here i m trying to open a xls file in python code but it is showing me some error as below.
Code:
```
from xlrd import open_workbook
import os.path
wb = open_workbook('C:\Users\xxxx\Desktop\a.xlsx')
Error:Traceback (most recent call last):
File "C:\Python27\1.py", line 3, in <module>
wb =... | 2014/07/24 | [
"https://Stackoverflow.com/questions/24931465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3872486/"
] | This is a version conflict issue. Your Excel sheet format and the format that xlrd expects are different. You could try to save the Excel sheet in a different format until you find what xlrd expects. | Not familiar with xlrd, but nothing wrong appears on my Mac.
According to @jewirth, you can try to rename the suffix to xls which is the old version, and then reopen it or convert it into xlsx. | 4,424 |
33,686,880 | I have a `libpython27.a` file: how to know whether it is 32-bit or 64-bit, on Windows 7 x64? | 2015/11/13 | [
"https://Stackoverflow.com/questions/33686880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395857/"
] | Try `dumpbin /headers "libpython27.a"`. ([dumpbin reference](https://msdn.microsoft.com/en-us/library/c1h23y6c.aspx))
The output will contain
`FILE HEADER VALUES
14C machine (x86)`
or
`FILE HEADER VALUES
8664 machine (x64)`
---
Note that if you get an error message like:
```
E:\temp>dumpbin /headers "libpython... | When starting the Python interpreter in the terminal/command line you may also see a line like:
>
> Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit
> (AMD64)] on win32
>
>
>
Where [MSC v.1500 64 bit (AMD64)] means 64-bit Python.
Or
Try using ctypes to get the size of a void pointer:
```
impor... | 4,427 |
68,764,541 | I was reading through the [PEP 526](https://www.python.org/dev/peps/pep-0526/) documentation and I was wondering what is the proper way to annotate a class instance.
I have not found the answer in the documentation.
I have the following module:
```py
class global_variables:
# Class body
global_variables_dictio... | 2021/08/12 | [
"https://Stackoverflow.com/questions/68764541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10588212/"
] | **Note**: "Best Practice" for something like this is difficult to define, since everyone's situation is likely different.
That being said, one of our projects has a similar situation as yours: we use Git Flow, and our `develop` branch build numbers are always different than the `release` branch build numbers. Our pote... | What about using an external tool to manage the version?
We use [GitVersion](https://github.com/GitTools/GitVersion) for this. Now I am not sure if there is a smarter way, but a brute-force one is to have something like this `<version>${env.GitVersion_SemVer}</version>` in your pom.xml, where env.GitVersion\_SemVer is ... | 4,430 |
26,472,868 | I have a python script (analyze.py) which takes a filename as a parameter and analyzes it. When it is done with analysis, it waits for another file name. What I want to do is:
1. Send file name as a parameter from PHP to Python.
2. Run analyze.py in the background as a daemon with the filename that came from PHP.
I c... | 2014/10/20 | [
"https://Stackoverflow.com/questions/26472868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1430739/"
] | The obvious answer here is to either:
1. Run `analyze.py` once per filename, instead of running it as a daemon.
2. Pass `analyze.py` a whole slew of filenames at startup, instead of passing them one at a time.
But there may be a reason neither obvious answer will work in your case. If so, then you need some form of *... | Here is what I did.
PHP Part:
```
<?php
$param1 = "filename";
$command = "python analyze.py ";
$command .= " $param1";
$pid = popen( $command,"r");
echo "<body><pre>";
while( !feof( $pid ) )
{
echo fread($pid, 256);
flush();
ob_flush();
}
pclose($pid);
?>
```
Python Part:
```
1. I used [JSON-RPC]: https://... | 4,431 |
46,877,384 | I am reading a text file in python(500 rows) and it seems like:
```
File Input:
0082335401
0094446049
01008544409
01037792084
01040763890
```
I wanted to ask that is it possible to insert one space after 5th Character in each line:
```
Desired Output:
00823 35401
00944 46049
01008 544409
01037 792084
01040 763890
... | 2017/10/22 | [
"https://Stackoverflow.com/questions/46877384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Inside your k6 script use the url `host.docker.internal` to access something running on the host machine.
For example to access a service running on the host at `http://localhost:8080`
```js
// script.js
import http from "k6/http";
import { sleep } from "k6";
export default function () {
http.get("http://host.dock... | k6 inside the docker instance should be able to connect to the "public" IP on your host machine - the IP that is configured on your ethernet or Wifi interface. You can do a `ipconfig /all` to see all your interfaces and their IPs.
On my Mac I can do this:
`$ python httpserv.py &
[1] 7824
serving at port 8000
$ ifconf... | 4,432 |
36,711,810 | I'm going to come out with a disclaimer and say this is my homework problem. So I don't necessarily want you to solve it, I just want some clarification.
The exact problem is this:
>
> Write a function to swap odd and even bits in an integer with as few
> instructions as possible (e.g., bit 0 and bit 1 are swapped... | 2016/04/19 | [
"https://Stackoverflow.com/questions/36711810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1157549/"
] | In assembly one can use [bit masks](https://en.wikipedia.org/wiki/Mask_%28computing%29) together with other [bitwise operations](https://en.wikipedia.org/wiki/Bitwise_operation) to archive your result.
```
result = ((odd-bit-mask & input) << 1) | ((even-bit-mask & input) >> 1)
```
where `odd-bit-mask` is a value wit... | Here are a few hints:
* Bitwise boolean operations (these usually have 1:1 counterparts in assembly, but if everything else fails, you can construct them by cleverly combining several XOR calls)
+ bitwise AND: 0b10110101 & 0b00011000 → 0b00010000
+ bitwise OR: 0b10110101 & 0b00011000 → 0b10111101
+ bitwise XOR: 0b... | 4,433 |
41,132,864 | I have been trying to install OpenCV for ages now and finally I succeeded using this tutorial: <http://www.pyimagesearch.com/2016/12/05/macos-install-opencv-3-and-python-3-5/>.
However, whenever I try to import cv2 in IDLE, it is not found but I am certain I installed OpenCV.
The cv2.so file exists at:
/usr/local/li... | 2016/12/14 | [
"https://Stackoverflow.com/questions/41132864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7293747/"
] | ok i found the answer! after you activate the virtual environment with:
```
work on cv
```
type this on the terminal to open the IDLE with the current virtual environment
```
python -c "from idlelib.PyShell import main; main()"
```
or
```
python -m idlelib
```
and it will do the trick! | Dumb approach but does your IDLE run the same python environment as your terminal? | 4,434 |
12,990,462 | This is a repost of an issue I posted on the berkelium project on github (<https://github.com/sirikata/berkelium/issues/19>).
My question:
During chromium compilation on Linux (Debian testing, 64bit, gcc 4.7.1, cmake 2.8.9), the python script `action_makenames.py` fails with the following error:
```
...
ACTION web... | 2012/10/20 | [
"https://Stackoverflow.com/questions/12990462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/780281/"
] | Turns out to be a preprocessor bug for gcc 4.6. As a fix, you have to remove the `-P` parameter of the gcc preprocessor command in `make_names.pl`.
**Bug report**:
<http://code.google.com/p/chromium/issues/detail?id=46411>
**Bug fix**:
<http://trac.webkit.org/changeset/84123> | sounds like you may be missing a directory, a la
<http://aur.archlinux.org/packages.php?ID=45713> | 4,435 |
53,066,830 | I have a python program which I have made work in both Python 2 and 3, and it has more functionality in Python 3 (using new Python 3 features).
My script currently starts `#!/usr/bin/env python`, as that seems to be the mostly likely name for a python executable. However, what I'd like to do is "if python3 exists, use... | 2018/10/30 | [
"https://Stackoverflow.com/questions/53066830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27074/"
] | Another better method modified from [this question](https://stackoverflow.com/questions/12070516/conditional-shebang-line-for-different-versions-of-python) is to check the `sys.version`:
```
import sys
py_ver = sys.version[0]
```
Original answer: May not be the best method, but one way to do it is test against a fun... | Try with version\_info from sys package | 4,436 |
58,192,211 | I'm trying to do something simple in Python. I'm a little rusty so I'm not sure what I'm doing wrong. I want to give random values to dictionary items. Each loop I want to subtract from the original value so if a house has 5 rooms then the total doesn't ever go over 5 for the combined items in the dictionary.
This is ... | 2019/10/01 | [
"https://Stackoverflow.com/questions/58192211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1112733/"
] | In the script you're re-assigning `h1` with `h1 - size` in each iteration of the `for` loop, and if `size` happens to be `h1` as it is the upper bound passed to `randint`, `h1` would become `0` after the assignment, so that in the next iteration you would be effectively calling `random.randint(1, 0)`, where the upper b... | Let's consider a simple example. You randomly select a 4-room house. Your random numbers give you 3 bedrooms and one bath. Your loop continues to "study" and tries to generate a random number form 1 to 0. You neglected to reserve a room for that requirement. Python considers the inverted range to be an error.
If you t... | 4,438 |
33,306,221 | I need in python execute this command and enter password from keyboard, this is works:
```
import os
cmd = "cat /home/user1/.ssh/id_rsa.pub | ssh user2@host.net \'cat >> .ssh/authorized_keys\' > /dev/null 2>&1"
os.system(cmd)
```
As you can see I want append public key to remote host via ssh.
See here: [equivalen... | 2015/10/23 | [
"https://Stackoverflow.com/questions/33306221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595216/"
] | From [the `pexpect` docs](http://pexpect.readthedocs.org/en/stable/api/pexpect.html#spawn-class):
>
> Remember that Pexpect does NOT interpret shell meta characters such as
> redirect, pipe, or wild cards (`>`, `|`, or `*`). This is a
> common mistake. If you want to run a command and pipe it through
> another com... | That worked for me:
```
command = "/bin/bash -c \"cat /home/user1/.ssh/id_rsa.pub | ssh user2@host.net \'cat >> ~/.ssh/authorized_keys\' > /dev/null 2>&1\""
child = spawn(command=command, timeout=5)
``` | 4,439 |
2,286,276 | I made a model, and ran python manage.py syncdb. I think that created a table in the db. Then I realized that I had made a column incorrectly, so I changed it, and ran the same command, thinking that it would drop the old table, and add a new one.
Then I went to python manage.py shell, and tried to run .objects.all(),... | 2010/02/18 | [
"https://Stackoverflow.com/questions/2286276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/275779/"
] | None of the answers shows how to delete just one table in an app. It's not too difficult. The [`dbshell`](https://docs.djangoproject.com/en/1.7/ref/django-admin/#django-admin-dbshell) command logs the user into the sqlite3 shell.
```
python manage.py dbshell
```
When you are in the shell, type the following command... | In Django 2.1.7, I've opened the `db.sqlite3` file in [SQLite browser](https://sqlitebrowser.org/) (there is also a Python package on [Pypi](https://pypi.org/project/sqlite_bro/)) and deleted the table using command
```
DROP TABLE appname_tablename;
```
and then
```
DELETE FROM django_migrations WHERE App='appname... | 4,440 |
59,039,858 | I am importing a large number of dates in the form DD/MM/YYYY from a csv file into python and want to group them by just MM-YYYY. One method I have tried is the following:
```
str=date.iloc[2]
```
which results in str=7/18/2019. But what I want to do is convert it to Jul 2019 to make groupings by month and year. I h... | 2019/11/25 | [
"https://Stackoverflow.com/questions/59039858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12432098/"
] | ```
datetime.datetime.strptime("str","%m/%d/%Y").strptime("%b %Y")
```
Is to parse literally the string of "str" into the date. Instead, you should do
```
datetime.datetime.strptime(str,"%m/%d/%Y").strftime("%b %Y")
``` | In this line
```
datetime.datetime.strptime("str","%m/%d/%Y").strptime("%b %Y")
```
`"str"` is a string literal. You want the variable `str`
```
datetime.datetime.strptime(str,"%m/%d/%Y").strptime("%b %Y")
``` | 4,450 |
4,707,941 | I have seen several Questions comparing different ECommerce CMS's:
1. [Prestashop compared to Zen-Cart and osCommerce](https://stackoverflow.com/questions/2040472/prestashop-compared-to-zen-cart-and-oscommerce)
2. [Magento or Prestashop, which is better?](https://stackoverflow.com/search?q=prestashop)
3. [Best php/rub... | 2011/01/16 | [
"https://Stackoverflow.com/questions/4707941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/363701/"
] | "Free" in the e-commerce industry usually works out to a few thousand dollars a month of real cost. E-commerce stores are powering the livelihood of businesses, so there is no way to go with a value hosting company. Additionally security is a huge concern so updates are incredibly important. So this leaves you with a s... | The prices is not the main difference between Shopify and PrestaShop. Talking about the scope- I think both will suit you.
1. Technical Level
The choice of hosted Shopify or open-source PrestaShop may depends on the level of technical skills. Without doubt it is easier to maintain your store with hosted shopping cart... | 4,452 |
12,624,324 | I am facing difficulty in getting the xml structure listing all the directories/ sub directories inside a given directory. I got that working using the recursion in the [given post](https://stackoverflow.com/questions/2104997/os-walk-python-xml-representation-of-a-directory-structure-recursion) My problem is little bit... | 2012/09/27 | [
"https://Stackoverflow.com/questions/12624324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1364646/"
] | [`os.walk`](http://docs.python.org/library/os.html#os.walk) already distinguishes between files and directories:
```
def find_all_dirs(root='.'):
for path,dirs,files in os.walk(root):
for d in dirs:
yield os.path.join(path, d)
``` | For just one directory...
```
import os
def get_dirs(p):
p = os.path.abspath(p)
return [n for n in os.listdir(p) if os.path.isdir(os.path.join(p, n))]
print "\n".join(get_dirs("."))
``` | 4,453 |
46,552,178 | I have two files. `functions.py` has a function and creates a pyspark udf from that function. `main.py` attempts to import the udf. However, `main.py` seems to have trouble accessing the function in `functions.py`.
functions.py:
```
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
def d... | 2017/10/03 | [
"https://Stackoverflow.com/questions/46552178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5617110/"
] | Just adding this as answer:-
add your py file to sparkcontext in order to make it available to your executors.
```
sc.addPyFile("functions.py")
from functions import sample_udf
```
Here is my test notebook
<https://databricks-prod-cloudfront.cloud.databricks.com/public/4027ec902e239c93eaaa8714f173bcfc/366922160... | I think a cleaner solution would be to use the udf decorator to define your udf function :
```
import pyspark.sql.functions as F
from pyspark.sql.types import StringType
@F.udf
def sample_udf(x):
return x + 'hello'
```
With this solution, the udf does not reference any other function and you don't need the `sc... | 4,456 |
21,226,366 | I have a script to get and setup the latest NodeJS on my .deb system:
```
echo "Downloading, building and installing latest NodeJS"
sudo apt-get install python g++ make checkinstall
mkdir /tmp/node_build && cd $_
curl -O "http://nodejs.org/dist/node-latest.tar.gz"
tar xf node-latest.tar.gz && cd node-v*
NODE_VERSION="... | 2014/01/20 | [
"https://Stackoverflow.com/questions/21226366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/587021/"
] | Is there another "v" in the path, like right before the "i8/"? `#*v` will remove through the *first* "v" in the variable; I'm pretty sure you want `##*v` which'll remove through the *last* "v" in the variable. (Technically, `#` removes the shortest matching prefix, and `##` removes the longest match). Thus:
```
NODE_V... | Try this
```
sudo checkinstall -y --install=no --pkgversion "${NODE_VERSION##*v}"
``` | 4,457 |
37,445,901 | This question comes from [this one](https://stackoverflow.com/questions/37399965/refresh-web-page-using-a-cgi-python-script).
What I want is to be able to return the `HTTP 303` header from my python script, when the user clicks on a button. My script is very simple and as far as output is concerned, it *only* prints t... | 2016/05/25 | [
"https://Stackoverflow.com/questions/37445901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751115/"
] | Assuming you are using cgi ([2.7](https://docs.python.org/2/library/cgi.html))([3.5](https://docs.python.org/3.5/library/cgi.html))
The example below should redirect to the same page. The example doesn't attempt to parse headers, check what POST was send, it simply redirects to the page `'/'` when a POST is detected.
... | Typically browsers like to see `/r/n/r/n` at the end of an HTTP response. | 4,458 |
29,848,351 | I have the following list of keys in python.
```
[{'country': None, 'percent': 100.0}, {'country': 'IL', 'percent': 100.0}, {'country': 'IT', 'percent': 100.0}, {'country': 'US', 'percent': 2.0202}, {'country': 'JP', 'percent': 11.1111}, {'country': 'US', 'percent': 6.9767}, {'country': 'SG', 'percent': 99.8482}, {'co... | 2015/04/24 | [
"https://Stackoverflow.com/questions/29848351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567797/"
] | ```
result_map = {}
for item in response:
if item['country'] is None:
continue
if item['country'] not in result_map:
result_map[item['country']] = item['percent']
else:
result_map[item['country']] += item['percent']
results = [
{'country': country, 'percent': percent}
for co... | Change the condition of the if to:
```
if response.index(v) != response.index(j) and v['country'] == j['country']:
```
You're addding twice the elements. | 4,460 |
19,847,275 | My function is like
```
def calResult(w,t,l,team):
wDict={}
for item in team:
for x in w:
wDict[item]=int(wDict[item])+int(x[item.index(" "):item.index(" ")+1])
for x in t:
wDict[item]=int(wDict[item])+int(x[item.index(" "):item.index(" ")+1])
return wDict
```
say ... | 2013/11/07 | [
"https://Stackoverflow.com/questions/19847275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2844097/"
] | You can not access `wDict[item]` the first time, since your dict is empty
This would be ok:
```
wDict[item] = 1
```
But you can not do this :
```
wDict[item] = wDict[item] + 1
```
Maybe you want to use this syntax :
```
wDict[item] = int(wDict.get(item, 0)]) + int(x[item.index(" "):item.index(" ") + 1])
``` | Looks like you are trying to use wDict[item] as the rvalue and the lvalue in the same assignment statement, when wDict[item] is not yet initialized.
```
wDict[item]=int(wDict[item])+int(x[item.index(" "):item.index(" ")+1])
```
You are trying to access the "value" of the key item, but there is no key value pair init... | 4,463 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.