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 |
|---|---|---|---|---|---|---|
29,648,412 | I have a Python 3 installation of Anaconda and want to be able to switch quickly between python2 and 3 kernels. This is on OSX.
My steps so far involved:
```
conda create -p ~/anaconda/envs/python2 python=2.7
source activate python2
conda install ipython
ipython kernelspec install-self
source deactivate
```
After t... | 2015/04/15 | [
"https://Stackoverflow.com/questions/29648412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1217949/"
] | Apparently IPython expects explicit pathnames, so no '~' instead of the home directory. It worked after changing the kernel.json to:
```
{
"display_name": "Python 2",
"language": "python",
"argv": [
"/Users/sonium/anaconda/envs/python2/bin/python2.7",
"-m",
"IPython.kernel",
"-f",
"{connection_file}"
],
... | I install the Anaconda 3 in Win10. I am now focus on python 3, but I have lot projects written in python 2. If I want check them in juypter in python environment it's will failed, and shows "kernel error". The solution is almost like above, but something different.
The path to find those two json files is :
`C:\Progra... | 13,545 |
16,033,348 | I have a list of items that relate to each other, I know they end up building a graph but the data is not sorted in any way.
```
PMO-100 -> SA-300
SA-100 -> SA-300
SA-100 -> SA-200
PMO-100 -> SA-100
```
In python examples for graphViz api I realize that you can pretty much generate a graph if you know it's top node ... | 2013/04/16 | [
"https://Stackoverflow.com/questions/16033348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/220255/"
] | There is no need to identify a top node for graphviz. Just add all Nodes and edges and let it do the rest. For example:
```
import pydot
graph = pydot.Dot('graphname', graph_type='digraph')
pmo100 = pydot.Node("PMO-100")
sa300 = pydot.Node("SA-300")
sa100 = pydot.Node("SA-100")
sa200 = pydot.Node("SA-200")
graph.add_... | Try out [pygraph](http://github.com/iamaziz/pygraph) package, it produces a directed graph based on relation statements (data). No matter if the data are sorted or not.
So (as in your case) if we have the following data (in a triple relation), it is easy to produce the corresponding graph:
### First way
```
s1 = "PM... | 13,546 |
50,860,578 | I have the following situation:
```
for x1 in range(x1, x2):
for x2 in range(x3, x4):
for x3 ...
...
f(x1, x2, x3, ...)
```
How to convert this to a mechanism in which I only tell python to make *n* nested loops where the variable name is x1, x2, x3, x4, ...? I don't want to w... | 2018/06/14 | [
"https://Stackoverflow.com/questions/50860578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8472333/"
] | What you want to do is iterate over a product. Use [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product).
```
import itertools
ranges = [range(x1, x2), range(x3, x4), ...]
for xs in itertools.product(*ranges):
f(*xs)
```
Example
-------
```
import itertools
ranges = [range... | Recommended: itertools
----------------------
[`itertools`](https://docs.python.org/3/library/itertools.html) is an awesome package for everything related to iteration:
```
from itertools import product
x1 = 3; x2 = 4
x3 = 0; x4 = 2
x5 = 42; x6 = 42
for x, y, z in product(range(x1, x2), range(x3, x4), range(x4, x5))... | 13,548 |
55,138,466 | I'm scraping a [website](https://www.cofidis.es/es/creditos-prestamos/financiacion-coche.html). I'm trying to click on a link under `<li>` but it throws `NoSuchElementException` exception.
And the links I want to click:
[](https://i.stack.imgur.com/2... | 2019/03/13 | [
"https://Stackoverflow.com/questions/55138466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11155464/"
] | onchange of the radio button select the input using document.querySelector and using setAttribute set the required attribute to the elements
```js
function a()
{
document.querySelector('.one').setAttribute('required','required');
document.querySelector('.five').setAttribute('required','required');
}
```
```html
... | You can add class to the input elements by matching the id of the radio button. Then on clicking on the button add the *required* attribute with that class name:
```js
var radio = [].slice.call(document.querySelectorAll('[name=customer]'));
radio.forEach(function(r){
r.addEventListener('click', function(){
va... | 13,554 |
69,086,563 | i am trying to read CT scan Dicom file using pydicom python library but i just can't get rid of this below error even when i install gdcm and pylibjpeg
```
RuntimeError: The following handlers are available to decode the pixel data however they are missing required dependencies: GDCM (req. ), pylibjpeg (req. )
```
H... | 2021/09/07 | [
"https://Stackoverflow.com/questions/69086563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15054164/"
] | Try running the following:
```
!pip install pylibjpeg
!pip install gdcm
``` | In a [similar problem](https://stackoverflow.com/questions/62159709/pydicom-read-file-is-only-working-with-some-dicom-images) as yours, we could see that the problem persists at the *Pixel Data* level. You need to [install one or more optional libraries](https://pydicom.github.io/pydicom/stable/tutorials/installation.h... | 13,559 |
52,478,863 | I have an input file *div.txt* that looks like this:
```
<div>a</div>b<div>c</div>
<div>d</div>
```
Now I want to pick all the *div* tags and the text between them using *sed*:
```
sed -n 's:.*\(<div>.*</div>\).*:\1:p' < div.txt
```
The result I get:
```
<div>c</div>
<div>d</div>
```
What I really want:
```
<... | 2018/09/24 | [
"https://Stackoverflow.com/questions/52478863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5459536/"
] | This might work for you (GNU sed):
```
sed 's/\(<\/div>\)[^<]*/\1\n/;/^</P;D' file
```
Replace a `</div>` followed by zero or more characters that are not a `<` by itself and a newline. Print only lines that begin with a `<`. | Sed is not the right tool to handle HTML.
But if you really insist, and you know your input will always have properly closed pairs of div tags, you can just replace everything that's not inside a div by a newline:
```
sed 's=</div>.*<div>=</div>\n<div>='
``` | 13,560 |
62,026,087 | I have a simple Glue pythonshell job and for testing purpose I just have print("Hello World") in it.
I have given it the required AWSGlueServiceRole. When I am trying to run the job it throws the following error:
```
Traceback (most recent call last):
File "/tmp/runscript.py", line 114, in <module>
temp_file_pa... | 2020/05/26 | [
"https://Stackoverflow.com/questions/62026087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10133469/"
] | In Glue you need to attach S3 policies to the Amazon Glue Role that you are using to run the job. When you define the job you select the role. In this example it is AWSGlueServiceRole-S3IAMRole. That does not have S3 access until you assign it.
[](htt... | You need to have the permissions to the bucket **and** the script resource.
Try adding the following inline policy:
```
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:*"
],
"Resource": "arn:aws:s3:::myBucket/*",
"Effect": "Al... | 13,561 |
69,455,665 | In python, if class C inherits from two other classes C(A,B), and A and B have methods with identical names but different return values, which value will that method return on C? | 2021/10/05 | [
"https://Stackoverflow.com/questions/69455665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | "Inherits two methods" isn't quite accurate. What happens is that `C` has a *method resolution order* (MRO), which is the list `[C, A, B, object]`. If you attempt to access a method that `C` does not define or override, the MRO determines which class will be checked next. If the desired method is defined in `A`, it sha... | MRO order will be followed now, if you inherit A and B in C, then preference order goes from left to right, so, A will be prefered and method of A will be called instead of B | 13,562 |
28,747,456 | I am trying to install a python package using pip in linux mint but keep getting this error message. Anyone know how to fix this?
```
alex@alex-Satellite-C660D ~ $ pip install django-registration-redux
Downloading/unpacking django-registration-redux
Downloading django-registration-redux-1.1.tar.gz (63kB): 63kB downl... | 2015/02/26 | [
"https://Stackoverflow.com/questions/28747456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3541209/"
] | Autoprefixer doesn't run on it's own. It needs to be run as part of postcss-cli like so:
`postcss --use autoprefixer *.css -d build/`
(from <https://github.com/postcss/autoprefixer#cli>)
Save-dev postcss-cli and then reformat your build:css to match
`postcss --use autoprefixer -b 'last 2 versions' <assets/styles... | Installation: `npm install -g postcss-cli autoprefixer`
Usage (order matters!): `postcss main.css -u autoprefixer -d dist/` | 13,563 |
11,729,662 | ```
print'Personal information, journal and more to come'
x = raw_input()
if x ==("Personal Information"): # wont print
print' Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN: , SS:'
elif x ==("Journal"): # wont print
read = open('C:\\python\\foo.txt' , 'r')
name = read.readline()
print (name)
```
I star... | 2012/07/30 | [
"https://Stackoverflow.com/questions/11729662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1564130/"
] | >
> when i type either Personal information or journal
>
>
>
Well, yeah. It isn't expecting either of those; your case is wrong.
To perform a case-insensitive comparison, convert both to the same case first.
```
if foo.lower() == bar.lower():
``` | Works for me. Are you writing "Personal Information" with a capital I?
```
print'Personal information, journal and more to come'
x = raw_input()
if x == ("Personal Information"): # wont print
print' Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN: , SS:'
elif x ==("Journal"): # wont print
read = open('C... | 13,566 |
47,705,274 | I am learning bare metal programming in c++ and it often involves setting a portion of a 32 bit hardware register address to some combination.
For example for an IO pin, I can set the 15th to 17th bit in a 32 bit address to `001` to mark the pin as an output pin.
I have seen code that does this and I half understand ... | 2017/12/07 | [
"https://Stackoverflow.com/questions/47705274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1158977/"
] | The 7 (base 10) is chosen as its binary representation is 111 (7 in base 2).
As for why it's bits 8, 9 and 10 set it's because you're reading from the wrong direction. Binary, just as normal base 10, counts right to left.
(I'd left this as a comment but reputation isn't high enough.) | >
> How do I choose the 7
>
>
>
You want to clear three adjacent bits. Three adjacent bits at the bottom of a word is 1+2+4=7.
>
> and how do I choose the number of bits to shift left
>
>
>
You want to clear bits 21-23, not bits 1-3, so you shift left another 20.
Both your examples are wrong. To clear 15-1... | 13,568 |
32,625,597 | I am having trouble getting this python code to work right. it is a code to display pascal's triangle using binomials. I do not know what is wrong. The code looks like this
```
from math import factorial
def binomial (n,k):
if k==0:
return 1
else:
return int((factorial(n)//factorial(k))*factori... | 2015/09/17 | [
"https://Stackoverflow.com/questions/32625597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5345562/"
] | You can use
```
SELECT id, date, product_id, sales FROM sales LIMIT X OFFSET Y;
```
where X is the size of the batch you need and Y is current offset (X times number of current iterations for example) | To expand on akalikin's answer, you can use a stepped iteration to split the query into chunks, and then use LIMIT and OFFSET to execute the query.
```
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT COUNT(*) FROM sales")
for i in range(0,cur.fetchall(),5):
cur2 = con.cursor(mdb.cursors.DictCursor)
... | 13,570 |
35,894,511 | When i run
```
pip install --upgrade pip
```
I get this error message:
```
Collecting pip
Downloading pip-8.1.0-py2.py3-none-any.whl (1.2MB)
100% |████████████████████████████████| 1.2MB 371kB/s
Installing collected packages: pip
Found existing installation: pip 8.0.2
Uninstalling pip-... | 2016/03/09 | [
"https://Stackoverflow.com/questions/35894511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5827690/"
] | A permission issue means your user privileges don't allow you to write on the desired folder(`/Library/Python/2.7/site-packages/pip/`). There's basically two things you can do:
1. run pip as sudo:
```
sudo pip install --upgrade pip
```
2. Configure pip to install only for the current user, as covered [here](https://... | From administrator mode command prompt, you can run the following command, that should fix the issue:
```
python -m ensurepip --user
```
Replace python3 if your version supports that. | 13,576 |
10,838,596 | The below piece of code is giving me a error for some reason, Can someone tell me what would be the problem..
Basically, I create 2 classes Point & Circle..THe circle is trying to inherit the Point class.
```
Code:
class Point():
x = 0.0
y = 0.0
def __init__(self, x, y):
self.x = x
self... | 2012/05/31 | [
"https://Stackoverflow.com/questions/10838596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | It looks like you already may have fixed the original error, which was caused by `super().__init__(x,y)` as the error message indicates, although your fix was slightly incorrect, instead of `super(Point, self)` from the `Circle` class you should use `super(Circle, self)`.
Note that there is another place that calls `s... | `super(..)` takes only new-style classes. To fix it, extend Point class from `object`. Like this:
```
class Point(object):
```
Also the correct way of using super(..) is like:
```
super(Circle,self).__init__(x,y)
``` | 13,582 |
71,391,688 | pip install pygame==2.0.0.dev10 this package not installed in python 3.8.2 version.so when I run the gaming project so that time this error showing.instead of this I am install pip install pygame==2.0.0.dev12,this package is install but same error is showing.
so can anyone give me a solution | 2022/03/08 | [
"https://Stackoverflow.com/questions/71391688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18405878/"
] | Redirect in htaccess does not matter if it is a pdf file or anything else just a **valid link**.
This is an example of a 301 redirect code to the link you want
`RedirectMatch 301 /subpage/ <https://www.mywebsite.com/upload/files/file.pdf>` | To target an HTML link to a specific page in a PDF file, add #page=[page number] to the end of the link's URL.
For example, this HTML tag opens page 4 of a PDF file named myfile.pdf:
```
<A HREF="http://www.example.com/myfile.pdf#page=4">
```
---
And If you want to redirect a single page to another you just need t... | 13,585 |
33,813,848 | I only started using python, so i don't know it very well.Can you help how to say that the number should not be divisible by another integer given by me ? For example, if a is not divisible by 2. | 2015/11/19 | [
"https://Stackoverflow.com/questions/33813848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5583129/"
] | Check out the % operator.
```
if x%2 == 0:
# x is divisible by 2
print x
``` | "a is not divisible by 2": `(a % 2) != 0` | 13,588 |
49,626,707 | ```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
drive... | 2018/04/03 | [
"https://Stackoverflow.com/questions/49626707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9575127/"
] | As you have created an instance of `ChromeOptions()` as **chrome\_options** you need to pass it as an argument to put the configurations in effect while invoking `webdriver.Chrome()` as follows :
```
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
chrome_options = webd... | ```
driver.switch_to_alert().dismiss()
driver.switch_to_alert().accept()
```
These can be used dismiss-right and accept-left | 13,590 |
22,418,816 | I'm trying to use multiprocessing to get a handle on my memory issues, however I can't get a function to pickle, and I have no idea why. My main code starts with
```
def main():
print "starting main"
q = Queue()
p = Process(target=file_unpacking,args=("hellow world",q))
p.start()
p.join()
if p... | 2014/03/15 | [
"https://Stackoverflow.com/questions/22418816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2352742/"
] | Pickling a function is a very very relevant thing to do if you want to do any parallel computing. Python's `pickle` and `multiprocessing` are pretty broken for doing parallel computing, so if you aren't adverse to going outside of the standard library, I'd suggest `dill` for serialization, and `pathos.multiprocessing` ... | You can technically pickle a function. But, it's only a name reference that's being saved. When you unpickle, you must set up the environment so that the name reference makes sense to python. Make sure to read [What can be pickled and unpicked](http://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpick... | 13,591 |
38,947,967 | I'm trying to mungle my data from the following data frame to the one following it where the values in column B and C are combined to column names for the values in D grouped by the values in A.
Below is a reproducible example.
```
set.seed(10)
fooDF <- data.frame(A = sample(1:4, 10, replace=TRUE), B = sample(letter... | 2016/08/15 | [
"https://Stackoverflow.com/questions/38947967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3329254/"
] | `my Tuple $t` creates a `$t` variable such that any (re)assignment or (re)binding to it must (re)pass the `Tuple` type check.
`= [1, 2]` assigns a reference to an `Array` object. The `Tuple` type check is applied (and passes).
`$t.append(3)` modifies the contents of the `Array` object held in `$t` but does not reassi... | The type constraint is bound to the scalar container, but the object it contains is just a plain old array - and an array's `append` method is unaware you want it to trigger a type check.
If you want to explicitly trigger the check again, you could do a reassignment like `$t = $t`. | 13,592 |
64,318,676 | I am trying to scrape all email addresses from this index page - <http://www.uschess.org/assets/msa_joomla/AffiliateSearch/clubresultsnew.php?st=AL>
I modified a python script to define the string, parse content with BS4 and save each unique address to an xls file:
```
import requests
from bs4 import BeautifulSoup
im... | 2020/10/12 | [
"https://Stackoverflow.com/questions/64318676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5705012/"
] | Your insert has 2 issues. Assuming the string '1,2,3,4' is the result of your decode (not at all clear on that) there is no new line ( chr(10)||chr(13) ) data in it. As a result there is only 1 value to be extracted. Perhaps the decoded result is actually a CSV. I proceed with that assumption.
Your second issue is ... | ```
PROCEDURE LOAD_SPM_ITEM_SYNC(P_ENCODED_STRING IN CLOB,truncateflag in varchar2) IS
r_records varchar2(3000);
BEGIN
declare
cursor c_records IS
select regexp_substr(utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(P_ENCODED_STRING))), '[^'||CHR(10)||CHR(13)||']+', 1, level)
from dual
connect b... | 13,595 |
50,330,893 | I use python-telegram-bot and I don't understand how forward a message from the user to a telegram group, I have something like this:
```
def feed(bot, update):
bot.send_message(chat_id=update.message.chat_id, text="reply this message"
bot.forward_message(chat_id="telegram group", from_chat_id="username bot", mess... | 2018/05/14 | [
"https://Stackoverflow.com/questions/50330893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9788313/"
] | From [documentation](https://python-telegram-bot.readthedocs.io/en/stable/telegram.bot.html#telegram.Bot.forward_message):
**chat\_id** - Unique identifier for the target chat ...
**from\_chat\_id** - Unique identifier for the ***chat where the original message was sent*** ...
**message\_id** - Message identif... | Its easy with `Telethon`.
You need the `chat_id`, `from_chat_id`.
You can add a bot and you will need the token. | 13,596 |
25,044,403 | I've had success with `mvn deploy` for about a week now, and suddenly it's not working. It used to prompt me for my passphrase (in a dialog window--I'm using Kleopatra on Windows 7, 32bit), but it's not any more. The only thing that's changed in the POM is the project's version number.
There are two random outcomes, b... | 2014/07/30 | [
"https://Stackoverflow.com/questions/25044403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2736496/"
] | Set your gpg.passphrase in your ~/.m2/settings.xml like so:
```
<server>
<id>gpg.passphrase</id>
<passphrase>clear or encrypted text</passphrase>
</server>
```
Or pass it as a parameter when calling maven:
```
mvn -Dgpg.passphrase=yourpassphrase deploy
``` | I uninstalled gpg4win (of which Kleopatra is part), restarted my computer, and re-installed gpg4win, and the passphrase issue went away. The dialog popped up and prompted me for my password.
```
R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava>mvn deploy
[INFO] Scanning for projects...
[INFO] ... | 13,597 |
62,327,106 | I am trying to make a class consisting of several methods and I want to use return values from methods as parameters for other methods within the same class. Is it possible to do so?
```
class Result_analysis():
def __init__(self, confidence_interval):
self.confidence_interval = confidence_interval
d... | 2020/06/11 | [
"https://Stackoverflow.com/questions/62327106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13628325/"
] | You didn't include all your code, and you should have updated the question with the traceback, but did you mean this:
```
n = ... # I don't know what n is.
d = Result_analysis(0.95)
print(d.extract_arrays(d.read_file(n))
``` | If you don't want to call the function read\_file explicitly from outside class. then you can convert the program as:
```
class Result_analysis():
def __init__(self, confidence_interval):
self.confidence_interval = confidence_interval
def read_file(self, file_number):
dict_ = {1: 'Ten_Runs_avg... | 13,599 |
620,954 | Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) . | 2009/03/07 | [
"https://Stackoverflow.com/questions/620954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31610/"
] | Other than pygments? <http://pygments.org/> | If you're using gtk+, there's a binding of gtksourceview for Python in [gnome-python-extras](http://ftp.gnome.org/pub/GNOME/sources/gnome-python-extras/2.25/). It seems to work well in my experience. The downside: the documentation is less than perfect.
There's also a binding of [QScintilla](http://www.riverbankcomput... | 13,600 |
60,396,222 | I know there are questions like that but I still wanted to ask this because I couldn't solve, so there is my code:
```
#! python3
import os
my_path = 'E:\\Movies'
for folder in os.listdir(my_path):
size = os.path.getsize(folder)
print(f'size of the {folder} is: {size} ')
```
And I got this error:
```
Tr... | 2020/02/25 | [
"https://Stackoverflow.com/questions/60396222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10577122/"
] | Temporary tables are created using the server's collation by default. It looks like your server's collation is `SQL_Latin1_General_CP1_CI_AS` and the database's (actually, the column's) `Hebrew_CI_AS` or vice versa.
You can overcome this by using `collate database_default` in the temporary table's column definitions, ... | In your temp table definition #x,add COLLATE DATABASE\_DEFAULT to the String columns, like
```
custName nvarchar(xx) COLLATE DATABASE_DEFAULT NOT NULL
``` | 13,606 |
29,723,590 | I'm trying to set up Python to run on my local apache server on a mac.
On `httpd.conf`, I've
```
<VirtualHost *:80>
DocumentRoot "/Users/ptamzz/Sites/python/sandbox.ptamzz.com"
<Directory "/Users/pritams/Sites/python/sandbox.ptamzz.com">
Options Indexes FollowSymLinks MultiViews ExecCGI
AddHa... | 2015/04/18 | [
"https://Stackoverflow.com/questions/29723590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383393/"
] | **Executing python in Apache ( cgi )**
System : OSX yosmite 10.10.3 , Default apache
**uncommented in http config**
```
LoadModule cgi_module libexec/apache2/mod_cgi.so
```
**virtual hosts entry**
```
<VirtualHost *:80>
# Hook virtual host domain name into physical location.
ServerName python.localhost
... | For later Versions of Apache (2.4) the answer of Sojan V Jose is mostly still applying, except that I got an authorization failure, that can be resolved by replacing:
```
Order allow,deny
Allow from all
```
with:
```
Require all granted
``` | 13,607 |
70,125,767 | I am a student, new to python. I am trying to code a program that will tell if a user input number is fibonacci or not.
```
num=int(input("Enter the number you want to check\n"))
temp=1
k=0
a=0
summ=0
while summ<=num:
summ=temp+k
temp=summ
k=temp
if summ==num:
a=a+1
print("Yes. {} is a ... | 2021/11/26 | [
"https://Stackoverflow.com/questions/70125767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17517066/"
] | You don't need quite so many variables. A Fibonacci integer sequence can be generated with the single assignment
```
a, b = b, a + b
# Short for
# temp = a
# a = b
# b = temp + b
```
Repeated applications sets `a` to the numbers in the pattern in sequence. The choice of initial values for `a` and `b` d... | I'd suggest something like this:
```
fib_terms = [0, 1] # first two fibonacci terms
user_input= int(input('Enter the number you want to check\n'))
# Add new fibonacci terms until the user_input is reached
while fib_terms[-1] <= user_input:
fib_terms.append(fib_terms[-1] + fib_terms[-2])
if user_input in fib_te... | 13,608 |
46,035,788 | I'm trying to use python to search through a directory of files and open every single file in search of a string.
We're talking about less than 1000 files with 1, 2, 3 line each, so opening them all only takes a few seconds.
Well, I think that I've made it, but there's a problem: the string that I'm search for is "**... | 2017/09/04 | [
"https://Stackoverflow.com/questions/46035788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6834568/"
] | Because the start of your pattern match the empty string:
```
/|google...
```
That means: nothing OR google ... | This pattern is invalid:
```
|google|robot|bot|spider|crawler|curl|Facebot|facebook|archiver|^$
^
|
+--- this character (an alternator) effectively renders the regex useless
```
This means that the regex could in theory match anything because the left part is empty.
Moreover, `^$` on the right of the last alternato... | 13,612 |
40,981,908 | I'm new to AWS Lambda and pretty new to Python.
I wanted to write a python lambda that uses the AWS API.
boto is the most popular python module to do this so I wanted to include it.
Looking at examples online I put `import boto3` at the top of my Lambda and it just worked- I was able to use boto in my Lambda.
How ... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1028270/"
] | [The documentation](http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html) seems to suggest `boto3` is provided by default on AWS Lambda:
>
> AWS Lambda includes the AWS SDK for Python (Boto 3), so you don't need to include it in your deployment package. However, if you want ... | AWS Lambda includes the AWS SDK for Python (Boto 3), so you don't need to include it in your deployment package.
This link will give you a little more in-depth info on Lambda environment
<https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/>
And this too
<https://alestic.com/2014/12/aws-lambda-persistence... | 13,613 |
26,278,386 | I have a list or array (what is the correct term in python?) of objects.
What is the most efficient way to get all objects matching a condition?
I could iterate over the list and check each element, but that doesn't seem very efficient.
```
objects = []
for object in list:
if object.value == "123":
objects.add(... | 2014/10/09 | [
"https://Stackoverflow.com/questions/26278386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1474934/"
] | This is the simplest way:
```
objects = [x for x in someList if x.value == 123]
```
If you're looking for a *faster* solution, you have to tell us more about your objects and how the source list is built. For example, if the property in question is unique among the objects, you can have better performance using `dic... | You can use `filter`
```
objects = filter(lambda i: i.value == '123', l)
```
*Note to self*
Apparently the ["filter vs list comp"](https://stackoverflow.com/questions/3013449/list-filtering-list-comprehension-vs-lambda-filter) debate starts flame wars. | 13,615 |
41,079,379 | I have to program a task in python 3.4 that requires the following:
- The program ask the user to enter a data model that is made by several submodels in a form of string like the following:
```
# the program ask :
please input the submodel1
# user will input:
A = a*x + b*y*exp(3*c/d*x)
# then the program ask :
-> pl... | 2016/12/10 | [
"https://Stackoverflow.com/questions/41079379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4434914/"
] | Invisible reCAPTCHA
===================
Implementing Google's new Invisible reCAPTCHA is very similar to how we add v2 to our site. You may add it as its own container like normal, or the new method of adding it to the form submit button. I hope this guide will help you along the correct path.
Standalone CAPTCHA Cont... | If you're looking for a fully customizable general solution which will even work with multiple forms on the same page, I'll explicitly render the reCaptcha widget by using the **render=explicit** and **onload=aFunctionCallback** parameters.
Here is a simple example:
```html
<!DOCTYPE html>
<html>
<body>
<form act... | 13,616 |
7,378,431 | How to add data to a relationship with multiple foreign keys in Django?
I'm building a simulation written in python and would like to use django's orm to store (intermediate and final) results in a database. Therefore I am not concerned with urls and views.
The problem I am having is the instantiation of an object wi... | 2011/09/11 | [
"https://Stackoverflow.com/questions/7378431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/939186/"
] | Try using [PAM](http://en.wikipedia.org/wiki/Pluggable_Authentication_Modules) via [Python PAM](http://atlee.ca/software/pam/) or similar | That should be possible by having your script read the `/etc/passwd` and `/etc/shadow` files, which contain details about usernames and passwords on a Linux system. Do note that the script will have to have read access to the files, which depending on the situation may or may not be possible.
Here are two good article... | 13,625 |
3,495,290 | relatively long-time PHP user here. I could install XAMPP in my sleep at this point to the point where I can get a PHP script running in the browser at "localhost", but in my searches to find a similar path using Python, I've run out of Googling ideas. I've discovered the mod\_python Apache mod, but then I also discove... | 2010/08/16 | [
"https://Stackoverflow.com/questions/3495290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/385950/"
] | well mod\_python has been retired. So in order to host python apps you want `mod_wsgi`
<http://code.google.com/p/modwsgi/>
But python isn't really like php(as in you mix it with html to get output, if I understand your question correctly). In learning python, using the command line/repl will probably be much more us... | Most Python webframeworks have a built-in minimal development server:
* [Flask](http://flask.pocoo.org/docs/quickstart/)
* [Turbogears](http://turbogears.org/2.0/docs/main/QuickStart.html#run-the-server)
* [Django](http://docs.djangoproject.com/en/dev/ref/django-admin/#runserver-port-or-ipaddr-port)
* [Pylons](http://... | 13,626 |
40,879,188 | np.where lets you pick values to assign for a boolean type query, e.g.
```
test = [0,1,2]
np.where(test==0,'True','False')
print test
['True','False','False']
```
Which is basically an 'if' statement. Is there a pythonic way of having an 'if, else if, else' kind of statement (with different cases) for a numpy array?... | 2016/11/30 | [
"https://Stackoverflow.com/questions/40879188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5531108/"
] | `np.choose` is something of a multielement `where`:
```
In [97]: np.choose([0,1,1,2,0,1],['red','green','blue'])
Out[97]:
array(['red', 'green', 'green', 'blue', 'red', 'green'],
dtype='<U5')
In [113]: np.choose([0,1,2],[0,np.array([1,2,3])[:,None], np.arange(10,13)])
Out[113]:
array([[ 0, 1, 12],
[ 0... | One of the more Pythonic ways to do this would be to use a list comprehension, like this:
```
>>> color = [0,1,2]
>>> ['red' if c == 0 else 'blue' if c == 1 else 'green' for c in color]
['red', 'blue', 'green']
```
It's fairly intuitive if you read it. For a given item in the list `color`, the value in the new list ... | 13,628 |
24,606,931 | I have tried for hours to install `FiPy`
I've installed Pip and many other things to get it to work. Pip successfull installed many of the things I needed but I cannot get it to work for PySparse or FiPy. Why I try, to install PySparse I get an error:
```
$ pip install pysparse
Downloading/unpacking pysparse
Could n... | 2014/07/07 | [
"https://Stackoverflow.com/questions/24606931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3811717/"
] | I've just encountered the same problems you did, and here are my work-arounds:
Pysparse:
pip doesn't find the pysparse distribution in PyPI because it appears to not be a stable version (see e.g. [Could not find a version that satisfies the requirement pytz](https://stackoverflow.com/questions/18230956/could-not-find-... | PySparse is not a strict requirement for FiPy. FiPy needs one of PySparse, Scipy or Trilinos as a linear solver and Scipy is probably the easiest to install. To check that FiPy has access to a linear solver, you can run the tests,
```
$ python -c "import fipy; fipy.test()"
```
It should be evident from the test outp... | 13,631 |
55,016,775 | I need help making a mirrored right triangle like below
```
1
21
321
4321
54321
654321
```
I can print a regular right triangle with the code below
```
print("Pattern A")
for i in range(8):
for j in range(1,i):
print(j, end="")
print("")
```
Which prints
```
1
12
123
1234
12345
1... | 2019/03/06 | [
"https://Stackoverflow.com/questions/55016775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11157933/"
] | Here is one using the new f-string formatting system:
```
def test(x):
s = ""
for i in range(1,x+1):
s = str(i) + s
print(f'{s:>{x}}')
test(6)
``` | Something like this works. I loop over the amount of lines, add the whitespace needed for that line and print the numbers.
```
def test(x):
for i in range(1,x+1):
print((x-i)*(" ") + "".join(str(j+1) for j in range(i)))
test(6)
``` | 13,632 |
44,690,174 | How to convert a column that has been read as a string into a column of arrays?
i.e. convert from below schema
```
scala> test.printSchema
root
|-- a: long (nullable = true)
|-- b: string (nullable = true)
+---+---+
| a| b|
+---+---+
| 1|2,3|
+---+---+
| 2|4,5|
+---+---+
```
To:
```
scala> test1.printSchema... | 2017/06/22 | [
"https://Stackoverflow.com/questions/44690174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4531806/"
] | There are various method,
The best way to do is using `split` function and cast to `array<long>`
```
data.withColumn("b", split(col("b"), ",").cast("array<long>"))
```
You can also create simple udf to convert the values
```
val tolong = udf((value : String) => value.split(",").map(_.toLong))
data.withColumn("ne... | Using a [UDF](https://jaceklaskowski.gitbooks.io/mastering-apache-spark/spark-sql-udfs.html) would give you exact required schema. Like this:
```
val toArray = udf((b: String) => b.split(",").map(_.toLong))
val test1 = test.withColumn("b", toArray(col("b")))
```
It would give you schema as follows:
```
scala> test... | 13,633 |
29,989,024 | Im trying to use a [specific gamma corrected grayscale implementation](http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0029740) - Gleam to convert an images pixels to grayscale. How can i do this manually with PIL python?
```
def tau_gamma_correct(pixel_channel):
pixel_channel = pixel_channel**(1/... | 2015/05/01 | [
"https://Stackoverflow.com/questions/29989024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/688830/"
] | I found that i could just build another image:
```
import sys
import os
import glob
import numpy
from PIL import Image
def tau_gamma_correct(pixel_channel):
pixel_channel = pixel_channel**(1/2.2)
return pixel_channel
#@param: rgb
#@result: returns grayscale value
def gleam(rgb):
#convert rgb tuple to lis... | Seeing the `SystemError: new style getargs format but argument is not a tuple` error it seems that you need to return a tuple, which is represented as :
```
sample_tuple = (1, 2, 3, 4)
```
So we edit the `gleam()` function as:
```
def gleam(rgb):
#convert rgb tuple to list
rgblist = list(rgb)
#gamma cor... | 13,635 |
66,312,791 | i have a python script to download and save a MP3 and i would like to add code to cut out 5 seconds from the beginning of the MP3.
```
def download():
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': 'c:/MP3/%(title)s.%(ext)s',
'cookiefile': 'cookies.txt',
'postprocessors': [{
... | 2021/02/22 | [
"https://Stackoverflow.com/questions/66312791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11675699/"
] | I don't think you can directly limit the width of the `Textfield`, it will take the max width of its parent element.
But you can put it in a parent element with fixable width:
```py
v.Row(
children = [
v.Html(
tag = 'div',
style_ = 'width: 500px',
children = [
... | Here is the best I have so far, based on Christoph's answer:
I added v.Spacer, and converted the second part to a v.Col (might be worth also including the first part to a v.Col ?)
```
import ipyvuetify as v
v.Row(
children = [
v.Html(
tag = 'div',
style_ = 'width: 50px',
... | 13,638 |
44,141,117 | I am trying to print fibonacci series using lists in python.
This is my code
```
f=[1,1]
for i in range(8):
f.append(f[i-1]+f[i-2])
print(f)
```
output is
```
[1, 1, 2, 3, 2, 3, 5, 5, 5, 8]
```
I am not getting the bug here! | 2017/05/23 | [
"https://Stackoverflow.com/questions/44141117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8054946/"
] | ```
f=[1,1]
for i in range(8):
s=len(f)
f.append(f[s-1]+f[s-2]) #sum of last two elements
print(f)
```
or use -1 and -2 as index for two last element. | Script
```
f=[1,1]
for i in range(2,8):
print(i)
f.append(f[i-1]+f[i-2])
print(f)
```
Output
```
2
[1, 1, 2]
3
[1, 1, 2, 3]
4
[1, 1, 2, 3, 5]
5
[1, 1, 2, 3, 5, 8]
6
[1, 1, 2, 3, 5, 8, 13]
7
[1, 1, 2, 3, 5, 8, 13, 21]
```
Issue is `i` starts from 0, `f[-1], f[-2]` returns 0.
start using range from 2 and 8 r... | 13,641 |
21,395,069 | I am running ubuntu 13.10 with the latest pip.
I have a whole set of SSL certs for my corporate proxy installed as per:
<https://askubuntu.com/questions/73287/how-do-i-install-a-root-certificate> now.
Firefox no longer complains about unrecognised certs but I still get:
```
Could not fetch URL http://pypi.python.or... | 2014/01/28 | [
"https://Stackoverflow.com/questions/21395069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1687633/"
] | I guess you would have to use `pip`'s `--cert` option.
```
--cert <path> Path to alternate CA bundle.
```
There's no indication in the documentation that you can use the `cert=` option in the `pip.conf` configuration file. See: <https://pip.pypa.io/en/stable/reference/pip/?highlight=proxy#cmdoption-cer... | try updating your proxy variables as shown here for http\_proxy and https\_proxy
<https://askubuntu.com/questions/228530/updating-http-proxy-environment-variable>
you should need the cert (or declared global cert as you have it above) as well as the proxy. the alternative to setting the variables would be to use it f... | 13,651 |
70,622,248 | My question is an extension to this:
[Python Accessing Values in A List of Dictionaries](https://stackoverflow.com/questions/17117912/python-accessing-values-in-a-list-of-dictionaries)
I want to only return values from dictionaries if another given value exists in that dictionary.
In the case of the example given in... | 2022/01/07 | [
"https://Stackoverflow.com/questions/70622248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3465940/"
] | The reason for your error is that the conditional operator (`c ? t : f`) takes precedence over the lambda declaration (`=>`).
[source](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/#operator-precedence)
Wrapping the conditional operator in `{}` brackets should solve your problem:
```cs
... | If someone has this error and the answers above do not help, try the following.
<https://stackoverflow.com/a/60379426/13434418>
Preview (Conditional mapping with different source types)
```
//Cannot convert lambda expression to type
x.MapFrom(src => src.CommunityId.HasValue ? src.Community : src.Account)
//OK
x.MapFr... | 13,655 |
63,583,084 | According to this [FAQ page](https://faq.whatsapp.com/iphone/how-to-link-to-whatsapp-from-a-different-app) of Whatsapp on **How to link to WhatsApp from a different app**
Using the URL
`whatsapp://send?phone=XXXXXXXXXXXXX&text=Hello`
can be used to open the Whatsapp app on a Windows PC and perform a custom action.
... | 2020/08/25 | [
"https://Stackoverflow.com/questions/63583084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/603633/"
] | You can use cmd exe to do such a job. Just try
```
import subprocess
subprocess.Popen(["cmd", "/C", "start whatsapp://send?phone=XXXXXXXXXXXXX&text=Hello"], shell=True)
```
edit:
if you want to pass '&'(ampersand) in cmd shell you need to use escape char '^' for it.
please try that one
```
subprocess.Popen(["cmd"... | Using this command
start whatsapp://send?phone=XXXXXXXXXXXXX^&text=Hello
not working after updated to new WhatsApp Desktop App (UWP) for windows.
you have other idea for send text message to destination user. | 13,657 |
50,546,892 | i've seen some people write their shebang line with a space after env.
Eg.
```
#!/usr/bin/env python
```
Is this a typo?
I don't ever use a space. I use
```
#!/usr/bin/env/python
```
Can someone please clarify this? | 2018/05/26 | [
"https://Stackoverflow.com/questions/50546892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9536653/"
] | No it isn't a typo! The one you are using will not work on all os's. E.G. in my Ubuntu Linux implementation 'env' is a program in /usr/bin not a directory so #!/usr/bin/env/python won't work. | Not using a space isn't a typo, but leads to portability issues when executing the same file on different machines. The purpose of the shebang line (`#!/usr....`) is to indicate what interpreter is to be used when executing the code in the file. According to [Wikipedia](https://en.wikipedia.org/wiki/Shebang_%28Unix%29#... | 13,658 |
57,864,579 | I have a dataset of 8500 rows of text. I want to apply a function `pre_process` on each of these rows. When I do it serially, it takes about 42 mins on my computer:
```
import pandas as pd
import time
import re
### constructing a sample dataframe of 10 rows to demonstrate
df = pd.DataFrame(columns=['text'])
df.text =... | 2019/09/10 | [
"https://Stackoverflow.com/questions/57864579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5305512/"
] | Try following :
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication131
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
... | you can use `local-name()` to ignore the namespace in xpath
```
//*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='BatchResponse']
``` | 13,659 |
51,311,741 | how can i create a spoofed UDP packet using python sockets,without using scapy library.
i have created the socket like this
```
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes('', "utf-8"), ('192.168.1.9', 7043))# 192.168.1.9dest 7043 dest port
``` | 2018/07/12 | [
"https://Stackoverflow.com/questions/51311741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6584777/"
] | This is one of the first results for google searches like "spoofing udp packet python" so I am going to expand @Cukic0d's answer using scapy.
Using the scapy CLI tool (some Linux distributions package it separately to the scapy Python library ):
```py
pkt = IP(dst="1.1.1.1")/UDP(sport=13338, dport=13337)/"fm12abcd"
s... | I think you mean changing the source and destination addresses from the IP layer (on which the UDP layer is based).
To do so, you will need to use raw sockets. (SOCK\_RAW), meaning that you have to build everything starting from the Ethernet layer to the UDP layer.
Honestly, without scapy, that’s a lot of hard work. ... | 13,660 |
20,078,739 | I have a list of objects that I need to sort according to a [key function](https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions "Key functions"). The problem is that some of the elements in my list can go "out-of-date" while the list is being sorted. When the key function is called on such an expired item, it fail... | 2013/11/19 | [
"https://Stackoverflow.com/questions/20078739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1839209/"
] | Every sorting algorithm I know doesn't throw out some values because they're outdated or something. The task of sorting algorithm is to **sort** the list, and sort it fast, everything else is extraneous, specific task.
So, I would write this magical function myself. It would do the sorting in two steps: first it wou... | Since the result of the key function can change over time, and most sorting implementations probably assume a deterministic key function, it's probably best to only execute the key function once per object, to ensure a well-ordered and crash-free final list.
```
def func(seq, **kargs):
key = kargs["key"]
store... | 13,661 |
14,104,128 | I'm trying to define "variables" in an openoffice document, and I must be doing something wrong because when I try to display the value of the variable using a field, I only get an empty string.
Here's the code I'm using (using the Python UNO bridge). The interesting bit is the second function.
```python
import tim... | 2012/12/31 | [
"https://Stackoverflow.com/questions/14104128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281368/"
] | Use the updater property:
<http://jsfiddle.net/ZUhFy/10/>
```
.typeahead({
source: namelist,
updater: function(item) {
$('#log').append(item + '<br>');
return item;
}
});
```
>
> updater returns selected item The method used to return selected item.
> Accepts a ... | try
```
$('#findname').on('keyup', function() {...});
``` | 13,666 |
69,503,139 | My path is all messed up, javac and python commands not found, I even uninstalled and reinstalled java. I would throw in random stuff from the internet into my terminal whenever my code wouldn't work and have subsequently ruined my path, I've even added stuff to my bash\_profile and I don't know how to reset it or fix ... | 2021/10/09 | [
"https://Stackoverflow.com/questions/69503139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17110677/"
] | In SQL Server Management Studio you can remove the shortcut CTRL+E to execute a query.
Go to Tools > Options in the menu, then go to Environment > Keyboard > Keyboard in the tree on the left. Then select `Query.Execute` in the right table. Select the shortcut `CTRL+E (SQL Query Editor)` then click Remove which removes... | To prevent executing an entire script file from start to end, and only allow running selected snippets, this would work:
```
WHILE 1=1
PRINT 'NOT ALLOWED, press the STOP button'
PRINT 'After WHILE, will not show unless executed manually'
GO
PRINT 'After GO, will not show unless executed manually'
```
Because th... | 13,668 |
66,345,760 | I'm trying to play a `.mp3` file.
My code :
```
import os
os.system("start C:\Users\User\Desktop\Wakeup.mp3")
```
But, it gives an error like this:
```
File "C:/Users/User/PycharmProjects/pythonProject/Test.py", line 2
os.system("start C:\Users\User\Desktop\Wakeup.mp3")
^
SyntaxError: (unicode er... | 2021/02/24 | [
"https://Stackoverflow.com/questions/66345760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15272617/"
] | You did not escape the backslash character. try this:
```
os.system("start C:\\Users\\User\\Desktop\\Wakeup.mp3")
```
**Option 2**
Use forward slash instead:
```
os.system("start C:/Users/User/Desktop/Wakeup.mp3")
```
**Option 3**
Use "raw" string:
```
os.system(r"start C:\Users\User\Desktop\Wakeup.mp3")
``` | If you want to play sound. You can do something like this.
```
from playsound import playsound
playsound("path/name.mp3")
```
Hope this helps ... :D | 13,671 |
5,639,049 | I found in the [documentation of pygraph](http://dl.dropbox.com/u/1823095/python-graph/docs/pygraph.classes.graph.graph-class.html) how to change the [attributes of the nodes and the edges](http://www.graphviz.org/doc/info/attrs.html), but I found no help on how to change the attributes of the graphs.
I tried without... | 2011/04/12 | [
"https://Stackoverflow.com/questions/5639049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380038/"
] | So, doing more research on my own, I found that [pygraphviz](http://networkx.lanl.gov/pygraphviz/index.html) is offering what I need. Here is the `pygraph` example using `pygraphviz` and accepting attributes. It is also shorter, as you don't have to specify the nodes if all of them are connected via edges.
```
#!/usr/... | I don't know about pygraph, but I think the way you set attributes in python was:
```
setattr(object, attr, value)
setattr(gr, 'aspect', 2)
```
I mean, you have tried gr.aspect = 2, right? | 13,672 |
64,866,304 | I'm trying to set up a new cygwin installation and install python through cygwin. I've done so, and the setup completed, but when I try to run `python3.8` I get a fatal python error:
```sh
$ python3.8
Python path configuration:
PYTHONHOME = 'C:\Users\cmhac\AppData\Local\Programs\Python\Python38'
PYTHONPATH = 'C:\U... | 2020/11/16 | [
"https://Stackoverflow.com/questions/64866304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11831775/"
] | I saw this exact error:
Fatal Python error: init\_fs\_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'
If you set these two env variables to nil, the problem should disappear:
set PYTHONHOME=
set PYTHONPATH= | Go to your wsgi.py file under your project and do something similar to:
```
import os
import sys
from django.core.wsgi import get_wsgi_application
sys.path.append('path/to/yourprojectenv/lib/python3.8/site-packages')
```
Restart your server and try again. | 13,676 |
44,434,185 | I am trying to create a python program that will take data from multiple excel sheets and I am kinda stuck at the moment:
```
import xlrd
import xlwt
workbook1 = xlrd.open_workbook('Z:\Public\Safety\SafetyDataPullProject\TestFile.xlsx', on_demand = True)
worksheet = workbook1.sheet_by_index('Sheet1')
sheet.cell(5, 5)... | 2017/06/08 | [
"https://Stackoverflow.com/questions/44434185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8131036/"
] | The answer's well documented in Marshmallows [api reference](http://marshmallow.readthedocs.io/en/latest/api_reference.html#module-marshmallow.fields).
I need to use `dump_to` :
```
class ApiSchema(Schema):
class Meta:
strict = True
time = fields.Number(dump_to='_time')
id = fields.String(dump_t... | You can override the [`dump`](https://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.Schema.dump) method to *prepend* underscores to selected fields before returning the serialised object:
```
class ApiSchema(Schema):
class Meta:
strict = True
time = fields.Number()
id = field... | 13,677 |
15,627,307 | I am trying to figure out the best way to convert from epoch seconds (since NTP epoch 1900-01-01 00:00) to a datetime string (MM/DD/YY,hh:mm:ss) without any libraries/modules/external functions, as they are not available on an embedded device.
My first thought was to look at the [Python datetime module source code](ht... | 2013/03/26 | [
"https://Stackoverflow.com/questions/15627307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2209295/"
] | The `getDateFromJulianDay` function originally proposed is too computationally intensive for effective use on an embedded device, containing many multiplication and division operations on large `long` variables or, as originally written in C++, [`longlong` variables](http://qt.gitorious.org/qt/qt/blobs/4.7/src/corelib/... | TL;DR
=====
If you are using a Telit GC-864, the Python interpreter seemingly inserts some sort of delay in-between each line of code execution.
For a Telit GC-864, the function in my question `getDateFromJulianDay(julianDay)` is faster than the function in my answer, `ntp_time_to_date(ntp_time)`.
More Detail
======... | 13,683 |
46,367,625 | I am trying to detect language of the string with langdetect package. But it does not work.
```
from langdetect import detect
word_string = "Books are for reading"
print(detect(word_string))
```
If I use code above I get error `ImportError: cannot import name detect`
When I replace detect with \*
```
from langdet... | 2017/09/22 | [
"https://Stackoverflow.com/questions/46367625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6152972/"
] | Try installing it first by writing :->
`!pip install langdetect` on terminal
and then `import langdetect` | You can not import it because it is probably not there. See if the name is correct. Seeing other questions here on SO I assume you mean detect\_langs. | 13,684 |
39,370,879 | I have a dataframe df\_energy2
```
df_energy2.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 29974 entries, 0 to 29973
Data columns (total 4 columns):
TIMESTAMP 29974 non-null datetime64[ns]
P_ACT_KW 29974 non-null int64
PERIODE_TARIF 29974 non-null object
P_SOUSCR 29974 non-null in... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39370879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2278337/"
] | I think you need [`dt.hour`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.hour.html):
```
print (df.TIMESTAMP.dt.hour)
0 0
1 0
Name: TIMESTAMP, dtype: int64
df['hours'] = df.TIMESTAMP.dt.hour
print (df)
TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR hours
0 2016-01-01 00:00:0... | Given your data:
>
>
> ```
> df_energy2.head()
>
> TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR
> 2016-01-01 00:00:00 116 HC 250
> 2016-01-01 00:10:00 121 HC 250
>
> ```
>
>
You have timestamp as the index. For extracting hours from timestamp where you have it as the index of the dataframe:
```
hours = df_ene... | 13,686 |
16,027,942 | I've written a high level motor controller in Python, and have got to a point where I want to go a little lower level to get some speed, so I'm interested in coding those bits in C.
I don't have much experience with C, but the math I'm working on is pretty straightforward, so I'm sure I can implement with a minimal am... | 2013/04/16 | [
"https://Stackoverflow.com/questions/16027942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1481457/"
] | You can take a look at this tutorial [here](http://csl.name/C-functions-from-Python/).
Also, a more reliable example on the official python website, [here](http://docs.python.org/2/extending/extending.html#a-simple-example).
For example,
`sum.h` function
```
int sum(int a, int b)
```
A file named, `module.c`,
`... | Another option: try [numba](http://numba.pydata.org/).
It gives you C-like speed for free: just import numba and @autojit your functions, for a wonderful speed increase.
Won't work if you have complicated data types, but if you're looping and jumping around array indices, it might be just what you're looking for. | 13,687 |
21,119,958 | I am trying to negate the value returned by one function.
Consider the code to be
```
def greater(a,b):
return a>b
check = negate(greater)
assert check(8,9)
```
OR
```
def equal(a,b):
return a==b
check = negate(equal)
assert check("python","java")
```
How should I define the ***NEGATE*** function??? | 2014/01/14 | [
"https://Stackoverflow.com/questions/21119958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3181773/"
] | Like this:
```
def negate(func):
def result(*args):
return not func(*args)
return result
```
This is a function which creates a function which returns the result of invoking the original function and `not`ing it's return value, and then returning that function. | Use the `not` operator in a decorator:
```
from functools import wraps
def negate(func):
@wraps(func)
def wrapper(*args, **kw):
return not func(*args, **kw)
return wrapper
```
The above decorator returns a wrapper function that applies `not` to the return value of the wrapped function. The [`@fu... | 13,690 |
14,749,379 | Because *programming* is one of my favorite hobbies I started a small project in python.
I'm trying to make a nutritional calculator for daily routine, see the code below:
```
# Name: nutri.py
# Author: pyn
my_dict = {'chicken':(40, 50, 10),
'pork':(50, 30, 20)
}
foods = raw_input("Enter your food... | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2050432/"
] | You could use the sibling selector. As long as div's share the same parent, you can still affect them with hover
[DEMO](http://jsfiddle.net/8LFWR/)
Vital Code:
```
#gestaltung_cd:hover ~ #mainhexa1,
#gestaltung_illu:hover ~ #mainhexa2,
#gestaltung_klassisch:hover ~ #mainhexa3 {
display: block;
}
``` | Here's an example of how to do the first one and you'd just do the same for the other two with the relevant IDs.
```
$("#gestaltung_cd").hover(
function () {
$("#mainhexa1").show();
},
function () {
$("#mainhexa1").hide();
}
);
``` | 13,693 |
7,556,499 | despite using the search function I've been unable to find an answer. I got two assumptions, but don't know in how far they may apply. Now the problem:
I'd like to plot a contour. For this I've got here the following python code:
```
import numpy as np
import matplotlib.pyplot as plt
xi=list_of_distance
yi=list_of_a... | 2011/09/26 | [
"https://Stackoverflow.com/questions/7556499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/329586/"
] | As @rocksportrocker implies, you need to take into account that `histogram2d` returns the edges in addition to the histogram. Another detail is that you probably want to explicitly pass in a range, otherwise one will be chosen for you based on the actual min and max values in your data. You then want to convert the edg... | Your traceback indicates that the error does not raise from the call to matplotlib, it is numpy which raises the ValueError. | 13,703 |
46,437,882 | So this is driving me crazy I have python3 and modwsgi and apache and a virtual host, that work great, as I have several other wsgi scripts that work fine on the server. I also have a django app that works great when I run the dev server.
I have checked that "ldd mod\_wsgi.so" is linked correctly against python3.5
W... | 2017/09/27 | [
"https://Stackoverflow.com/questions/46437882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4216567/"
] | You probably need to tell mod\_wsgi where your project code is. For embedded mode this is done with `WSGIPythonPath` directive. You should preferably though use daemon mode, in which case you would use `python-path` option to `WSGIDaemonProcess` directive. | ok I finally figured out how to fix the issue but not sure exactly why. First off when I was mixing my own wsgi scipts and django I had to specify the daemon process only for the script alias that was django
```
WSGIScriptAlias /certs /var/www/scripts/CavsCertSearch/CavsCertSearch/certstrip.wsgi
WSGIScriptAlias /t... | 13,704 |
12,957,921 | I am attempting to run a python program that can run a dictionary from a file with a list of words with each word given a score and standard deviation. My program looks like this:
```
theFile = open('word-happiness.csv' , 'r')
theFile.close()
def make_happiness_table(filename):
'''make_happiness_table: string ->... | 2012/10/18 | [
"https://Stackoverflow.com/questions/12957921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1712920/"
] | The template parameter to [`std::normal_distribution`](http://en.cppreference.com/w/cpp/numeric/random/normal_distribution) must be a floating-point type (`float`, `double`, or `long double`). Using anything else will result in undefined behavior.
Since normal distribution is a continuous distribution, it isn't really... | You can use `binomial_distribution` with default probability value of 0.5.
[link](http://www.cplusplus.com/reference/random/binomial_distribution/binomial_distribution/)
It will return integer values in range [0,t], with mean at t/2 ( in case t is even else (t+1)/2, (t-1)/2 have equal prob.). You can set the value of ... | 13,705 |
51,572,168 | when i want to see my django website in their server....i open cmd and go to manage.py directory:
```
C:\Users\computer house\Desktop\ahmed>
```
and then i type :
```
python manage.py runserver
```
but i see this error :
```
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execu... | 2018/07/28 | [
"https://Stackoverflow.com/questions/51572168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10102365/"
] | As far as i understood, You have started your project with the following command:
```
C:\Users\computer house\Desktop> python startproject ahmed
```
After that I assume you have similar file structure:
```
ahmed/
├── ahmed/ # make sure this directory exists
│ ├── __init__.py # make sure this file exists.
│ ├──... | check your current directory to have file names `__init__.py` also a directory named `ahmed` contains `__init__.py` | 13,706 |
10,363,853 | I'm trying to talk to a child process using the python subprocess.Popen() call. In my real code, I'm implementing a type of IPC, so I want to write some data, read the response, write some more data, read the response, and so on. Because of this, I cannot use Popen.communicate(), which otherwise works well for the simp... | 2012/04/28 | [
"https://Stackoverflow.com/questions/10363853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/526797/"
] | I would try to use `Popen().communicate()` if you can as it does a lot of nice things for you, but if you need to use `Popen()` exactly as you described, you'll need to set sed to flush its buffer after newlines with the `-l` option:
```
p = subprocess.Popen(['sed', '-l', 's/a/x/g'],
stdout=subpro... | `sed`'s output is buffered and only outputs its data until enough has been cumulated or the input stream is exhausted and closed.
Try this:
```
import subprocess
p = subprocess.Popen(["sed", 's/a/x/g'],
stdout = subprocess.PIPE,
stdin = subprocess.PIPE)
p.stdin.write("abc\n"... | 13,707 |
18,389,273 | I'm using python and having some trouble reading the properties of a file, when the filename includes non-ASCII characters.
One of the files for example is named:
`0-Channel-https∺∯∯services.apps.microsoft.com∯browse∯6.2.9200-1∯615∯Channel.dat`
When I run this:
```python
list2 = os.listdir('C:\\Users\\James\\AppDat... | 2013/08/22 | [
"https://Stackoverflow.com/questions/18389273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084310/"
] | If this is python 2.x, its an encoding issue. If you pass a unicode string to os.listdir such as `u'C:\\my\\pathname'`, it will return unicode strings and they should have the non-ascii chars encoded correctly. See [Unicode Filenames](http://docs.python.org/2/howto/unicode.html#unicode-filenames) in the docs.
Quoting ... | As you are in windows you should try with ntpath module instead of os.path
```
from ntpath import getmtime
```
As I don't have windows I can't test it. Every os has a different path convention, so, Python provides a specific module for the most common operative systems. | 13,708 |
7,281,348 | I'm building a website which allows you to write python code online just like <http://shell.appspot.com/> or <http://ideone.com>. Can someone please provide me some help how I can achieve this? | 2011/09/02 | [
"https://Stackoverflow.com/questions/7281348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/924945/"
] | First of all you can browse their [source code](http://code.google.com/p/google-app-engine-samples/downloads/detail?name=shell_20091112.tar.gz&can=2&q=). The main file is only 321 lines !
Basically it keeps a separate global dict for each user session, then uses `compile` and `exec` to run the code and return the resu... | I am new to python but hopefully following links could help you acheive ur goal,
BaseHTTPServer (http://docs.python.org/library/basehttpserver.html) library can be used for handling web requests and ipython (http://ipython.org) for executing python commands at the backend. | 13,709 |
33,301,838 | I am trying to access a JSON object/dictionary in python however get the error:
>
> TypeError: string indices must be integers if script['title'] ==
> "IT":
>
>
>
and this is my code to try and access that particular key within the dictionary:
```
def CreateScript(scriptsToGenerate):
start = time.clock()
... | 2015/10/23 | [
"https://Stackoverflow.com/questions/33301838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4867148/"
] | Facts:
* `scriptList` is a list of dictionaries (according to you)
* `for item in scriptList:` gets one dictionary at a time
* `proc = Process(target=CreateScript, args=(item))` passes a dictionary to the `CreateScript` function
* `def CreateScript(scriptsToGenerate):` receives a dictionary
* `for script in scriptsToG... | John, what I meant was that you have a json object there, it will need to be treated as such. I think you mean can you do the following?
```
def CreateScript(scriptsToGenerate):
#start = time.clock()
apiLocation = ""
saveFile = ""
i = json.loads(scriptsToGenerate)
if i['title'] == "IT":
tim... | 13,710 |
56,328,818 | I am using fuzzywuzzy in python for fuzzy string matching. I have a set of names in a list named HKCP\_list which I am matching against a pandas column iteratively to get the best possible match. Given below is the code for it
```
import fuzzywuzzy
from fuzzywuzzy import fuzz,process
def search_func(row):
chk = p... | 2019/05/27 | [
"https://Stackoverflow.com/questions/56328818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4762935/"
] | Use this function:
```
typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture) async {
try {
return await aFuture();
} catch (e) {
if (retries > 1) {
return retry(retries - 1, aFuture);
}
rethrow;
}
}
```
And to use it:
```
main(List<String> argu... | This is how I implemented it:
```
Future retry<T>(
{Future<T> Function() function,
int numberOfRetries = 3,
Duration delayToRetry = const Duration(milliseconds: 500),
String message = ''}) async {
int retry = numberOfRetries;
List<Exception> exceptions = [];
while (retry-- > 0) {
try {
... | 13,711 |
6,424,676 | I have a list of lists, say:
```
arr = [[1, 2], [1, 3], [1, 4]]
```
I would like to append 100 to each of the inner lists. Output for the above example would be:
```
arr = [[1, 2, 100], [1, 3, 100], [1, 4, 100]]
```
I can of course do:
```
for elem in arr:
elem.append(100)
```
But is there ... | 2011/06/21 | [
"https://Stackoverflow.com/questions/6424676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373948/"
] | The second version should be written like `arr = [elem + [100] for elem in arr]`. But the most pythonic way if you ask me is the first one. The `for` construct has it's own use, and it suits very well here. | You can do
```
[a + [100] for a in arr]
```
The reason why your `append` doesn't work is that `append` doesn't return the list, but rather `None`.
Of course, this is more resource intensive than just doing `append` - you end up making copies of everything. | 13,717 |
54,024,663 | I have a python application that is running in Kubernetes. The app has a ping health-check which is called frequently via a REST call and checks that the call returns an HTTP 200. This clutters the Kubernetes logs when I view it through the logs console.
The function definition looks like this:
```
def ping():
re... | 2019/01/03 | [
"https://Stackoverflow.com/questions/54024663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5240483/"
] | In kubernetes, everything in container which you have on `stdout` or `stderr` will come into the kubernetes logs. The only way to exclude the logs of `health-check` ping call remove from kubernetes logs is that, In your application you should redirect output of those ping calls to somefile in say `/var/log/`. This will... | Just invert the logic log on fail in the app, modify the code or wrap with a custom decorator | 13,721 |
48,186,159 | My app is installed correctly and its models.py reads:
```
from django.db import models
class Album(models.Model):
artist = models.CharField(max_lenght=250)
album_title = models.CharField(max_lenght=500)
genre = models.CharField(max_lenght=100)
album_logo = models.CharField(max_lenght=1000)
class Son... | 2018/01/10 | [
"https://Stackoverflow.com/questions/48186159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8978159/"
] | Use this:
As per my comment, length (lenght) splelling is wrong.
```
from django.db import models
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
album_logo = models.TextField()
class Song(... | You have spelled length wrong here
```
album_title = models.CharField(max_lenght=500)
```
happens to the best of us. | 13,724 |
63,709,035 | I am trying to have a button in HTML that removes a row in the database when I click it. This is for a flask app.
here is the HTML:
```
<div class="container-fluid text-center" id="products">
{% for product in productList %}
<div class='userProduct'>
<a href="{{ product.productURL }}" target="_blank">{... | 2020/09/02 | [
"https://Stackoverflow.com/questions/63709035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11522265/"
] | You're probably passing ID as an integer and your route is expecting a string. Use this instead:
```
@app.route('/delete/<int:id>')
``` | I just encountered the same error,
In my case it was caused by some values being None in the database.
So maybe check whether product.id has missing values.
To handle this, I needed an extra line, which would look something like this for you:
```
@app.route('/delete/<id>') # current line
@app.route('/delete', default... | 13,725 |
31,291,204 | I'm new to Apache Spark and have a simple question about DataFrame caching.
When I cached a DataFrame in memory using `df.cache()` in python, I found that the data is removed after the program terminates.
Can I keep the cached data in memory so that I can access the data for the next run without doing `df.cache()` ... | 2015/07/08 | [
"https://Stackoverflow.com/questions/31291204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2368670/"
] | The cache used with `cache()` is tied to the current spark context; its purpose is to prevent having to recalculate some intermediate results in the current application multiple times. If the context gets closed, the cache is gone. Nor can you share the cache between different running Spark contexts.
To be able to reu... | If you are talking about saving the RDD into disk , use any of the following -

The link is for pyspark , same is available for Java/ Scala as well-#
<https://spark.apache.org/docs/latest/api/python/pyspark.sql.html>
If you were not talking about d... | 13,726 |
38,989,150 | I trying to import a module and use a function from that module in my current python file.
I run the nosetests on the parser\_tests.py file but it fails with "name 'parse\_subject' not defined"
e.g its not finding the parse\_subject function which is clearly defined in the parsrer.py file
This is the parsrer file:
... | 2016/08/17 | [
"https://Stackoverflow.com/questions/38989150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6684586/"
] | ```
SELECT STUFF((
SELECT ','+ Name
FROM MyTable
WHERE ID in (1, 2, 3)
FOR XML PATH('')
), 1, 1, '') AS Names
```
Result:
>
> Apple,Microsoft,Samsung
>
>
> | ```
USE [Database Name]
SELECT COLUMN_NAME,*
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName'
``` | 13,727 |
41,595,532 | I have a Tkinter button, and for some reason, it accepts width=xx, but not height=xx
I'm using Python 3.5, with Tkinter support by default, on ubuntu 16.04
Here's the code sample:
```
# works: button_enter = ttk.Button(self.frm, text='ok', width = 100)
# works: button_enter.config(width=25)
# fails: button_enter = ... | 2017/01/11 | [
"https://Stackoverflow.com/questions/41595532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/377783/"
] | It's not a bug, that's just how ttk buttons work. If you need a highly configurable button, use a tkinter button. ttk buttons are less configurable on purpose. The goal of ttk widgets is to give you a set of buttons consistent with a particular theme.
Since you're on a linux system you can affect the height with `pack... | Use the **Place()** method instead over **Grid() or Pack() or Config()** . It will work fine. I never used **Config()** method | 13,732 |
631,884 | How do you encode a png image into base64 using python on Windows?
```
iconfile = open("icon.png")
icondata = iconfile.read()
icondata = base64.b64encode(icondata)
```
The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this? | 2009/03/10 | [
"https://Stackoverflow.com/questions/631884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76322/"
] | [Open the file in binary mode](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files):
```
open("icon.png", "rb")
```
I'm not very familiar with Windows, but I'd imagine what's happening is that the file contains a character (0x1A) that [Windows is interpreting as the end of the file](http://www... | To augment the answer from Miles, the [first eight bytes in a PNG file](http://www.libpng.org/pub/png/spec/1.2/PNG-Rationale.html#R.PNG-file-signature) are specially designed:
* 89 - the first byte is a check that
bit 8 hasn't been stripped
* "PNG" - let someone read that it's a
PNG format
* 0d 0a - the DOS end-of-lin... | 13,734 |
8,839,846 | In vim, you can check if a file is open in the current buffer with `bufexists`. For a short filename (not full path), you can check if it's open using `bufexists(bufname('filename'))`.
Is there any way to check if a file is open in a *tab*?
My closest workaround is to do something like:
```
:tabdo if bufnr(bufname(... | 2012/01/12 | [
"https://Stackoverflow.com/questions/8839846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814354/"
] | My impatience and good documentation got the better of me... here's the solution (greatly aided by [Check if current tab is empty in vim](https://stackoverflow.com/questions/5025558/check-if-current-tab-is-empty-in-vim) and [Open vim tab in new (GUI) window?](https://stackoverflow.com/questions/6123424/open-vim-tab-in-... | I'd reply to keflavich, but I can't yet...
I was working on a similar problem where I wanted to mimic the behavior of gvim --remote-tab-silent when opening files inside of gvim. I found this WhichTab script of yours, but ran into problems when there is more than one window open in any given tab. If you split windows ... | 13,735 |
44,894,992 | **On Windows 10, Python 3.6**
Let's say I have a command prompt session open **(not Python command prompt or Python interactive session)** and I've been setting up an environment with a lot of configurations or something of that nature. Is there any way for me to access the history of commands I used in that session w... | 2017/07/03 | [
"https://Stackoverflow.com/questions/44894992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6805800/"
] | You don't need Python at all, use `doskey` facilities for that, i.e.:
```
doskey /history
```
will print out the current session's command history, you can then redirect that to a file if you want to save it:
```
doskey /history > saved_commands.txt
```
If you really want to do it from within Python, you can use ... | You're actually asking for 3 different things there.
1. Getting Python REPL command hisotry
2. Getting info from "prompt", which I assume is the Powershell or CMD.exe.
3. Save the history list to a file.
To get the history from inside your REPL, use:
```py
for i in list(range(readline.get_current_history_length())):... | 13,736 |
73,631,420 | I am scraping web series data from `JSON` and `lists` using python. the problem is with date and time.
I got a function to convert the `duration` format
```
def get_duration(secs):
hour = int(secs/3600)
secs = secs - hour*3600
minute = int(secs/60)
if hour == 0:
return "00:" + str(minute)
e... | 2022/09/07 | [
"https://Stackoverflow.com/questions/73631420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19861079/"
] | That value looks like a timestamp so you could use [`datetime.fromtimestamp`](https://docs.python.org/3/library/datetime.html#datetime.date.fromtimestamp) to convert to a `datetime` object and then [`strftime`](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) to output in the format you want:... | The original question is slightly unclear about the final desired format. If you would like "22 Apr 2019" then the required format string is "%d %b %Y"
```
from datetime import datetime
d = datetime.fromtimestamp(1555939800)
print(d.strftime('%d %b %Y'))
```
Output:
```
22 Apr 2019
``` | 13,737 |
57,159,408 | Am new to python and trying to understand logging (am not new to programming at all though). Trying to replicate log4j logger that we have in Java. Have a simple test project of the following files:
- User.py
- Test.py
- conf/
- logging.conf
- log
All the python files have logger objects to log to specific file menti... | 2019/07/23 | [
"https://Stackoverflow.com/questions/57159408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1300830/"
] | I see a couple of things that may be the issue:
1) you're running 2 separate loggers: each file is instantiating it's own logger pointed to the same file.
2) if you want everything in the same file, then create one logger and pass the reference to other modules via a global var. I find it easier to create a log.py fil... | Thanks tbitson for the pointers. Here is the changed code.
```
import logging
import logging.config
logging.config.fileConfig('conf/logging.conf')
logger = logging.getLogger(__name__)
```
The modified User.py is:
```
from logger import logger
class User:
username = ""
password = ""
def __init__(self, ... | 13,738 |
47,111,787 | I'm trying to set and get keys from ElastiCache (memcached) from a python lambda function using Boto3. I can figure out how to get the endpoints but that's pretty much it. Is there some documentation out there that shows the entire process? | 2017/11/04 | [
"https://Stackoverflow.com/questions/47111787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4891674/"
] | It sounds like you are trying to interact with Memcached via Boto3. This is not possible. Boto3 is for interacting with the AWS API. You can manage your ElastiCache servers via the AWS API, but you can't interact with the Memcached software running on those servers. You need to use a Memcached client library like [pyth... | I had the exact timeout problem listed in the commment of the older post. My bug is in the security group for memcached. Here is the working version in terraform:
```
resource "aws_security_group" "memcached" {
vpc_id = "${aws_vpc.dev.id}"
name = "memcached SG"
ingress {
from_port = "${var.memcached... | 13,739 |
39,899,312 | I am using the Tracer software package (<https://github.com/Teichlab/tracer>).
The program is invoked as followed:
`tracer assemble [options] <file_1> [<file_2>] <cell_name> <output_directory>`
The program runs on a single dataset and the output goes to `/<output_directory>/<cell_name>`
What I want to do now is run ... | 2016/10/06 | [
"https://Stackoverflow.com/questions/39899312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6932623/"
] | I think this will do it, in bash, if I understand correctly -
```bash
for filename in /home/tobias/tracer/datasets/test/*.fastq
do
echo "Processing $filename file..."
basefilename="${filename##*/}" #<---
python tracer assemble --single_end --fragment_length 62 --fragment_sd 1 "$filename" "${basefilename%.fast... | From what I understood the library you use writes output to predefined (non configurable) directory
Let's call it `output_dir`.
At each iteration you should rename the output directory.
So your code should be something like this (pseudo code)
```
for filename in /home/tobias/tracer/datasets/test/*.fastq
do
e... | 13,740 |
69,760,313 | Is there more pythonic way to remove all duplicate elements from a list, while keeping the first and last element?
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
occurence = [i for i, e in enumerate(lst) if e == "foo"]
to_remove = occurence[1:-1]
for i in to_remove:
del lst[i]
print(lst) # ['foo', '... | 2021/10/28 | [
"https://Stackoverflow.com/questions/69760313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7661466/"
] | Use a slice-assignment and unpack/consume a filter?
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
lst[1:-1] = filter(lambda x: x != "foo", lst[1:-1])
print(lst)
```
Output:
```
['foo', 'bar', 'foobar', 'barfoo', 'foo']
``` | You can construct a new list with your requirements using Python's set data structure and slicing like this:
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
new_lst = [lst[0]] + list(set(lst[1:-1])) + [lst[-1]]
``` | 13,741 |
66,819,423 | I have homework where I'm asked to build Newton and Lagrange interpolation polynomials. I had no troubles with Lagrange polynomial but with Newton polynomial arises one problem: while Lagrange interpolation polynomial and original function match completely with each other, Newton Interpolation doesn't do this.
[Here is... | 2021/03/26 | [
"https://Stackoverflow.com/questions/66819423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11749578/"
] | One object is created, of type `C`, which contains all of the members of `A`, `B`, and `C`. | Here are some additional information about the relation between a base-class object and a derived-class object:
Every derived object contains a base-class part to which a pointer or reference of the base-class type can be bound. That's the reason why a conversion from derived to base exists, and no implicit Conversi... | 13,745 |
56,712,534 | How to append alpha values inside nested list in python?
```
nested_list = [['72010', 'PHARMACY', '-IV', 'FLUIDS', '7.95'], ['TOTAL',
'HOSPITAL', 'CHARGES', '6,720.92'],['PJ72010', 'WORD', 'FLUIDS',
'7.95']]
Expected_output:
[['72010', 'PHARMACY -IV FLUIDS', '7.95'], ['TOTAL HOSPITAL CHARGES', '6,720.92'],['PJ7201... | 2019/06/22 | [
"https://Stackoverflow.com/questions/56712534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11425561/"
] | If you create a function that defines what you mean by word you can use [`itertools.groupby()`](https://docs.python.org/3/library/itertools.html#itertools.groupby) to group by this function. Then you can either append the `join()`ed results or `extend()` depending on whether it's a group of numbers of word.
I'm inferr... | Go through the each nested list. Check the each element of that list . If it is a full alpha den append it in a temporary variable. Once you find a numeric append the temporary and numeric both.
Code:
```
nested_list = [['72010', 'PHARMACY', '-IV', 'FLUIDS', '7.95'], ['TOTAL',
'HOSPITAL', 'CHARGES', '6,720.92'],['PJ7... | 13,747 |
34,902,307 | I have a python script that processes an XML file each day (it is transferred via SFTP to a remote directory, then temporarily copied to a local directory) and stores its information in a MySQL database.
One of my parameters for the file is set to "date=today" so that the correct file is processed each day. This works... | 2016/01/20 | [
"https://Stackoverflow.com/questions/34902307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5451573/"
] | You can use `sys` module and pass the filename as command line argument.
That would be :
```
import sys
today = str(sys.argv[1]) if len(sys.argv) > 1 else datetime.datetime.now().strftime('%Y%m%d')
```
If the name is given as first argument, then `today` variable will be filename given from command line otherwise ... | You can use [argsparse](https://docs.python.org/3/library/argparse.html) to consume command line arguments. You will have to check if specific date is passed and use it instead of the current date
```
if args.date_to_run:
today = args.date_to_run
else:
today = datetime.datetime.now().strftime('%Y%m%d')
```
F... | 13,748 |
73,061,728 | I'm trying to get a better understanding of python imports and namespaces. Take the example of a module testImport.py:
```py
# testImport.py
var1 = 1
def fn1():
return var1
```
if I import this like this:
```py
from testImport import *
```
I can inspect `var1`
```py
>>> var1
1
```
and `fn1()` returns
```... | 2022/07/21 | [
"https://Stackoverflow.com/questions/73061728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13258525/"
] | I'm not sure that you would be able to modify the root node as you are trying to do here. The namespace URI should be `http://www.w3.org/2000/xmlns/p` if it is `p` that you are trying to use as the prefix and you would use `p:root` as the qualifiedName but that would result in the root node being modified like this `<r... | The root element is the root element. You change it by creating a new document with the root element of your choice.
If the the job is left to import all root elements children from another document, then be it (SimpleXML is not that fitting for that, DOMDocument is, see [`DOMDocument::importNode`](https://www.php.net... | 13,749 |
51,943,359 | I have this part on the `docker-compose` that will copy the `angular-cli` frontend and a `scripts` directory.
```
www:
build: ./www
volumes:
- ./www/frontend:/app
- ./www/scripts:/scripts
command: /scripts/init-dev.sh
ports:
- "4200:4200"
- "49153:49153"
```
The `Dockerfile`... | 2018/08/21 | [
"https://Stackoverflow.com/questions/51943359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2111400/"
] | Two options:
1. also start your services with the InProcessServerBuilder, and use the InProcessChannelBuilder to communicate with it, or
2. just contact the server over "localhost" | if you want a cli type of call to your local grpc server, you could checkout <https://github.com/fullstorydev/grpcurl> | 13,750 |
42,990,994 | I have this code
```
python_data_struct = {
'amazon_app_id': amazon_app_id,
'librivox_rest_url': librivox_rest_url,
'librivox_id': librivox_id,
'top': top,
'pacakge': 'junk',
'version': 'junk',
'password': password,
'description': description,
'l... | 2017/03/24 | [
"https://Stackoverflow.com/questions/42990994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/759991/"
] | You can make function calls on ngSubmit
*form class="well" (ngSubmit)="addUserModal.hide(); addUser(model); userForm.reset()" #userForm="ngForm"* | I haven't used AngularJS, but the following works for me in Angular 2, if you're able to use jQuery:
`$(".modal").modal("hide")` | 13,751 |
59,641,747 | I cannot get it it's bash related or python subprocess, but results are different:
```
>>> subprocess.Popen("echo $HOME", shell=True, stdout=subprocess.PIPE).communicate()
(b'/Users/mac\n', None)
>>> subprocess.Popen(["echo", "$HOME"], shell=True, stdout=subprocess.PIPE).communicate()
(b'\n', None)
```
Why in second... | 2020/01/08 | [
"https://Stackoverflow.com/questions/59641747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6519078/"
] | Use fifo format, which can reconnect.
My working example:
```
-f fifo -fifo_format flv \
-drop_pkts_on_overflow 1 -attempt_recovery 1 -recover_any_error 1 \
rtmp://bla.bla/bla
``` | +1 for the accepted answer, but:
In FFmpeg, an encoder auto-detects it's parameters based on selected output format. Here the output format is unknown (that's correct for formats like "fifo" and "tee") so the encoder won't have all parameters setup the same as if using "flv" output format.
For example: Wowza Streamin... | 13,754 |
58,469,032 | I am starting to learn python and I don't know much about programming right now. In the future, I want to build android applications. Python looks interesting to me.
Can I use python for building Android applications? | 2019/10/20 | [
"https://Stackoverflow.com/questions/58469032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11109516/"
] | You can build android apps in python, but it's not as powerful as android studio, and the apps made by python take more space and are less memory efficient.But the apps work well...
There are several ways to use Python on Android:
BeeWare. BeeWare is a collection of tools for building native user interfaces. ...
Cha... | As of now the official android development languages are **kotlin** and **java** in `android studio` IDE, with the addition of **dart** for cross-platform development in `flutter` SDK. I would advise you stick to whichever you find easiest as per your needs. Although python is more widely accepted in the domains of dat... | 13,755 |
74,054,668 | How to convert a `.csv` file to `.npy` efficently?
--------------------------------------------------
I've tried:
```
import numpy as np
filename = "myfile.csv"
vec =np.loadtxt(filename, delimiter=",")
np.save(f"{filename}.npy", vec)
```
While the above works for smallish file, the actual `.csv` file I'm working o... | 2022/10/13 | [
"https://Stackoverflow.com/questions/74054668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | Nice question; Informative in itself.
I understand you want to have the whole data set/array in memory, eventually, as a NumPy array. I assume, then, you have enough (RAM) memory to host such array -- 12M x 1K.
I don't specifically know about how `np.loadtxt` (`genfromtxt`) is operating behind the scenes, so I will t... | TL;DR
=====
Export to a different function other than `.npy` seems inevitable unless your machine is able to handle the size of the data in-memory as per described in [@Brandt answer](https://stackoverflow.com/a/74055562/610569).
---
Reading the data, then processing it (Kinda answering Q part 2)
===================... | 13,757 |
8,575,062 | I am sure the configuration of `matplotlib` for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
Ther... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504283/"
] | You must use `plt.show()` at the end in order to see the plot | `plt.plot(X,y)` function just draws the plot on the canvas. In order to view the plot, you have to specify `plt.show()` after `plt.plot(X,y)`. So,
```
import matplotlib.pyplot as plt
X = //your x
y = //your y
plt.plot(X,y)
plt.show()
``` | 13,764 |
15,128,225 | I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016950/"
] | Reading registry keys:
```
def read(path, root=HKEY_CURRENT_USER):
path, name = os.path.split(path)
with suppress(FileNotFoundError), OpenKey(root, path) as key:
return QueryValueEx(key, name)[0]
```
And writing:
```
def write(path, value, root=HKEY_CURRENT_USER):
path, name = os.path.split(path... | for Creating / writing values in registry key:
```
from winreg import*
import winreg
keyVal = r'SOFTWARE\\python'
try:
key = OpenKey(HKEY_LOCAL_MACHINE, keyVal, 0, KEY_ALL_ACCESS)
except:
key = CreateKey(HKEY_LOCAL_MACHINE, keyVal)
SetValueEx(key, "Start Page", 0, REG_SZ, "snakes")
CloseKey(key)
```
If acc... | 13,774 |
15,576,693 | I am currently working on a project for one of my classes where I have to implement an AI opponent to play tic-tac-toe using minmax and Alpha-Beta minmax algorithms to determine the moves.
The problem I am having however is attempting to generate a list of possible moves for a board.
My problem code is as follows
`... | 2013/03/22 | [
"https://Stackoverflow.com/questions/15576693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/967929/"
] | This line is a problem:
```
tempBoard = genBoard
```
After this line, you seem to think that you have *two* lists -- the original, still referenced
by `genBoard`, and a new one, now referenced by `tempBoard`. This is not the case.
This line does **not** create a copy of the list. Instead, it binds the name `tempBoa... | I belive Python does not create a copy of your Board but just points to the original version. therefore your printout is:
*"MovesList: "
[[0,(X,O,O,O,O,O,O,O,O)],[1,(X,O,O,O,O,O,O,O,O)],[2,(X,O,O,O,O,O,O,O,O)],* etc.
and your genBoard, variable is changed.
to test that add
*print genBoard*
directly before the end... | 13,784 |
47,801 | I am trying to create a web application using Pylons and the resources on the web point to the [PylonsBook](http://pylonsbook.com/alpha1/authentication_and_authorization) page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?
I tried down... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | I don't think AuthKit is actively maintained anymore. It does use the Paste (<http://pythonpaste.org>) libs though for things like HTTP Basic/Digest authentication. I would probably go ahead and take a look at the source for some inspiration and then use the Paste tools if you want to use HTTP authentication.
There i... | This actually got me interested:[Check out this mailing on the pylons list](http://groups.google.com/group/pylons-discuss/browse_thread/thread/644deb53612af362?hl=en). So AuthKit is being developed, and I will follow the book and get back on the results. | 13,785 |
44,532,041 | I want to strip all python docstrings out of a file using simple search and replace, and the following (extremely) simplistic regex does the job for one line doc strings:
[Regex101.com](https://regex101.com/r/PiExji/1)
```
""".*"""
```
How can I extend that to work with multi-liners?
Tried to include `\s` in a num... | 2017/06/13 | [
"https://Stackoverflow.com/questions/44532041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2171758/"
] | As you cannot use an inline `s` (DOTALL) modifier, the usual workaround to match any char is using a character class with opposite shorthand character classes:
```
"""[\s\S]*?"""
```
or
```
"""[\d\D]*?"""
```
or
```
"""[\w\W]*?"""
```
will match `"""` then any 0+ chars, as few as possible as `*?` is a lazy qua... | Sometimes there are multiline strings that are not docstrings. For example, you may have a complicated SQL query that extends across multiple lines. The following attempts to look for multiline strings that appear before class definitions and after function definitions.
```
import re
input_str = """'''
This is a clas... | 13,790 |
43,970,466 | I tried using the below python code to find the websites of the companies. But after trying few times, I face a **Service Unavailable** error.
I have finished the first level of finding the possible domains of the companies. For example :
CompanyExample [u'<http://www.examples.com/>', u'<https://www.example.com/quot... | 2017/05/15 | [
"https://Stackoverflow.com/questions/43970466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7664428/"
] | If you need to check a specific permission try
```
{% if user.hasPermission('administer nodes') %}
<div class="foo"><a href="/">Shorthand link for admins</a></div>
{% endif %}
``` | If you try to check the current user is administer in TWIG file , you can use
```
{% if is_admin %}
<div class="foo"><a href="/">Shorthand link for admins</a></div>
{% endif %}
``` | 13,791 |
2,731,871 | I have a web application in python wherein the user submits their email and password. These values are compared to values stored in a mysql database. If successful, the script generates a session id, stores it next to the email in the database and sets a cookie with the session id, with allows the user to interact with... | 2010/04/28 | [
"https://Stackoverflow.com/questions/2731871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/301860/"
] | You can encode the expiration time as part of your session id.
Then when you validate the session id, you can also check if it has expired, and if so force the user to log-in again.
You can also clean your database periodically, removing expired sessions. | You'd have to add a timestamp to the session ID in the database to know when it ran out.
Better, make the timestamp part of the session ID itself, eg.:
```
Set-Cookie: session=1272672000-(random_number);expires=Sat, 01-May-2010 00:00:00 GMT
```
so that your script can see just by looking at the number at the front ... | 13,792 |
47,412,723 | I'm new in python and I am trying to build a script that gets as an argument a URL and send a GET request to the website and then print the details from the response and the HTML body as well.
The code I wrote:
```
import sys
import urllib.request
url = 'https://%s' % (sys.argv[1])
res = urllib.request.urlopen(url)
... | 2017/11/21 | [
"https://Stackoverflow.com/questions/47412723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You have to handle array of elements separately:
```
var formToJSON = elements => [].reduce.call(elements, (data, element) => {
var isArray = element.name.endsWith('[]');
var name = element.name.replace('[]', '');
data[name] = isArray ? (data[name] || []).concat(element.value) : element.value;
return data;
},... | If you want to convert form data into json object, try the following
```
var formData = JSON.parse(JSON.stringify($('#frm').serializeArray()));
``` | 13,793 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.