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 |
|---|---|---|---|---|---|---|
14,970,952 | Im kinda new to python, and dont really understand my issue, really appreciate the help. Anyways, this is the line of coding.
```
def Banker(warrior):
gold = open(chairs[warrior-1], "strength")
return gold
```
This is the error i got.
```
line 22, in Banker
gold = open(chairs[warrior-1], "strength")
Typ... | 2013/02/20 | [
"https://Stackoverflow.com/questions/14970952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2089394/"
] | On a UNIX machine, use the [`pwent`](http://www.kernel.org/doc/man-pages/online/pages/man3/getpwent.3.html) series of functions:
```
#include <sys/types.h>
#include <pwd.h>
int main() {
struct passwd *p;
while((p = getpwent())) {
printf("name: %s\n", p->pw_name);
}
}
```
This will consult the sy... | The users of a machine are listed in /etc/passwd. A good way to filter all 'human' users is to do
```
cat /etc/passwd | grep "/home" |cut -d: -f1
```
as the human users usually have a home directory.
Now, for calling it inside C, you may use popen. Take a look at
```
man popen
``` | 8,426 |
74,618,168 | I have just starting learning python and as I creating this program, which asks user to input two numbers, which then adds them to together using a simple `if-elif-else` statement, however the else part of the code just seems to not work if, an user types out the six, for example, in words instead of the number.
```
... | 2022/11/29 | [
"https://Stackoverflow.com/questions/74618168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17851996/"
] | This should be what you are looking for:
```
try:
num_1 = int(input("Enter the first number: "))
num_2 = int(input("Enter the second number: "))
except ValueError:
print("invalid")
exit()
Total = num_1 + num_2
print("The total is: ", Total)
if num_1 > num_2:
print("num_1 is greater then num_2")
elif... | In your first two lines you’re calling int() on a string in the situation you’re describing. This won’t work, and your code will stop running here. What you want is probably something call a try-catch statement. | 8,431 |
36,862,589 | I'm attempting to Dockerise a Python application, which depends on OpenCV. I've tried several different ways, but I keep getting... `ImportError: No module named cv2` when I attempt to run the application.
Here's my current Dockerfile.
```
FROM python:2.7
MAINTAINER Ewan Valentine <[email protected]>
RUN mkdir ... | 2016/04/26 | [
"https://Stackoverflow.com/questions/36862589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541609/"
] | Here's an [image](https://hub.docker.com/r/chennavarri/ubuntu_opencv_python/) that is built on Ubuntu 16.04 with Python2 + Python3 + OpenCV. You can pull it using
`docker pull chennavarri/ubuntu_opencv_python`
Here's the Dockerfile (provided in the same dockerhub repo mentioned above) that will install opencv for both... | if you want to use Opencv dnn with CUDA, and torch with gpu (optionally) i recommend this:
```
FROM nvidia/cuda:10.2-base-ubuntu18.04
WORKDIR /home
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Europe/Minsk
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
RUN apt-get update && apt-get inst... | 8,432 |
49,768,187 | When doing some simple calculation from dataframe object (python 3.5, pandas 0.20.1), pandas is not behaving consistently when the calculated result doesn't fit the current numeric type. Why?
Please see code below, creating a dataframe with numeric type-int16 :
```
import pandas as pd
import numpy as np
d = {'col1':... | 2018/04/11 | [
"https://Stackoverflow.com/questions/49768187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6217667/"
] | You have to apply the :hover effect in a:hover because you have already applied background-color to a element. Try and add this code.
```
.tabs-nav a:hover {
background-color: red;
}
``` | Below code works for me
```
.tabs-nav li :hover {
color: white;
background: red;
}
```
If I am not wrong Space is added to apply hover to the child of li. In this case for anchor tag | 8,442 |
46,247,732 | So I am learning python and am trying to count the number of vowels in a sentence. I figured out how to do it both using the count() function and an iteration but now I am trying to do it using recursion. When I try the following method I get an error "IndexError: string index out of range". Here is my code.
```
sente... | 2017/09/15 | [
"https://Stackoverflow.com/questions/46247732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8616651/"
] | You have no base case. The function will keep recursing until `sentence` is empty, in which case your first if statement will cause that index error.
You should first of all check if sentence is empty, and if so return 0 | You can shorten things up quite a bit:
```
def count_vowels_recursive(sentence):
# this base case is needed to stop the recursion
if not sentence:
return 0
# otherwise, sentence[0] will raise an exception for the empty string
return (sentence[0] in "aeiou") + count_vowels_recursive(sentence[1... | 8,445 |
49,490,803 | I'm working through a python workbook, and I have to turn the following dictionary into a list:
```
lexicon = {
'north': 'direction',
'south': 'direction',
'east': 'direction',
'west': 'direction',
'down': 'direction',
'up': 'direction',
'left': 'direction',
'right': 'direction',
'b... | 2018/03/26 | [
"https://Stackoverflow.com/questions/49490803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9429075/"
] | You can use `.keys()` or `.values()`.
```
>>> list(lexicon.keys())
['princess', 'down', 'east', 'north', 'cabinet', 'at', 'right', 'door', 'left', 'up', 'from', 'bear', 'of', 'the', 'south', 'in', 'kill', 'eat', 'back', 'west', 'it', 'go', 'stop']
>>> list(lexicon.values())
['noun', 'direction', 'direction', 'directio... | if you just want values you can use :
`lexicon.values()` it will return you the values saved against each key.
but if you want to have a list of key value pairs then you can use the following :
```
>>lexicon.items()
output :
[('right', 'direction'), ('it', 'stop'), ('down', 'direction'), ('kill', 'verb'), ('at... | 8,447 |
38,471,306 | As what I have understand on python, when you pass a variable on a function parameter it is already reference to the original variable. On my implementation when I try to equate a variable that I pass on the function it resulted empty list.
This is my code:
```
#on the main -------------
temp_obj = []
obj = [
{'n... | 2016/07/20 | [
"https://Stackoverflow.com/questions/38471306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6099766/"
] | If all you want to do is switch from design view to code view then use the F7 key. In older versions of VS, F7 would switch back again too but in later versions you use Shift+F7 to switch from code view to design view.
When in design view, you can select the form or a control/component, open the Properties window, cli... | Already resolved. I was able to do it by creating another project and choosing the windows form application as visual basic, not c#. | 8,448 |
69,528,110 | I have the following code
```
name = "testyaml"
version = "2.5"
os = "Linux"
sources = [
{
'source': 'news',
'target': 'industry'
},
{
'source': 'testing',
'target': 'computer'
}
]
```
And I want to make this yaml with python3
```
services:
name: nam... | 2021/10/11 | [
"https://Stackoverflow.com/questions/69528110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/878280/"
] | ```py
import yaml
name = "testyaml"
version = "2.5"
os = "Linux"
sources = [
{"source": "news", "target": "industry"},
{"source": "testing", "target": "computer"},
]
yaml.dump(
{"services": {"name": name, "version": version, "os": os, "sources": sources}}
)
``` | Python's `yaml` module allows you to dump dictionary data into yaml format:
```py
import yaml
# Create a dictionary with your data
tmp_data = dict(
services=dict(
name=name,
version=version,
os=os,
sources=sources
)
)
if __name__ == '__main__':
with open('my_yaml.yaml', 'w... | 8,449 |
26,810,892 | I am trying to write the output of a python code in an excel sheet.
Here's my attempt:
```
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('pyt')
row =0 # row counter
col=0 # col counter
inputdata = [(1,2,3,4),(2,3,4,5)]
for c in inputdata:
for d in c:
sheet.write(row,col,d)
col +=1
... | 2014/11/07 | [
"https://Stackoverflow.com/questions/26810892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274879/"
] | You're seeing that behaviour because you're not setting `col` back to zero at the end of the row.
Instead, though, you should use the built-in [`enumerate()`](https://docs.python.org/2/library/functions.html#enumerate) which handles the incrementing for you.
```
for row, c in enumerate(inputdata):
for col, d in ... | Add `col = 0` on the next line after `row+=1` | 8,450 |
1,650,095 | I am reading the book [Think Python](http://www.greenteapress.com/thinkpython/) by Allen Downey. For chapter 4, one has to use a suite of modules called [Swampy](http://www.greenteapress.com/thinkpython/swampy/). I have downloaded and installed it.
The problem is that the modules were written in Python 2 and I have Py... | 2009/10/30 | [
"https://Stackoverflow.com/questions/1650095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115139/"
] | Many important third-party libraries have not yet been rewritten for Python 3; you'll have to stick to Python 2.x for now. There is no way around it. As it says on the [official Python download page](http://www.python.org/download/),
>
> If you don't know which version to
> use, start with Python 2.6.4; more
> exis... | There is a conversion tool for converting Python 2 code to work with Python 3: <http://svn.python.org/view/sandbox/trunk/2to3/>
Not sure how this extends to 3rd party libraries but it might be worth passing this over the swampy code. | 8,451 |
54,140,796 | I have a very large string consiting of a series of numbers separated by one or more spaces. Some of the numbers are equal to -123, and the rest can be any random number.
```
example_string = "102.3 42.89 98 812.7 374 5 -123 8 -123 13 -123 21..."
```
I would like to replace the values that are not equal ... | 2019/01/11 | [
"https://Stackoverflow.com/questions/54140796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691928/"
] | You can use this regex:
```
(^|\s)(?!-123(\s|$))-?[0-9.]+(?=\s|$)
```
It looks for the start of string or a space, not followed by -123 and space of end of string (using a negative lookahead) then some number of digits or a `.`, followed by either a space or end of string.
Then you can replace with `\g<1>456` to tu... | You could match only the numbers between whitspace boundaries and the use re.sub with a callback function to check if the match is not `-123`. If it not, relace it with `456`
```
(?<!\S)-?\d+(?:\.\d+)?(?!\S)
```
**Explanation**
* `(?<!\S)` Negative lookbehind to assert what is on the left is not a non-whitespace ch... | 8,456 |
21,704,149 | I am trying to configure Chronos to use custom mesos-docker executor present at <https://github.com/mesosphere/mesos-docker/> . Everytime I try to run the command it fails.
I created the task using below command
```
echo '{"schedule":"R/2014-02-14T00:52:00Z/PT90M", "name":"testing_docker_executor", "command":"docker_... | 2014/02/11 | [
"https://Stackoverflow.com/questions/21704149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213542/"
] | the problem is here:
```
size_t file;
```
size\_t is unsigned, so it will always be >=0
it should have been:
```
int file;
``` | >
> the open call returns something greater than 0
>
>
>
`open` returns `int`, but you put in in an unsigned variable (`size_t` is usually unsigned), so you fail to detect when it is `<0` | 8,457 |
65,732,046 | here is my code
```
import numpy
a = numpy.arange(0.5, 1.5, 0.1, dtype=numpy.float64)
print(a)
print(a.tolist())
>>>[0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4]
>>>[0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999, 1.0999999999999999, 1.1999999999999997, 1.2999999999999998, 1.4]
```
When tryin... | 2021/01/15 | [
"https://Stackoverflow.com/questions/65732046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14922407/"
] | %%writefile is an IPython [cell magic](https://ipython.readthedocs.io/en/stable/interactive/magics.html#cell-magics), not a magic method. Cell magics are different by line magics because they are identified by a double %.
IPyhton cell and line magics are specific to IPython. See [here](https://ipython.readthedocs.io/e... | If you mean this [magic command in iPython](https://ipython.readthedocs.io/en/stable/interactive/magics.html#cellmagic-writefile) (note: *command*, not *function*), then that's your answer; it is a specific iPython extension, not part of the Python language itself. | 8,458 |
55,454,569 | I am calling some java binary in unix environment wrapped inside python script
When I call script from bash, output comes clean and also being stored in desired variable , However when i run the same script from Cron, Output stored(in a Variable) is incomplete
my code:
```
command = '/opt/HP/BSM/PMDB/bin/abcAdminUt... | 2019/04/01 | [
"https://Stackoverflow.com/questions/55454569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8848689/"
] | ```
alias py=python3.7
py filename.py
```
Add the alias to you `bash_aliases` to get it in every terminal | If you're using linux, you can shorten it to nothing by adding the line
```py
#!/usr/bin/env python3.7
```
to the top of your python file. Then `chmod 755 <filename.py>` and run it like any other executable. | 8,459 |
59,544,848 | I have captcha image as attached in this question.
[](https://i.stack.imgur.com/wVbyF.png)
I am trying to extract the text in the image. My following code is able to make all areas except the text and lines in white color
```
import cv2
from PIL im... | 2019/12/31 | [
"https://Stackoverflow.com/questions/59544848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8340105/"
] | My approach is based on the fact that the line is thinner than the characters. In this example I used blurring, threshold and morphology to get rid of the line between the characters. The result is this:
[](https://i.stack.imgur.com/VwXMR.png)
```py
i... | You can use CV2 functions like threshold, dilate, bitwise\_and and bitwise\_not for removing unwanted lines from captcha
```
import numpy as np
import cv2
img = cv2.imread('captcha.jpg',0)
horizontal_inv = cv2.bitwise_not(img)
masked_img = cv2.bitwise_and(img, img, mask=horizontal_inv)
masked_img_inv = cv2.bitwise_n... | 8,460 |
3,106,994 | I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms.
I was hoping on getting you guys suggestions on how to solve this issue. Any algorithm or library in particular you would like to r... | 2010/06/24 | [
"https://Stackoverflow.com/questions/3106994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245968/"
] | In addition to `difflib` and other common subsequence libraries, if it's natural language text, you might look into stemming, which normalizes words to their root form. You can find several implementations in the Natural Language Toolkit ( <http://www.nltk.org/> ) library. You can also compare blobs of natural language... | Longest common chain? Perhaps this will help then: <http://en.wikipedia.org/wiki/Longest_common_subsequence_problem> | 8,461 |
36,732,614 | Getting errors as below, when I follow **step 4** of the instruction from [Getting Started with ARC Open Source on Linux](https://chromium.googlesource.com/arc/arc/+/release-39.4410.148.0/docs/getting-started-open-source.md). OS is Ubuntu 14.04 LTS running in Hyper-V.
>
> UBUNTU14:~/arc$ ./configure
>
> ERROR:roo... | 2016/04/20 | [
"https://Stackoverflow.com/questions/36732614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/633210/"
] | The problem was bad ACLs on the files. I reached out to @elijah-taylor for a fix, it should now work! | faced same issue..fixed after running the following.
```
apt-get install gsutil
apt-get install libwww-perl
chmod +x ./third_party/tools/depot_tools/third_party/gsutil/gsutil
``` | 8,467 |
51,432,473 | the problem
-----------
I'm trying to use the `concurrent.futures` library to run a function on a list of "things". The code looks something like this.
```
import concurrent.futures
import logging
logger = logging.getLogger(__name__)
def process_thing(thing, count):
logger.info(f'starting processing for thing {... | 2018/07/19 | [
"https://Stackoverflow.com/questions/51432473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7830612/"
] | Here's a little recipe for a `DelaydLogger` class that puts all calls to `logger`'s methods into a list instead of actually performing the call, until you finally do a `flush` where they are all fired up.
```
from functools import partial
class DelayedLogger:
def __init__(self, logger):
self.logger = logg... | First I modified @Jeronimo's answer to come up with this
```
class DelayedLogger:
class ThreadLogger:
"""to be logged from a single thread"""
def __init__(self, logger):
self._call_stack = [] # list of (method, *args, **kwargs) tuples
self.logger = logger
self... | 8,468 |
46,158,930 | Have questions concerning the output of `apply()` method in python `pandas.DataFrame`
### Q1 -
Why does this function returns a `pandas.DataFrame` **with the same format** as the input (`pandas.DataFrame`) when `apply` function returns an `array` with the same shape as input?.
For instance
```
foo = pd.DataFrame([[... | 2017/09/11 | [
"https://Stackoverflow.com/questions/46158930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3941704/"
] | You can do it in one line by composing a regular expression pattern `"(item1|item2|item3)"`
```
let array = ["dee", "kamal"]
let str = "Hello all how are you, I m here for deepak."
let success = str.range(of: "(" + array.joined(separator: "|") + ")", options: .regularExpression) != nil
``` | You should iterate over the array and for each element, call `str.contains`.
```
for word in array {
if str.contains(word) {
print("\(word) is part of the string")
} else {
print("Word not found")
}
}
``` | 8,469 |
46,606,947 | I'm trying to INSERT to MySQL from a CSV file, first 'column' in the file is a date in this format:
```
31/08/2017;
```
then my column in the table is set as YYYY-MM-DD
this is my code:
```
import datetime
import csv
import MySQLdb
...
insertionSQL="INSERT INTO transactions (trans_date, tr... | 2017/10/06 | [
"https://Stackoverflow.com/questions/46606947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5794219/"
] | You will first have to create a path as a rounded rectangle. Then with each step in your animation you have to modify the eight segments of the path. This will only work with `Path` objects, not if your rectangle is a `Shape`.
The segment points and the handles have to be set like this:
[![rounded rect point and handl... | Change the corner size to the following
```
var cornerSize = circle.radius / 1;
``` | 8,471 |
51,308,114 | I am again stuck with extract and compare list elements.
I have following list of lists:
```
list = [['laravel', 1.0, 54],
['laravel', 1.0, 3615],
['php', 1.0, 1405],
['php', 1.0, 5175],
['php', 1.0, 5176],
['php', 1.0, 54],
['php', 1.0, 5252],
['php', 1.0, 5279],
['python', 1.0, 54],
['laravel', 0.8333333... | 2018/07/12 | [
"https://Stackoverflow.com/questions/51308114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9758339/"
] | Using '`Counter`' and '`defaultdict`' from Python:
```
l = [['laravel', 1.0, 54],
['laravel', 1.0, 3615],
['php', 1.0, 1405],
['php', 1.0, 5175],
['php', 1.0, 5176],
['php', 1.0, 54],
['php', 1.0, 5252],
['php', 1.0, 5279],
['python', 1.0, 54],
['laravel', 0.8333333333333334, 54],
['python',0.833333333333333... | You could use something like this,
```
my_list = [['laravel', 1.0, 54],
['laravel', 1.0, 3615],
['php', 1.0, 1405],
['php', 1.0, 5175],
['php', 1.0, 5176],
['php', 1.0, 54],
['php', 1.0, 5252],
['php', 1.0, 5279],
['python', 1.0, 54],
['laravel', 0.8333333333333334, 54],
['python',0.8333333333333334, 3615]]
compute... | 8,472 |
53,853,038 | I have a python list `l` containing instances of the class `Element`:
```py
class Element:
def __init__(self, id, value):
self.id = id
self.value = value
l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)]
```
Now I want to sum all `value` members of the classes `... | 2018/12/19 | [
"https://Stackoverflow.com/questions/53853038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7362422/"
] | There is (almost?) nothing that `itertools` cannot do. Take a look at [`groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby):
```
from itertools import groupby
from operator import attrgetter
class Element:
def __init__(self, id, value):
self.id = id
self.value = value
... | One way would be to create a [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) that maps ids to sums of values. Then we can take those results and use them to build a new list of `Elements`. One way to do that is to use [`starmap`](https://docs.python.org/3/library/itertools.ht... | 8,482 |
26,710,578 | I am using **python 2.7** .I am creating 3 lists (float values (if it matters at all)), i am using json object to save it in a file.
**Say for eg.**
```
L1=[1,2,3,4,5]
L2=[11,22,33,44,55]
L3=[22,33,44,55,66]
b={}
b[1]=L1
b[2]=L2
b[3]=L3
json.dump(b,open("file.txt","w"))
```
I need to read these values back from ... | 2014/11/03 | [
"https://Stackoverflow.com/questions/26710578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2126725/"
] | try
```
content = json.load(open('file.txt'))
```
or using a the [with context manager](https://stackoverflow.com/questions/1369526/what-is-the-python-keyword-with-used-for) to close the file for you:
```
with open('file.txt') as f:
content = json.load(f)
```
Also, read the library's [documentation](https://d... | I used this following code:
```
import json
path=r"file.txt"
for line in open(path):
obj = json.loads(line)
x=obj['1']
y=obj['2']
z=obj['3']
```
Now, i will have the List *L1 in x*, *L2 in y* and *L3 in z* | 8,485 |
8,711,794 | I am looking for the simplest **generic** way to convert this python list:
```
x = [
{"foo":"A", "bar":"R", "baz":"X"},
{"foo":"A", "bar":"R", "baz":"Y"},
{"foo":"B", "bar":"S", "baz":"X"},
{"foo":"A", "bar":"S", "baz":"Y"},
{"foo":"C", "bar":"R", "baz":"Y"},
]
```
into:
... | 2012/01/03 | [
"https://Stackoverflow.com/questions/8711794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248922/"
] | ```
#!/usr/bin/env python3
from itertools import groupby
from pprint import pprint
x = [
{"foo":"A", "bar":"R", "baz":"X"},
{"foo":"A", "bar":"R", "baz":"Y"},
{"foo":"B", "bar":"S", "baz":"X"},
{"foo":"A", "bar":"S", "baz":"Y"},
{"foo":"C", "bar":"R", "baz":"Y"},
]
def fun(... | I would define a function that performs a single grouping step like this:
```
from itertools import groupby
def group(items, key, subs_name):
return [{
key: g,
subs_name: [dict((k, v) for k, v in s.iteritems() if k != key)
for s in sub]
} for g, sub in groupby(sorted(items, key=lamb... | 8,486 |
8,552,556 | I have never used python in my life. I need to make a little fix to a given code.
I need to replace this
```
new_q = q[:q.index('?')] + str(random.randint(1,rand_max)) + q[q.index('?')+1:]
```
with something that replace all of the occurrence of ? with a random, different number.
how can I do that? | 2011/12/18 | [
"https://Stackoverflow.com/questions/8552556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182416/"
] | ```
import re
import random
a = 'abc?def?ghi?jkl'
rand_max = 9
re.sub(r'\?', lambda x:str(random.randint(1,rand_max)), a)
# returns 'abc3def4ghi6jkl'
```
or without regexp:
```
import random
a = 'abc?def?ghi?jkl'
rand_max = 9
while '?' in a:
a = a[:a.index('?')] + str(random.randint(1,rand_max)) + a[a.index('?... | If you need all the numbers to be different, just using a new random number for each occurrence of `?` won't be enough -- a random number might occur twice. You could use the following code in this case:
```
random_numbers = iter(random.sample(range(1, rand_max + 1), q.count("?")))
new_q = "".join(c if c != "?" else s... | 8,488 |
37,803,628 | I'm trying to create a CNN using Tensorflow that classifies images into **16 classes**.
My original image size is 72x72x1, and my network is structured like this:
```
# Network
n_input = dim
n_output = nclass # 16
weights = {
'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32], stddev=0.1)),
'wc2': tf.Var... | 2016/06/14 | [
"https://Stackoverflow.com/questions/37803628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1578098/"
] | Given your code (and guessing what is missing in it), I think you have these parameters and results (correct me if wrong):
* `batch_size`: 1
* `num_classes`: 16
* labels `y`: type int, shape `[batch_size, 1]`
* outputs `_pred`: type float32, **should be** shape `[batch_size, num_classes]`
---
In your code, you only ... | Its hard to tell from what you provided, but it seems like you feed inputs with a batch size of 6, but only provide one label for them. Where does your data come from? | 8,489 |
20,133,316 | I have the following code which works:
```
import xml.etree.ElementTree as etree
def get_path(self):
parent = ''
path = self.tag
sibs = self.parent.findall(self.tag)
if len(sibs) > 1:
path = path + '[%s]'%(sibs.index(self)+1)
current_node = self
while True:
parent = current_no... | 2013/11/21 | [
"https://Stackoverflow.com/questions/20133316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2723675/"
] | If you *need* parents, use lxml instead - it tracks parents internally, and is still C behind the scenes so it's very fast.
However... be aware that there is a tradeoff in tracking parents, in that a given node can only have a single parent. This isn't usually a problem, however, if you do something like the following... | you can just use xpath, for example:
```
import lxml.html
def get_path():
for e in doc.xpath("//b//*"):
print e
```
should work, didn't test it though... | 8,490 |
66,320,831 | TLDR;
=====
It's possible to configure the Beam portable runner with the spark configurations? More precisely, it's possible to configure the `spark.driver.host` in the Portable Runner?
Motivation
==========
Currently, we have airflow implemented in a Kubernetes cluster, and aiming to use TensorFlow Extended we need... | 2021/02/22 | [
"https://Stackoverflow.com/questions/66320831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13454548/"
] | I have three solutions to choose from depending on your deployment requirements. In order of difficulty:
1. Use the Spark "uber jar" job server. This starts an embedded job server inside the Spark master, instead of using a standalone job server in a container. This would simplify your deployment a lot, since you woul... | Let me revise the answer. The Job server need to able to communicate with the workers vice verse. The error of keep exiting is due to this. You need to configure such that they can communicate. A k8s headless service able to solve this.
reference of workable example at <https://github.com/cometta/python-apache-beam-sp... | 8,491 |
55,799,546 | I am trying to make a simple app in kivy(a python package) that gets a text from a TextInput field and when a button is clicked it returns a text in Hebrew that will displayed on another TextInput, Everything seems to be working just fine but I encounter the problem that a TextInput field in Kivy could not show the Heb... | 2019/04/22 | [
"https://Stackoverflow.com/questions/55799546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10139792/"
] | Okay! So it didn't take a long time because someone on a discord server helped me and all I had to do was to just switch the text area font because the previous one didn't have an Hebrew font. To do it I downloaded the font "Arial" added it to my folder with the main script, I imported `from kivy.core.text import Label... | you should also reverse the text that the user type, i did this:
```
class HebrowTextInput(TextInput):
def __init__(self, **kwargs):
super(HebrowTextInput, self).__init__(font_name='DejaVuSans.ttf', halign="right", **kwargs)
self.multiline = False
def keyboard_on_key_down(self, window, keycod... | 8,492 |
34,178,172 | I have created a table:
```
cursor.execute("CREATE TABLE articles (title varchar PRIMARY KEY, pubDate timestamp with time zone);")
```
I inserted a timestamp like this:
```
timestamp = date_datetime.strftime("%Y-%m-%d %H:%M:%S+00")
cursor.execute("INSERT INTO articles VALUES (%s, %s)",
(title, time... | 2015/12/09 | [
"https://Stackoverflow.com/questions/34178172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4772958/"
] | Python's `datetime` objects are automatically [adapted](http://initd.org/psycopg/docs/usage.html#python-types-adaptation) into SQL by `psycopg2`, you don't need to stringify them:
```
cursor.execute("INSERT INTO articles VALUES (%s, %s)",
(title, datetime_obj))
```
To read the rows returned by a `SE... | After some more googling I think I figured it out. If I change:
```
print(row)
```
to
```
print(row[0])
```
It actually works. I guess this is because row is a tuple and this is way to unpack the tuple correctly. | 8,493 |
31,581,902 | How to clone with disabled SSL checking, using GitPython library. The following code ...
```
import git
x = git.Repo.clone_from('https://xxx', '/home/xxx/lala')
```
... yields this error:
```
Error: fatal: unable to access 'xxx': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt C... | 2015/07/23 | [
"https://Stackoverflow.com/questions/31581902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4319148/"
] | The two following methods have been tested with GitPython 2.0.8 but should be working at least since 1.0.2 (from the doc).
As suggested by @Byron:
```py
git.Repo.clone_from(
'https://example.net/path/to/repo.git',
'local_destination',
branch='master', depth=1,
env={'GIT_SSL_NO_VERIFY': '1'},
)
```
As sugges... | It seems easiest to pass the `GIT_SSL_NO_VERIFY` environment variable to all git invocations. Unfortunately [`Git.update_environment(...)`](http://gitpython.readthedocs.org/en/stable/reference.html?highlight=update_environment#git.cmd.Git.update_environment) can only be used on an existing instance, which is why you wo... | 8,496 |
45,994,973 | I have a Numpy one-dimensional array of 1 and 0. for e.g
```
a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0])
```
I want to count the continuous 0s and 1s in the array and output something like this
```
[1,3,7,1,1,2,3,2,2]
```
What I do atm is
```
np.diff(np.where(np.abs(np.diff(a)) == 1)[0])
```
an... | 2017/09/01 | [
"https://Stackoverflow.com/questions/45994973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1947744/"
] | Here's one vectorized approach -
```
np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size])
```
Sample run -
```
In [208]: a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0])
In [209]: np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size])
Out[209]: array([1, 3, 7, 1, 1, 2, 3, 2, 2])
```
Faster one with `b... | Using `groupby` from `itertools`
```
from itertools import groupby
a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0])
grouped_a = [ sum(1 for i in g) for k,g in groupby(a)]
``` | 8,497 |
14,241,239 | Can I have any highlight kind of things using Python 2.7? Say when my script clicking on the `submit button`,feeding data into the `text field` or selecting values from the `drop-down field`, just to highlight on that element to make sure to the script runner that his/her script doing what he/she wants.
***EDIT***
I ... | 2013/01/09 | [
"https://Stackoverflow.com/questions/14241239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2767755/"
] | This is something you need to do with javascript, not python. | ***[NOTE: I'm leaving this answer for historical purposes but readers should note that the original question has changed from concerning itself with Python to concerning itself with Selenium]***
Assuming you're talking about a browser based application being served from a Python back-end server (and it's just a guess ... | 8,500 |
26,691,784 | Example:
```
class Planet(Enum):
MERCURY = (mass: 3.303e+23, radius: 2.4397e6)
def __init__(self, mass, radius):
self.mass = mass # in kilograms
self.radius = radius # in meters
```
Ref: <https://docs.python.org/3/library/enum.html#planet>
Why do I want to do this? If there are a f... | 2014/11/01 | [
"https://Stackoverflow.com/questions/26691784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257299/"
] | While you can't use named arguments the way you describe with enums, you can get a similar effect with a [`namedtuple`](https://docs.python.org/3/library/collections.html#collections.namedtuple) mixin:
```
from collections import namedtuple
from enum import Enum
Body = namedtuple("Body", ["mass", "radius"])
class Pl... | The accepted answer by @zero-piraeus can be slightly extended to allow default arguments as well. This is very handy when you have a large enum with most entries having the same value for an element.
```
class Body(namedtuple('Body', "mass radius moons")):
def __new__(cls, mass, radius, moons=0):
return su... | 8,501 |
74,542,597 | i have a a number of xml files with me, whose format is:
```
<objects>
<object>
<record>
<invoice_source>EMAIL</invoice_source>
<invoice_capture_date>2022-11-18</invoice_capture_date>
<document_type>INVOICE</document_type>
<data_capture_provider_code>00001</data_capture_pro... | 2022/11/23 | [
"https://Stackoverflow.com/questions/74542597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397498/"
] | So here is what I would do.
Instead of controlling the stamina in multiple places and hve forth and back references (=dependencies) between all your scripts I would rather keep this authority within the `PlayerController`.
Your `StaminaBar` component should be purely **listening** and visualizing the current value wi... | You're decreasing and increasing the stamina in the same scope. I think you should let the stamina to be drained when sprint is pressed and start regenerating only if it is released. | 8,507 |
59,573,454 | I am trying to find a simple way to calculate soft cosine similarity between two sentences.
Here is my attempt and learning:
```
from gensim.matutils import softcossim
sent_1 = 'Dravid is a cricket player and a opening batsman'.split()
sent_2 = 'Leo is a cricket player too He is a batsman,baller and keeper'.split()
... | 2020/01/03 | [
"https://Stackoverflow.com/questions/59573454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4763959/"
] | As of the current version of Gensim, 3.8.3, some of the method calls from both the question and previous answers have been deprecated. Those functions deprecated have been removed from the 4.0.0 beta. Can't seem to provide code in a reply to @EliadL, so adding a new comment.
The current method for solving this problem... | Going by [this tutorial](https://www.machinelearningplus.com/nlp/gensim-tutorial/#18howtocomputesimilaritymetricslikecosinesimilarityandsoftcosinesimilarity):
```
import gensim.downloader as api
from gensim import corpora
from gensim.matutils import softcossim
sent_1 = 'Dravid is a cricket player and a opening batsma... | 8,508 |
510,972 | How do I find out the name of the class used to create an instance of an object in Python?
I'm not sure if I should use the [`inspect`](https://docs.python.org/2/library/inspect.html "inspect — Inspect live objects") module or parse the `__class__` attribute. | 2009/02/04 | [
"https://Stackoverflow.com/questions/510972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18909/"
] | ```
class A:
pass
a = A()
str(a.__class__)
```
The sample code above (when input in the interactive interpreter) will produce `'__main__.A'` as opposed to `'A'` which is produced if the `__name__` attribute is invoked. By simply passing the result of `A.__class__` to the `str` constructor the parsing is handled fo... | In Python 2,
```
type(instance).__name__ != instance.__class__.__name__
# if class A is defined like
class A():
...
type(instance) == instance.__class__
# if class A is defined like
class A(object):
...
```
Example:
```
>>> class aclass(object):
... pass
...
>>> a = aclass()
>>> type(a)
<class '__main__.acl... | 8,511 |
70,014,480 | I've been hosting my static site via an google app engine standard python setup for years without a problem. Today I started seeing the error below. Note: there used to be a page on GCP explaining how to host a static page using python GAE standard, but I can't find it now. Is it maybe the case where now it's recommend... | 2021/11/18 | [
"https://Stackoverflow.com/questions/70014480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10458445/"
] | This error only happened on Nov 17th and has since not happened again, without any changes by me. Perhaps it was related to something under-the-hood on google app engine servers. | Note that you are using Python 3.8 as per your `app.yaml` file, and the document you have shared is for Python 2.7. As Python 2 is no longer supported, migrating from Python 2 to Python 3 runtime will help you remove the error.
The documentation [here](https://cloud.google.com/appengine/docs/standard/python/migrate-to... | 8,521 |
50,996,060 | I'm trying to use ruamel.yaml to modify an AWS CloudFormation template on the fly using python. I added the following code to make the safe\_load working with CloudFormation functions such as `!Ref`. However, when I dump them out, those values with !Ref (or any other functions) will be wrapped by quotes. CloudFormation... | 2018/06/22 | [
"https://Stackoverflow.com/questions/50996060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3209177/"
] | Essentially you tweak the loader, to load tagged (scalar) objects as if they were mappings, with the tag the key and the value the scalar. But you don't do anything to distinguish the `dict` loaded from such a mapping from other dicts loaded from normal mappings, nor do you have any specific code to represent such a ma... | Apart from Anthon's detailed answer above, for the specific question in terms of CloudFormation template, I found another very quick & sweet workaround.
Still using the constructor snippet to load the YAML.
```
def funcparse(loader, node):
node.value = {
ruamel.yaml.ScalarNode: loader.construct_scalar,
... | 8,522 |
62,585,490 | TF 2.3.0.dev20200620
I got this error during .fit(...) for a model with a sigmoid binary output. I used tf.data.Dataset as the input pipeline.
The strange thing is it depends on the metric:
Don't work:
```
model.compile(
optimizer=tf.keras.optimizers.Adam(lr=1e-4, decay=1e-6),
loss=tf.keras.losses.BinaryCros... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62585490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762295/"
] | Had exactly the same problem when using 'accuracy' metric.
I followed <https://github.com/tensorflow/tensorflow/issues/32912#issuecomment-550363802> example:
```
def _fixup_shape(images, labels, weights):
images.set_shape([None, None, None, 3])
labels.set_shape([None, 19]) # I have 19 classes
weights.set_... | I am able to fix this in such a way as to keep the metrics 'accuracy' (rather than using BinaryAccuracy). However, I do not quite understand why this is needed for 'accuracy', but not needed for other closely related one (e.g. BinaryAccuracy).
2 things:
1. construct a ds such that the batch label has shape of (batch\... | 8,523 |
49,989,188 | I have function like this one:
```
def get_list_of_movies(table):
#some code here
print(a_list)
return a_list
```
Reason why I want to use print and return is that I'm using this function in many places. So after calling this function from menu I want to get printed list of content.
This same functio... | 2018/04/23 | [
"https://Stackoverflow.com/questions/49989188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8773813/"
] | Add a separate argument with a default value of `None` to control the printing. Pass
```
def get_list_of_movies(table, printIt=False):
...
if printIt:
print(a_list)
return a_list
...
movies = get_list_of_movies(table, printIt=True)
```
Another approach is to pass `print` itself as the argument,... | A completely different approach is to *always* print the list, but control where it gets printed *to*:
```
def get_list_of_movies(table, print_to=os.devnull):
...
print(a_list, file=location)
return a_list
movies = get_list_of_movies(table, print_to=sys.stdout)
```
The `print_to` argument can be any fi... | 8,524 |
11,882,194 | I have a django web application running on our **apache2** production server using **mod\_python**, but no static files are found (css,images ... )
All our static stuff is under `/var/my.site/example/static`
```
/var/my.site/example/static/
|-admin/
|-css/
... | 2012/08/09 | [
"https://Stackoverflow.com/questions/11882194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481406/"
] | After @supervacuo suggestion that I strip down everything from django, I got apache to serve the static files and realized what was wrong.
The problem was that `<Location "/example">` got priority over `Alias /example/static`. It didn't matter where I put the `Alias` (above or below the `<Location> - tag`).
To fix ... | Try to eliminate the problem step-by-step.
Loading static files should work completely independently of Django. Try commenting out all lines relating to Django in your `VirtualHost` config. (Remember to reload Apache after changing the configuration)
If that works, it may be that you need to take more steps to avoid ... | 8,525 |
61,966,894 | So I was using flask\_login for my login system on my mac, and I seem to have run into a problem. When I ran the code, it says I have not set my secret key even if I had done so.
My code was:
```py
from flask import Flask, render_template, request, session, redirect, url_for, jsonify
from flask_session import Session... | 2020/05/23 | [
"https://Stackoverflow.com/questions/61966894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13600242/"
] | As @Harmandeep Kalsi said in the comments, I added `app.config['SESSION_TYPE']` and it worked. | For anyone else that is still getting an error after the other answers, if you're using the format `app.confing['<string>']` make sure that you include the underscore between "SECRET" and "KEY".
That ended up being my issue, but it results in the same error code so searching for it lead me here. So, I thought I'd prov... | 8,528 |
11,170,414 | I just upgraded from SnowLeapord to Lion and now cannot create virtualenvs. I understand that there are new Python installations after the upgrade and no site packages and have tried installing pip and virtualenv again as well as upgrading to Xcode4 but I always get this error:
```
~ > virtualenv --distribute env
New ... | 2012/06/23 | [
"https://Stackoverflow.com/questions/11170414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/883845/"
] | Turns out that although I upgraded Xcode to version 4, it does not automatically install the command line tools. I followed this <http://blog.cingusoft.org/mac-osx-lion-virtualenv-and-could-not-call-in>.
Basically, install Xcode, go into Preferences and then Downloads and install "Command Line Tools". It works now.
... | I also had to upgrade my setuptools.
`pip install setuptools --upgrade` | 8,529 |
57,151,931 | I've created a python script together with selenium to parse a specific content from a webpage. I can get this result `AARONS INC` located under `QUOTE` in many different ways but the way I wish to scrape that is by using ***`pseudo selector`*** which unfortunately selenium doesn't support. The commented out line withi... | 2019/07/22 | [
"https://Stackoverflow.com/questions/57151931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7180194/"
] | This is one of the ways you can achieve that. Give it a shot.
```
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
with webdriver.Chrome() as driver:
wait = WebDriverWait(driver, 10)
driver.get('https://www.nyse.com/quote/XNYS:AAN')
item = wait.until(
lambda ... | Here is the simple approach.
```
url = 'https://www.nyse.com/quote/XNYS:AAN'
driver.get(url)
# wait for the elment to be presented
ele = WebDriverWait(driver, 30).until(lambda driver: driver.execute_script('''return $('span:contains("AARONS")')[0];'''))
# print the text of the element
print (ele.text)
``` | 8,531 |
15,669,924 | I'm trying to get tumblr "liked" posts for a user at the <http://api.tumblr.com/v2/user/likes> url. I have registered my app with tumblr and authorized the app to access the user's tumblr data, so I have `oauth_consumer_key`,
`oauth_consumer_secret`, `oauth_token`, and `oauth_token secret`. However, I'm not sure what ... | 2013/03/27 | [
"https://Stackoverflow.com/questions/15669924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1132385/"
] | Well if you don't mind using Python I can recommend [rauth](https://github.com/litl/rauth). There isn't a Tumblr example, but there are [real world, working examples](https://github.com/litl/rauth/tree/master/examples) for both OAuth 1.0/a and OAuth 2.0. The API is intended to be simple and straight forward. I'm not su... | I sort of found an answer. I ended up using OAuth::Consumer in perl to connect to the tumblr API. It's the simplest solution I've found so far and it just works. | 8,533 |
64,063,248 | My Python version:`Python 3.8.3`
`python -m pip install IPython` gives me `Successfully installed IPython-7.18.1`
Still gives me the following error:
```
from IPython.display import Image
/usr/bin/python3 "/home/sanyifeju/Desktop/python/ML/decision_trees.py"
Traceback (most recent call last):
File "/home/san... | 2020/09/25 | [
"https://Stackoverflow.com/questions/64063248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1107591/"
] | I had the same issue, and the problem was that the `python` command was linked to the python2 version:
```
$ ls -l /usr/bin/python
lrwxrwxrwx 1 root root 7 Apr 15 2020 /usr/bin/python -> python2*
```
The following commands fixed it for me:
```
$ sudo rm /usr/bin/python
$ sudo ln -s python3 /usr/bin/python
``` | Try installing-
```
python -m pip install ipython
``` | 8,534 |
13,218,362 | I'm currently learning python and tried to make a little game using the pygame librabry. I use python 3.2.3 and pygame 1.9.2a with Windows Xp. Everything works fine, except one thing : if I go on another window when my game is running, it crashes and I get an error message in the console :
```
Fatal Python error: (pyg... | 2012/11/04 | [
"https://Stackoverflow.com/questions/13218362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1717248/"
] | I know thread is old, but I was getting the same error "Fatal Python error: (pygame parachute) Segmentation Fault" in linux when I resized a pygame window continuously for several seconds. Just in case this helps anyone else, it turned out to be caused by blitting to the window surface in one thread when I was resizing... | I don't know if you have anything after the last line that you're not putting in, but if you don't, you should replace your last line with
```
pygame.quit()
sys.exit()
```
As an alternative, you could put those two lines outside of the `while` loop and keep what you have. Don't forget to `import sys`. | 8,535 |
68,532,863 | I currently have a multiple regression that generates an OLS summary based on the life expectancy and the variables that impact it, however that does not include RMSE or standard deviation. Does statsmodels have a rsme library, and is there a way to calculate standard deviation from my code?
I have found a previous ex... | 2021/07/26 | [
"https://Stackoverflow.com/questions/68532863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12374203/"
] | The canonical dplyr-way would be to write a custom predicate function that returns `TRUE` or `FALSE` for each column depending on whether the conditions are matched and use this function inside `across(where(predicate_function), ...)`.
Below I borrow the example data from @Tob and add some variations (one column is `0... | This is what I might do but I don't know how fast it will if your data is large
```
# Create some data
test_data <- data.frame(strings = c("a", "b", "c", "d", "e"),
col_2 = c(1, 0, 0, 0, 1),
col_3 = c( 0,1, 1, 0, 1))
# Find columns that are only 0s and 1s
cols_to_convert <- names(tes... | 8,536 |
20,338,360 | I am looking for a production database to use with python/django for web development. I've installed MySQL successfully. I believe the python connector is not working and I don't know how to make it work. Please point me in the right direction. Thanks.
If I try importing `MySQLdb`:
```
import MySQLdb
```
I get the ... | 2013/12/02 | [
"https://Stackoverflow.com/questions/20338360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2424253/"
] | If your problem is with the `MySQLdb` module, not the MySQL server itself, you might want to consider [`PyMySQL`](https://github.com/PyMySQL/PyMySQL) instead. It's much simpler to set up. Of course it's also somewhat different.
The key difference is that it's a pure Python implementation of the MySQL protocol, not a w... | I would recommend postgres.app : <http://postgresapp.com>
Tried and never left
My preference for the driver is <http://initd.org/psycopg/>
You'll find a list of drivers at <http://wiki.postgresql.org/wiki/Python> | 8,539 |
3,947,878 | I have a appengine webapp where i need to set HTTP Location variable to redirect to another page in the same webapp. For that i need to produce a absolute link. for portability reason i cannot use directly the domain name which i am currently using.
Is it possible to produce the domain name on which the webapp is host... | 2010/10/16 | [
"https://Stackoverflow.com/questions/3947878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/329292/"
] | I don't think I quite fully understand the need to getdomain name. But check out if redirect API provided by google app engine will do the job.
<http://code.google.com/appengine/docs/python/tools/webapp/redirects.html> | this question is poorly answered. You need the domain name to generate pages like: robots.txt, sitemap.xml and many many more things which are not relative links. Ive tried using this:
```
from google.appengine.api.app_identity import get_default_version_hostname
host = get_default_version_hostname()
```
but... it... | 8,540 |
71,288,828 | I am trying to extract book names from oreilly media website using python beautiful soup.
However I see that the book names are not in the page source html.
I am using this link to see the books:
[https://www.oreilly.com/search/?query=\*&extended\_publisher\_data=true&highlight=true&include\_assessments=false&includ... | 2022/02/27 | [
"https://Stackoverflow.com/questions/71288828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7895331/"
] | So if you investigate into network tab, when loading page, you are sending request to API
[](https://i.stack.imgur.com/kKfDY.png)
It returns json with books.
After some investigation by me, you can get your titles via
```
import json
import requests
response_json... | To solve this issue you need to know beautiful soup can deal with websites that use plan html. so the the websites that use JavaScript in their page beautiful soup cant's get all page data that you looking for bcz you need a browser like to load the JavaScript data in the website.
and here you need to use Selenium bcz ... | 8,545 |
63,424,301 | I am trying to refresh power b.i. more frequently than current capability of gateway schedule refresh.
I found this:
<https://github.com/dubravcik/pbixrefresher-python>
Installed and verified I have all required packages installed to run.
Right now it works fine until the end - where after it refreshes a Save functio... | 2020/08/15 | [
"https://Stackoverflow.com/questions/63424301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11854373/"
] | If this is your command line:
```
g++ -std=c++17 -pthread -o http_test.out http_test.cpp -lssl -lcrypto && ./http_test.out
```
Aren't you missing "-O2"? It looks like you are building without optimizations. Which will be considerably slower. | From what i know of bitmex engine, having a latency around 10ms for order execution is the best you can get, and it will be worse during high volatility periods. Check <https://bonfida.com/latency-monitor> to get an idea of latencies. On crypto world, latency are far higher than traditional hft | 8,546 |
31,687,690 | I just got a new MackBook Pro and installed Python 3.4.
I ran the terminal and typed
```
python3.4
```
I got:
```
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
```
I typed:
``... | 2015/07/28 | [
"https://Stackoverflow.com/questions/31687690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4996405/"
] | Notice the "..." prompt? That's telling you that the interactive interpreter knows you are in a block. You'll have to enter a blank line to terminate the block, before doing the final print statement.
This is an artifact of running interactively -- the blank line isn't required when you type your code into a file. | You have to use space for indentation (and ";" to separate two instruction :
```
>>> counter = 5
>>> while counter > 0:
counter -= 1
print("Hello")
Hello
Hello
Hello
Hello
Hello
>>>
``` | 8,547 |
28,242,066 | my code :
```
def isModuleBlink(modulename):
f = '/tmp/'+modulename + '.blink'
if(os.path.isfile(f)):
with open(f) as fii:
res = fii.read()
print 'res',res
print res is '1'
if(res is '1'):
print 'return true'
return True
return False
```
and print out :
```
res 1
False
```
... | 2015/01/30 | [
"https://Stackoverflow.com/questions/28242066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3585139/"
] | `res` is `1 \n` and not `1` ... in condition i replaced `1 in res` and work ...
thanks | `is` tests if things are *identical*. You want to test if two strings are equal, not necessarily that they occupy the same memory address. So you want `==`. | 8,553 |
38,249,606 | Say I have a vector of values from a tokenizing function, `tokenize()`. I know it will only have two values. I want to store the first value in `a` and the second in `b`. In Python, I would do:
```python
a, b = string.split(' ')
```
I could do it as such in an ugly way:
```cpp
vector<string> tokens = tokenize(strin... | 2016/07/07 | [
"https://Stackoverflow.com/questions/38249606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459669/"
] | With structured bindings (definitely will be in C++17), you'd be able to write something like:
```
auto [a,b] = as_tuple<2>(tokenize(str));
```
where `as_tuple<N>` is some to-be-declared function that converts a `vector<string>` to a `tuple<string, string, ... N times ...>`, probably throwing if the sizes don't matc... | Ideally you'd rewrite the `tokenize()` function so that it returns a pair of strings rather than a vector:
```
std::pair<std::string, std::string> tokenize(const std::string& str);
```
Or you would pass two references to empty strings to the function as parameters.
```
void tokenize(const std::string& str, std::str... | 8,554 |
8,055,132 | I have the script below which I'm using to send say 10 messages myself<->myself. However, I've noticed that Python really takes a while to do that. Last year I needed a system to send about 200 emails with attachments and text and I implemented it with msmtp + bash. As far as I remember it was much faster.
Moving the ... | 2011/11/08 | [
"https://Stackoverflow.com/questions/8055132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030287/"
] | You are opening the connection to the SMTP server and then closing it for each email. It would be more efficient to keep the connection open while sending all of the emails. | The real answer here is "profile that code!". Time how long different parts of the code take so you know where most of the time is spent. That way you'll have a real answer without guesswork.
Still, my guess would be that it is the calls to `smtp_serv.verify(recipient)` may be the slow ones. Reasons might be that the ... | 8,557 |
34,162,320 | I want to execute bash command
```
'/bin/echo </verbosegc> >> /tmp/jruby.log'
```
in python using Popen. The code does not raise any exception, but none change is made on the jruby.log after execution. The python code is shown below.
```
>>> command='/bin/echo </verbosegc> >> '+fullpath
>>> command
'/bin/echo </v... | 2015/12/08 | [
"https://Stackoverflow.com/questions/34162320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/910118/"
] | The first argument to `subprocess.Popen` is the array `['/bin/echo', '</verbosegc>', '>>', '/tmp/jruby.log']`. When the first argument to `subprocess.Popen` is an array, it does not launch a shell to run the command, and the shell is what's responsible for interpreting `>> /tmp/jruby.log` to mean "write output to jruby... | Have you tried without splitting the command `and using shell=True`? My usual format is:
```
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
output = process.stdout.read() # or .readlines()
``` | 8,562 |
46,668,481 | I'm trying to use PyQt\_Fit. I installed it from pip install pyqt\_fit but when I import it does not work and show me this message:
```
----------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-8-36ec621967a7> in <modu... | 2017/10/10 | [
"https://Stackoverflow.com/questions/46668481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8752769/"
] | I faced the same problem with you. when I install the pyqt\_fit package successfully by
```
sudo pip install git+https://github.com/Multiplicom/pyqt-fit.git
```
It will install the path.py (The last version) and pyqt\_fit at the same time.
Then When I import the package, I faced the follow error
```
import pyqt_fi... | This seems to be happening for quite some time. Check this recent issue report [on the repo](https://github.com/sergeyfarin/pyqt-fit/issues/5).
I've installed the package and tested myself and I got the same problem. Checked the solution provided on the possible duplicate and seems to have fixed the problem.
You migh... | 8,567 |
72,179,492 | Recently, I updated to Ubuntu 22. I am using python 3.10.
After installing matplotlib and other required libraries for python, I am trying to plot some graphs.
Everytime I am facing this error while running my code.
I followed all the solutions given in stackoverflow or Google but no luck.
This is the error I am get... | 2022/05/10 | [
"https://Stackoverflow.com/questions/72179492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16780162/"
] | ```
md$Children[which(x >= 8 & y < 60)] = NA
``` | @AbdurRohman's answer is good.
You could use
```r
md <- within(md,
Children[Children >= 8 & Age <60] <- NA
)
```
for slightly clearer code. (You should definitely tell your instructor you got help on Stack Overflow.) | 8,569 |
9,794,616 | I'm using the following code which will generate a wav file which contains a tone at 440 Hz lasting for 2 seconds.
```
from scipy.io.wavfile import write
from numpy import linspace,sin,pi,int16
def note(freq, len, amp=1, rate=44100):
t = linspace(0,len,len*rate)
data = sin(2*pi*freq*t)*amp
return data.astype(int1... | 2012/03/20 | [
"https://Stackoverflow.com/questions/9794616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/840973/"
] | You can do this using numpy.concatenate, (as already posted). You need to specify the concatenation axis also. Using very low rate to illustrate:
```
from scipy.io.wavfile import write
from numpy import linspace,sin,pi,int16,concatenate
def note(freq, len, amp=1, rate=5):
t = linspace(0,len,len*rate)
data = sin(2*p... | `numpy.linspace` creates a numpy array. To concatenate the tones, you'd want to concatenate the corresponding arrays. For this, a bit of Googling indicates that Numpy provides the helpfully named [`numpy.concatenate` function](http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html). | 8,570 |
5,151,898 | I realized there is a memory leak in one python script. Which occupied around 25MB first, and after 15 days it is more than 500 MB.
I followed many different ways, and not able to get into the root of the problem as am a python newbie...
Finally, I got this following
```
objgraph.show_most_common_types(limit=20)
t... | 2011/03/01 | [
"https://Stackoverflow.com/questions/5151898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/379997/"
] | Am I reading correctly that the same script is running for 15 days non-stop?
For such long-running processes periodic restart is a good practice and it's much easier to do than eliminating all memory leaks.
*Update*: Look at [this answer](https://stackoverflow.com/questions/1641231/python-working-around-memory-leaks/... | My first thought is, probably you are creating new objects in you script and accumulating them in some sort of global list. It is usually easier to go over your script and make sure that you are not generating any persistent data than debugging the garbage. I think the utility you are using, objgraph, also allows you t... | 8,571 |
10,928,313 | Is anyone familiar with DRAKON?
I quite like the idea of the DRAKON visual editor and have been playing with it using Python -- more info: <http://drakon-editor.sourceforge.net/python/python.html>
The only thing I've had a problem with so far is python's try: except: exceptions. The only way I've attempted it is to u... | 2012/06/07 | [
"https://Stackoverflow.com/questions/10928313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/507286/"
] | You could put the whole "try: except:" construct inside one "Action" icon like this:

Both spaces and tabs can be used for indentation inside an icon. | There are limitation exist in Drakon since it is a code generator, but what you can do is to re-factor the code as much as possible and stuff it inside action block:
```
try:
function_1()
function_2()
except:
function_3()
```
Drakon works best if you follow suggested rules(skewer,happy route,branching etc)... | 8,572 |
15,063,936 | I have a script reading in a csv file with very huge fields:
```
# example from http://docs.python.org/3.3/library/csv.html?highlight=csv%20dictreader#examples
import csv
with open('some.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row)
```
However, this throws the followin... | 2013/02/25 | [
"https://Stackoverflow.com/questions/15063936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1251007/"
] | This could be because your CSV file has embedded single or double quotes. If your CSV file is tab-delimited try opening it as:
```
c = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
``` | You can use the `error_bad_lines` option of `pd.read_csv` to skip these lines.
```py
import pandas as pd
data_df = pd.read_csv('data.csv', error_bad_lines=False)
```
This works since the "bad lines" as defined in pandas include lines that one of their fields exceed the csv limit.
Be careful that this solution is v... | 8,573 |
48,206,553 | I am trying to make a view that i can use in multiple apps with different redirect urls:
Parent function:
```
def create_order(request, redirect_url):
data = dict()
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
form.save()
return redire... | 2018/01/11 | [
"https://Stackoverflow.com/questions/48206553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7161215/"
] | ```
url(r'^orders/create/', views.create_order, name='create_order')
```
This clearly is not going to work, since `create_order` requires `redirect_url` but there is no `redirect_url` kwarg in the regex `r'^orders/create/'`.
Perhaps you want to use the `admin_order_document` view here instead:
```
url(r'^orders/cre... | If you didn't changed the regular url
```
urlpatterns = [
url(r'^admin/', admin_site.urls),
...
]
```
of your admin site you need to call your function like that:
```
@login_required()
def admin_order_document(request):
redirect_url = 'admin:order_waiting_list'
return create_order(request, redirect... | 8,583 |
35,438,785 | I have a list of numbers and I want to make rows and columns out of the list.
I can brute force it and do the following below in Python 2.7.
```
l = [1,2,3,4,5,6,7,8,9]
r1 = [l[0], l[1], l[2]]
r2 = [l[3], l[4], l[5]]
r3 = [l[6], l[7], l[8]]
c1 = [l[0], l[3], l[6]]
```
But I can't seem to create a function in py... | 2016/02/16 | [
"https://Stackoverflow.com/questions/35438785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5936229/"
] | Your error is a misunderstanding in [how Python passes arguments](http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/). `r` in the function `make_row` is just a name. When you assign into it, it simply points that name to something new, in the context of your function, lea... | Your function `make_row` works as far as I can tell (I have not tested it), but you need to `return r`. | 8,584 |
42,230,691 | For a beginner in Tkinter, and just average in Python, it's hard to find proper stuff on tkinter. Here is the problem I met (and begin to solve). I think Problem came from python version.
I'm trying to do a GUI, in OOP, and I got difficulty in combining different classes.
Let say I have a "small box" (for example, a ... | 2017/02/14 | [
"https://Stackoverflow.com/questions/42230691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6721930/"
] | The tutorial you are using has an incorrect example. The `Tk` class doesn't have a parent.
Also, you must only create a single instance of `Tk` (or subclass of `Tk`). Tkinter widgets exist in a tree-like hierarchy with a single root. This root widget is `Tk()`. You cannot have more than one root. | The code looks quite similar at this one : [Best way to structure a tkinter application](https://stackoverflow.com/questions/17466561/best-way-to-structure-a-tkinter-application)
But there is one slight difference, we're not working on Frame here. And the error asks for a problem in screenName, etc. which, intuitively... | 8,587 |
45,733,399 | I have a Javascript file `Commodity.js` like this:
```
commodityInfo = [
["GLASS ITEM", 1.0, 1.0, ],
["HOUSEHOLD GOODS", 3.0, 2.0, ],
["FROZEN PRODUCTS", 1.0, 3.0, ],
["BEDDING", 1.0, 4.0, ],
["PERFUME", 1.0, 5.0, ],
["HARDWARE", 5.0, 6.0, ],
["CURTAIN", 1.0, 7.0, ],
["CLOTHING", 24.0, 8.0, ],
["ELECTRICAL IT... | 2017/08/17 | [
"https://Stackoverflow.com/questions/45733399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6624726/"
] | The following code may not be the most efficient, but it works for your case.
What I'm doing here: turn the string (the content of the file) into valid JSON and then load the JSON string into a Python variable.
Note: It would be easier if the content of your JS file was already valid JSON!
```
import re
import json
... | You can use `for` loops to achieve that.
Something like this would work:
```
for commodity in commodityInfo:
commodity[0] # the first element (e.g: GLASS ITEM)
commodity[1] # the second element (e.g: 1.0)
print(commodity[1] + commodity[2]) #calculate two values
```
You can learn more about `for` loops [... | 8,588 |
20,554,040 | I'm new with Django and I follow a tuto. The problem is that the tuto uses Sqlite but I want to use MySql server instead. I changed the parameters following documentation but I have the following error when I try to run the server. I already found some resolve but it didn't work...
For your information, I installed My... | 2013/12/12 | [
"https://Stackoverflow.com/questions/20554040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2904080/"
] | Your problem is most likely related to buffering in your system, not anything intrinsically wrong with your line of code. I was able to create a test scenario where I could reproduce it - then make it go away. I hope it will work for you too.
Here is my test scenario. First I write a short script that writes the time ... | Consider how `uniq -c` is working.
In order to print the count, it needs to read all the unique lines and only once a line that is different from the previous one, it can print the line and number of occurences.
That's just how the algorithm fundamentally works and there is no way around it.
You can test this by run... | 8,589 |
6,929,981 | I'm trying to build a regex that joins numbers in a string when they have spaces between them, ex:
```
$string = "I want to go home 8890 7463 and then go to 58639 6312 the cinema"
```
The regex should output:
```
"I want to go home 88907463 and then go to 586396312 the cinema"
```
The regex can be either in pytho... | 2011/08/03 | [
"https://Stackoverflow.com/questions/6929981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797495/"
] | Use a look-ahead to see if the next block is a set of numbers and remove the trailing space. That way, it works for any number of sets (which I suspected you might want):
```
$string = "I want to go home 8890 7463 41234 and then go to 58639 6312 the cinema";
$newstring = preg_replace("/\b(\d+)\s+(?=\d+\b)/", "$1", $s... | Python:
```
import re
text = 'abc 123 456 789 xyz'
text = re.sub(r'(\d+)\s+(?=\d)', r'\1', text) # abc 123456789 xyz
```
This works for any number of consecutive number groups, with any amount of spacing in-between. | 8,592 |
71,583,214 | In GitBook, the title shows up while mousing over them by default.
[](https://i.stack.imgur.com/nXE8q.png)
I wanna show up the title. I inspect the elements,
```html
<div class="book-header" role="navigation">
<!-- Title -->
<h1>
<i class="fa... | 2022/03/23 | [
"https://Stackoverflow.com/questions/71583214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3067748/"
] | Because .book-header h1 opacity is 0.
Try add this to your css.
```
.book-header h1 {
opacity:1!important;
}
``` | Try this! More about `color: inherit` [here](https://www.w3schools.com/cssref/css_inherit.asp). You can use other property like `z-index`, `opacity` and `position` if it doesn't work too. Thanks :)
```css
.book-header h1 a, .book-header h1 a:hover {
display: block !important;
color: #000 !important;
text-d... | 8,593 |
46,908,231 | I'm a noobie, learning to code and i stumbled upon an incorrect output while practicing a code in python, please help me with this. I tried my best to find the problem in the code but i could not find it.
Code:
```
def compare(x,y):
if x>y:
return 1
elif x==y:
return 0
else:
return... | 2017/10/24 | [
"https://Stackoverflow.com/questions/46908231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8818971/"
] | `raw_input` returns a string always.
so you have to convert the input values into numbers.
```
i=raw_input("enter x\n")
j=raw_input("enter y\n")
print compare(i,j)
```
should be
```
i=int(raw_input("enter x\n"))
j=int(raw_input("enter y\n"))
print compare(i,j)
``` | Your issue is that `raw_input()` returns a string, not an integer.
Therefore, what your function is actually doing is checking "10" > "5", which is `False`, therefore it falls through your `if` block and reaches the `else` clause.
To fix this, you'll need to cast your input strings to integers by wrapping the values ... | 8,594 |
66,385,439 | I'm working on a project where I need to convert a set of data rows from database into `list of OrderedDict` for other purpose and use this `list of OrderedDict` to convert into a `nested JSON` format in `python`. I'm starting to learn python. I was able convert the query response from database which is a `list of list... | 2021/02/26 | [
"https://Stackoverflow.com/questions/66385439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2699684/"
] | I was able to write a python code to get the format as I needed using simple looping with a couple of changes in the output like the fields SessionID, Num\_Pax and Channel is taken outside then the OUTBOUND field and fields within are generated.
Instead of OrderedDict, I used a list of lists as input which I convert i... | Assuming that you stored the dictionary to some variable `foo`, you can do:
```py
import json
json.dumps(foo)
```
And be careful, you added extra bracket in the 4th element `OUTBOUND` list | 8,596 |
67,055,004 | My Azure devops page will look like :
[](https://i.stack.imgur.com/YBdJx.png)
I have 4 pandas dataframes.
I need to create 4 sub pages in Azure devops wiki from each dataframe.
Say, Sub1 from first dataframe, Sub2 from second dataframe and so on.
My... | 2021/04/12 | [
"https://Stackoverflow.com/questions/67055004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11049287/"
] | use value() method
```
$user->image()->value('image');
```
From [Eloquent documentation](https://laravel.com/docs/8.x/queries#retrieving-a-single-row-column-from-a-table)
>
> If you don't need an entire row, you may extract a single value from a record using the value method. This method will return the value of t... | You can create another function inside your model and access the previous method like
```
public function image()
{
return $this->hasOne(UserImages::class, 'user_id', 'id')->latest();
}
public function avatar()
{
return $this->image->image ?: null;
//OR
return $this->image->image ?? null;
//OR
return !is_... | 8,597 |
30,114,579 | I am running ubuntu 12.04 and running programs through the terminal. I have a file that compiles and runs without any issues when I am in the current directory. Example below,
```
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$ pwd
/home/david/Documents/BudgetAutomation/BillList
david@block-ubunt... | 2015/05/08 | [
"https://Stackoverflow.com/questions/30114579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4362951/"
] | Your problem starts in line 5:
```
arr = glob.glob('./*.txt')
```
You are telling glob to look in the local directory for all .txt files. Since you are one directory up you do not have these files.
You are getting a ValueError because the line variable is empty.
As it is written you will need to run it from that ... | You don't need to create that range object to iterate over the glob result. You can just do it like this:
```
for file_path in arr:
with open(file_path) as text_file:
#...code below...
```
The reason of why that exception is raised, I guess, is there exist text files contain content not conforming with y... | 8,599 |
14,965,542 | I have a huge file from which I need data for specific entries. File structure is:
```
>Entry1.1
#size=1688
704 1 1 1 4
979 2 2 2 0
1220 1 1 1 4
1309 1 1 1 4
1316 1 1 1 4
1372 1 1 1 4
1374 1 1 1 4
1576 1 1 1 4
>Entry2.1
#size=6251
6110 3 1.5 0 2
... | 2013/02/19 | [
"https://Stackoverflow.com/questions/14965542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031842/"
] | With regex
```
import re
ss = '''
>Entry1.1
#size=1688
704 1 1 1 4
979 2 2 2 0
1220 1 1 1 4
1309 1 1 1 4
1316 1 1 1 4
1372 1 1 1 4
1374 1 1 1 4
1576 1 1 1 4
>Entry2.1
#size=6251
6110 3 1.5 0 2
6129 2 2 2 2
6136 1 1 1 4
6142 ... | Not entirely sure what you're asking. Does this get you any closer? It will put all your entries as dictionary keys and a list of all its entries. Assuming it is formatted like I believe it is. Does it have duplicate entries? Here's what I've got:
```
entries = {}
key = ''
for entry in open('entries.txt'):
if entr... | 8,604 |
5,086,419 | I wrote the following script in python to convert datetime from any given timezone to EST.
```
from datetime import datetime, timedelta
from pytz import timezone
import pytz
utc = pytz.utc
# Converts char representation of int to numeric representation '121'->121, '-1729'->-1729
def toInt(ch):
ret = 0 ... | 2011/02/23 | [
"https://Stackoverflow.com/questions/5086419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629424/"
] | Firstly slightly less insane implementation:
```
import datetime
import pytz
EST = pytz.timezone('US/Eastern')
def convert2EST(date, time, tzone):
dt = datetime.datetime.strptime(date+time, '%Y%m%d%H:%M:%S')
tz = pytz.timezone(tzone)
dt = tz.localize(dt)
return dt.astimezone(EST)
```
Now, we try to... | Seems like you have answered your own question. If pytz says DST ends on 27 Feb in Brazil, it's wrong. DST in Brazil ends on the [third Sunday of February](http://translate.google.com/translate?js=n&prev=_t&hl=en&ie=UTF-8&layout=2&eotf=1&sl=pt&tl=en&u=http%3A%2F%2Fpcdsh01.on.br%2FDecHV.html), unless that Sunday falls d... | 8,607 |
30,368,275 | I have file test.robot with test cases.
How can i get the list of this test cases without activating the tests, from command line or python? | 2015/05/21 | [
"https://Stackoverflow.com/questions/30368275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923721/"
] | You can check out [testdoc tool](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#test-data-documentation-tool-testdoc). Like explained in the doc, "The created documentation is in HTML format and it includes name, documentation and other metadata of each test suite and test case". | **For v3.2 and up:**
In RobotFramework 3.2 [the parsing APIs have been rewritten](https://github.com/robotframework/robotframework/blob/master/doc/releasenotes/rf-3.2.rst#parsing-apis-have-been-rewritten), so the answer from Bryan Oakley won't work on these versions anymore.
The proper code that is compatible with bo... | 8,608 |
50,254,723 | I updated the python version from 3.6.4 to 3.6.5 today. This is because, in the process of distributing to Heroku, it recommends version 3.6.5. Therefore, the following power shell contents were confirmed.
```
Writing objects: 100% (35/35), 11.68 KiB | 0 bytes/s, done.
Total 35 (delta 3), reused 0 (delta 0)
remote: Co... | 2018/05/09 | [
"https://Stackoverflow.com/questions/50254723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9556991/"
] | Heroku believes that your `runtime.txt` contains some extra characters:
```
ÿþpython-3.6.5
```
This is probably [byte-order mark for a file encoded as UTF-16 in little-endian order](https://en.wikipedia.org/wiki/Byte_order_mark#UTF-16). Make sure you're using a sane encoding for that file (and others). UTF-8 is a go... | You're trying to install `ÿþpython-3.6.5` not `python-3.6.5` as the console output suggests. Remove `ÿþ` and it should work as expected. | 8,610 |
65,030,618 | TLDR
====
One of my models contains data that could either be a charfield, textfield, or boolfield based on a choice made in a separate model that it is connected to through a foreignkey. What's the most efficient way to model this in Django?
My problem
==========
I'm putting together a Django app that outputs a pyt... | 2020/11/27 | [
"https://Stackoverflow.com/questions/65030618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14621609/"
] | If your database supports [jsonfield](https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#jsonfield) and you want to keep it as a single field, you can use it.
If it doesn't, first of all, if I'm not skipping something, you can use both textfield and charfield as textfield instead of separating them. Ot... | I feel that `contenttypes` will be useful for you, and help you to prevent reinventing the wheel:
<https://docs.djangoproject.com/en/3.1/ref/contrib/contenttypes/> | 8,611 |
2,030,970 | I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this:
[](https://i.stack.imgur.com/FUL1M.png)
But I'm looking for something like this:
[]... | 2010/01/08 | [
"https://Stackoverflow.com/questions/2030970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43665/"
] | Numpy has a function called [histogram2d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html), whose docstring also shows you how to visualize it using Matplotlib. Add `interpolation=nearest` to the imshow call to disable the interpolation. | Is `matplotlib.pyplot.hist` what you're looking for?
```
>>> help(matplotlib.pyplot.hist)
Help on function hist in module matplotlib.pyplot:
hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, botto
m=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=Fa
lse, hold=None... | 8,612 |
5,518,927 | I need to crawl a list of several thousand hosts and find at least two files rooted there that are larger than some value, given as an argument. Can any popular (python based?) tool possibly help? | 2011/04/01 | [
"https://Stackoverflow.com/questions/5518927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/649805/"
] | Here is an example of how you can get the filesize of an file on a HTTP server.
```
import urllib2
def sizeofURLResource(url):
"""
Return the size of an resource at 'url' in bytes
"""
info = urllib2.urlopen(url).info()
return info.getheaders("Content-Length")[0]
```
There is also an library for ... | Here is how I did it. See the code below.
```
import urllib2
url = 'http://www.ueseo.org'
r = urllib2.urlopen(url)
print len(r.read())
``` | 8,621 |
57,915,312 | I am not sure how exactly to ask this question so please forgive my ignorance.
I am running a function from many files. And after importing df I get the outcome into a csv file.
```
df=pd.read_csv("C:\Users\filename.csv ")
years = 5
days = 365
out_put, productivity= timeresult.input_data.outbuild(df, year, days)
... | 2019/09/12 | [
"https://Stackoverflow.com/questions/57915312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12016027/"
] | If I understand your problem correctly, this code is for you:
```
years = 5
days = 365
filelist = ["C:\Users\jan.csv", "C:\Users\feb.csv", "C:\Users\mar.csv"]
for filepath in filelist:
df = pd.read_csv(filepath)
out_put, productivity= timeresult.input_data.outbuild(df, year, days)
df.index.name = filepat... | You were so close, you used the location instead of the file. Use this code:
```
filelist=["C:\Users\jan.csv", "C:\Users\feb.csv", "C:\Users\mar.csv"]
for location in filelist:
df = pd.read_csv(location)
out_put, productivity= timeresult.input_data.outbuild(df, year, days)
filelist.append(productivity)
``... | 8,622 |
56,438,069 | I have images in a sub-folder. Let's the folder `images`
I have a python program which will take image arguments from the folder one by one, the images are named in sequential order (1.jpg , 2.jpg, 3.jpg and so on).
The call to the program is : `python prog.py 1.jpg`
What will be a shell script to automate this ?
P... | 2019/06/04 | [
"https://Stackoverflow.com/questions/56438069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6916919/"
] | Try this from the folder that contains images/:
`for i in images/*.jpg; do
python prog.py $i
done` | ```
cd IMG_DIR
for item in [0-9]*.jpg
do
python prog.py $item
echo "Item processed : $item"
done
```
You can also pass image dir as a shellscript argument | 8,624 |
37,023,460 | I'm transitioning from discretization of a continuous state space to function approximation. My action and state space(3D) are both continuous. My problem suffers majorly from errors due to aliasing and nearly no convergene after training for a long time. Also I just cannot figure out how to choose the right step size ... | 2016/05/04 | [
"https://Stackoverflow.com/questions/37023460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4284161/"
] | As the Simon's comment describes, a key difference between a highly discretized state space and a function approximator using tile coding, it's the hability of tile coding to generalize the values learned from one state to other similar states (i.e., tiles can overlap). In the case of a highly discretized state space, ... | Adding to Pablo's answer -
Tile coding (as a special case of coarse coding) can be compared to simple state aggregation. A simple state aggregation is, for example, a grid. Tile coding would be a stack of grids on top of each other, each shifted a bit from the previous.
The benefits are two fold - it allows you to ha... | 8,626 |
1,480,431 | I need to:
1. Open a video file
2. Iterate over the frames of the file as images
3. Do some analysis in this image frame of the video
4. Draw in this image of the video
5. Create a new video with these changes
OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst?
Thank you... | 2009/09/26 | [
"https://Stackoverflow.com/questions/1480431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179372/"
] | Do you mean opencv can't connect to your webcam or can't read video files recorded by it?
Have you tried saving the video in an other format?
OpenCV is probably the best supported python image processing tool | Just build a C/C++ wrapper for your webcam and then use SWIG or SIP to access these functions from Python. Then use OpenCV in Python that's the best open sourced computer vision library in the wild.
If you worry for performance and you work under Linux, you could download free versions of Intel Performance Primitives ... | 8,627 |
8,099,925 | I want to check what is the password I stored in the DB for the user named as 'user'.
Here is what I have done.
```
user@ubuntu:~/Documents/Django/django_bookmarks$ python manage.py shell
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more... | 2011/11/11 | [
"https://Stackoverflow.com/questions/8099925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391104/"
] | You can check the user's password with `check_password`: <https://docs.djangoproject.com/en/1.3/topics/auth/#django.contrib.auth.models.User.check_password>
```
from django.contrib.auth.models import User
user = User.objects.get(id=1)
user.check_password('password') # Returns True or False
``` | django has been hashed your passwd, this is a function that only works in a way.
You can try to search the sha1 on a [hash database](http://www.hash-database.net/), but they are not guaranty to found it.
You should search for 'f92c73726c0bd5d4821013ad4161578a2114090f'. Hash function is sha1 and key used to hash is '6... | 8,632 |
35,104,897 | First of all a disclaimer: I am using python and anaconda and jupyter all for the first time, so it might be something basic.
I pasted the following code into a new Jupyter note from this url:
<https://github.com/t0pep0/btc-e.api.python/blob/master/btceapi.py>
After filling in my own API and secret API key, I tried to... | 2016/01/30 | [
"https://Stackoverflow.com/questions/35104897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3022427/"
] | `getInfo` is a class method. So you need to instanciate an `api` object before calling it. You could try something like this.
```
myApi = api()
myApi.getInfo()
``` | Some general comments, as Hakens answer is your problem.
Don't copy this script into a cell in the notebook like this (I believe this is what you are doing) You can either manually install to site packages (there doesn't appear to be a setup script for this module), or have the file in the same directory as the notebo... | 8,635 |
17,417,918 | What's the most efficient way to get the integer part and fractional part of a python (python 3) `Decimal`?
This is what I have right now:
```
from decimal import *
>>> divmod(Decimal('1.0000000000000003')*7,Decimal(1))
(Decimal('7'), Decimal('2.1E-15'))
```
Any suggestions are welcome. | 2013/07/02 | [
"https://Stackoverflow.com/questions/17417918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1115577/"
] | You can use the `Window > Reset Windows` menu item. This will reset the IDE's GUI back to the default state. | Use the `Help>About` menu to find the `User Directory`. Then navigate to it and delete directory `config>Windows2Local`. Restart the IDE and you will have the default windows settings. (The deleted dir will be recreated by netbeans) | 8,636 |
28,029,672 | I want to be able to create a JSON object so that I can access it like this.
```
education.schools.UNCC.graduation
```
Currently, my JSON is like this:
```
var education = {
"schools": [
"UNCC": {
"graduation": 2015,
"city": "Charlotte, NC",
"major": ["CS", "Span... | 2015/01/19 | [
"https://Stackoverflow.com/questions/28029672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3558010/"
] | Objects have named keys. Arrays are a list of members.
Replace the value of `"schools"` with an object. Change `[]` to `{}`. | This is your JSON corrected.
Your JSON is invalid.
```
{
"schools": [
{
"UNCC": {
"graduation": "2015",
"city": [
"CS",
"Spanish"
],
"major": [
"CS",
... | 8,637 |
1,809,874 | I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! `field.field.widget.__class__.__name__`
Unfortunately, you're... | 2009/11/27 | [
"https://Stackoverflow.com/questions/1809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] | Following the answer from Oli and rinti: I used this one and I think it is a bit simpler:
template code: `{{ field|fieldtype }}`
filter code:
```
from django import template
register = template.Library()
@register.filter('fieldtype')
def fieldtype(field):
return field.field.widget.__class__.__name__
``` | You can make every view that manages forms inherit from a custom generic view where you load into the context the metadata that you need in the templates. The generic form view should include something like this:
```
class CustomUpdateView(UpdateView):
...
def get_context_data(self, **kwargs):
context =... | 8,638 |
51,804,600 | I am a little confused about a piece of python code in using dict:
```
>>> S = "ababcbacadefegdehijhklij"
>>> lindex = {c: i for i, c in enumerate(S)}
>>> lindex
{'a': 8, 'c': 7, 'b': 5, 'e': 15, 'd': 14, 'g': 13, 'f': 11, 'i': 22, 'h': 19, 'k': 20, 'j': 23, 'l': 21}
```
How to understand it the "{c: i for i, c in e... | 2018/08/11 | [
"https://Stackoverflow.com/questions/51804600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6654375/"
] | First question
--------------
Polymorphism can be achieved in Java in two ways:
* Through *class inheritance*: `class A extends B`
* Through *interface implementation*: `class A implements C`.
In the later case, to properly implement A's behaviour, it can be done though *composition*, making A delegate over some oth... | There is book answer, if one remember about all the firemans are fireman but some are drivers, chiefs etc. There you need polymorphism. There is things you can do with classes and it's a general idea in OOP as language constraints. Overriding is just what you can do with classes. Also permissions and local and/or globa... | 8,648 |
63,592,741 | When trying to update a dictionary with a tuple, I encountered the error:
`>>> dict1.update(("stat",10))`
`ValueError: dictionary update sequence element #0 has length 4; 2 is required`
When in reality this shouldn't be happening. From the python docs,
>
> update() accepts either another dictionary object or an it... | 2020/08/26 | [
"https://Stackoverflow.com/questions/63592741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14168419/"
] | The documentation said you need an ***iterable*** of key value pairs. A single tuple is not an iterable of key value pairs, either a list or tuple of tuples will do.
```py
dict1.update([("stat", 10)])
``` | The documentation says "or an iterable of key/value pairs (as tuples or other iterables of length two)".
Therefore you need to pass it a tuple of tuples that have length 2
Try this:
```
dict1.update((("stat",10),))
```
Or you can pass multiple key/value pairs as followings:
```
dict1.update((("stat",10), ('foo', ... | 8,651 |
4,701,383 | what i'm trying to do is write a quadratic equation solver but when the solution should be `-1`, as in `quadratic(2, 4, 2)` it returns `1`
what am i doing wrong?
```
#!/usr/bin/python
import math
def quadratic(a, b, c):
#a = raw_input("What\'s your `a` value?\t")
#b = raw_input("What\'s your `b` valu... | 2011/01/15 | [
"https://Stackoverflow.com/questions/4701383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/569183/"
] | Unless the formula has changed since I went to school (one can never be too sure), it's `(-b +- sqrt(b^2-4ac)) / 2a`, you have `b` in your code.
[edit] May I suggest a refactor?
```
def quadratic(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant < 0:
return []
elif discriminant == 0:
retur... | The solution to the quadratic is
```
x = (-b +/- sqrt(b^2 - 4ac))/2a
```
but what you have coded up is
```
x = (b +/- sqrt(b^2 - 4ac))/2a
```
So that's why you get the sign error. | 8,653 |
70,088,798 | I am making a python PyQt5 CSV comparison tool project and the user can add conditions for querying the pandas dataframe one by one before they are executed.
At the moment I have a nested list of conditions with each element containing the field, operation (==,!=,>,<), and value for comparison as strings. With just on... | 2021/11/23 | [
"https://Stackoverflow.com/questions/70088798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13696214/"
] | Would this work?
```
conds = [
f'{f} {o} {v}' for f, o, v in zip(field, operation, value)
]
data.query(' and '.join(conds))
``` | **Warning**: Not tested, more like a comment but put here for proper format:
`data.query` returns a dataframe, you can't just do `dataframe1 & dataframe2`. You would do something like
```
data.query(' AND '.join(['{} {} {}'.format(f, o, v)
for f, o, v in zip(fields, operations, values)
... | 8,659 |
26,785,812 | I need to do some intense numerical computations and fortunately python offers very simple ways to implement parallelisations. However, the results I got were totally weird and after some trial'n error I stumbled upon the problem.
The following code simply calculates the mean of a random sample of numbers but illustr... | 2014/11/06 | [
"https://Stackoverflow.com/questions/26785812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4223923/"
] | When you use `multiprocessing`, you're talking about distinct processes. Distinct processes means distinct Python interpreters. Distinct interpreters means distinct random states. If you aren't seeding the random number generator uniquely on each process, then you're going to get the same starting random state from eac... | The answer was to put a new random seed into each process. Changing the function to
```
def get_random(seed):
np.random.seed()
dummy = random(1000) * seed
return np.mean(dummy)
```
gives the wanted results. | 8,660 |
72,468,946 | I'm migrating from `setup.py` to `pyproject.toml`. The commands to install my package appear to be the same, but I can't find what the `pyproject.toml` command for cleaning up build artifacts is. What is the equivalent to `python setup.py clean --all`? | 2022/06/01 | [
"https://Stackoverflow.com/questions/72468946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7059681/"
] | The distutils command [clean](https://docs.python.org/3/distutils/apiref.html#module-distutils.command.clean) is not needed for a `pyproject.toml` based build. Modern tools invoking [PEP517](https://peps.python.org/pep-0517/)/[PEP518](https://peps.python.org/pep-0518/) hooks, such as [build](https://pypi.org/project/bu... | I ran into this same issue when I was migrating. What wim answered seems to be mostly true. If you do as the setuptools documentation says and use `python -m build` then the `build` directory will not be created, but a `dist` will. However if you do `pip install .` a `build` directory will be left behind even if you ar... | 8,661 |
11,023,990 | I would like to use Python to run a macro contained in MacroBook.xlsm on a worksheet in Data.csv.
Normally in excel, I have both files open and shift focus to the Data.csv file and run the macro from MacroBook. The python script downloads the Data.csv file daily, so I can't put the macro in that file.
Here's my code:... | 2012/06/13 | [
"https://Stackoverflow.com/questions/11023990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1137778/"
] | Just return an empty enumerable in the base method.
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
return Enumerable.Empty<Uri>();
}
```
Or if you're targeting a version of the .NET framework < 3.5 return an empty List. | Built in arrays support IEnumerable so you can use:
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
return new Uri[0];
}
``` | 8,662 |
52,377,332 | [This](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-sdk-python.html) page shows how to send an email using SES. The example works by reading the credentials from `~/.aws/credentials`, which are the root (yet "shared"??) credentials.
The documentation advises in various places against using the root... | 2018/09/18 | [
"https://Stackoverflow.com/questions/52377332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/704972/"
] | Here you go. There were a few problems.
1) When you return a value from a function, you need to assign it to a variable so you can pass it into the next function.
2) String literals like the letter grade "F" need to be inside single or double quote marks.
```
def main():
student_name = input('Please enter your f... | Make sure you understand some Python concepts such as the scope of variables, return statements and function arguments. In your case, for instance, `score1` ... `score5` inside `askForScore` are not "readable" by `calc_average`. In fact, `calc_average` returns the values you need and those values need to be passed to t... | 8,667 |
21,072,841 | I am testing some python functionalities as web server. Typed :
```
$ python -m SimpleHTTPServer 8080
```
...and setup port forwarding on router to this 8080. I can access via web with <http://my.ip.adr.ess:8080/>, whereas my.ip.adr.ess stands for my IP adress.
When I started my xampp server it is accessible with ... | 2014/01/12 | [
"https://Stackoverflow.com/questions/21072841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/891304/"
] | It means that xampp is running on port 80 which is default for http://. You need to run SimpleHTTPServer on that port too. [More info about running SimpleHTTPServer on port 80](https://unix.stackexchange.com/questions/24598/how-can-i-start-the-python-simplehttpserver-on-port-80). | Specify the port as `80` (default port for HTTP protocol).
```
python -m SimpleHTTPServer 80
```
You may need superuser permission in Unix to bind port 80 (under 1024).
```
sudo python -m SimpleHTTPServer 80
``` | 8,668 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.