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 |
|---|---|---|---|---|---|---|
53,185,119 | I want to retrieve the list of resources are currently in used region wise by using python script and boto3 library.
for example script have to give me the out put as follows
Region : us-west-2
service: EC2
//resource list//instance ids //Name
service: VPC
//resource list//VPC ids//Name | 2018/11/07 | [
"https://Stackoverflow.com/questions/53185119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4108278/"
] | There's no easy way to do it, but you can achieve this with a few describe calls.
First enumerate through the regions that you use:
```
for regionname in ["us-east-1", "eu-west-1"]
```
Or if you want to check all:
```
ec2client = boto3.client('ec2')
regionresponse = ec2client.describe_regions()
for region in regio... | There is no way to obtain a list of all resources used. You would need to write it yourself.
Alternatively, there are third-party companies offering services that will do this for you (eg [Hava](https://www.hava.io/). | 9,145 |
32,714,656 | This a recuring question and i've read many topics some helped a bit ([python Qt: main widget scroll bar](https://stackoverflow.com/questions/2130446/python-qt-main-widget-scroll-bar), [PyQt: Put scrollbars in this](https://stackoverflow.com/questions/14159337/pyqt-put-scrollbars-in-this)), some not at all ([PyQt addin... | 2015/09/22 | [
"https://Stackoverflow.com/questions/32714656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862605/"
] | There are several things wrong with the example code. The main problems are that you are not using layouts properly, and the content widget is not being added to the scroll-area.
Below is a fixed version (the commented lines are all junk, and can be removed):
```
def setupUi(self, Interface):
# Interface.setObjec... | The scrollbars are grayed out because you made them always visible by setting the scrollbar policy to `Qt.ScrollBarAlwaysOn` but actually there is no content to be scrolled so they are disabled. If you want scrollbars to appear only when they are needed you need to use `Qt.ScrollBarAsNeeded`.
There is no content to b... | 9,148 |
52,456,516 | I am doing a list comprehension in python 3 for list of list serially numbers according to given range. My code works fine with but problem is with big range it slows down and take a lot of time. I there any way to do it other way? I don't want to use numpy.
```
global xy
xy = 0
a = 3
def func(x):
global xy
... | 2018/09/22 | [
"https://Stackoverflow.com/questions/52456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4217784/"
] | In exactly the form you asked
```
[list(range(x, x + a)) for x in range(1, a**2 + 1, a)]
```
**Optimizations**
If you're only iterating over inner list elements
```
(range(x, x + a) for x in range(1, a**2 + 1, a))
```
If you're only indexing inner elements (for indices `inner` and `outer`)
```
range(1, a**2 + 1... | Try:
```
t = [list(range(a*i + 1, a*(i+1) + 1)) for i in range(a)]
```
It seems pretty fast for a>100 even, though not fast enough for inside a graphical loop or event handler | 9,149 |
18,464,237 | I've have been making changes and uploading them for testing on AppEngine Python 2.7 runtime.
When uploading I only get as far as seeing the message "Getting current resource limits". The next expected message is "Scanning files on local disk", but this never comes, I always get an error instead.
My last successful d... | 2013/08/27 | [
"https://Stackoverflow.com/questions/18464237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/498463/"
] | I encountered the same problem. Fortunately, I was able to deploy the project successfully.
Just stop the **appengine** from running your project and try to deploy it again.
Hope this helps. | You wouldn't believe it.... I tried deploying again just before posting this question. Everything the same and it works now.
12:30 UK time.... so just a bit of an AppEngine issue? Did anyone else run into this?
Can anyone explain what was going on? I can't be affording to spend 90 minutes messing about everytime I wa... | 9,152 |
61,770,551 | I have a Django project running on my local machine with dev server `manage.py runserver` and I'm trying to run it with Uvicorn before I deploy it in a virtual machine. So in my virtual environment I installed `uvicorn` and started the server, but as you can see below it fails to find Django static css files.
```
(env... | 2020/05/13 | [
"https://Stackoverflow.com/questions/61770551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3423825/"
] | When not running with the built-in development server, you'll need to either
* use [whitenoise](http://whitenoise.evans.io/en/stable/) which does this as a Django/WSGI middleware (my recommendation)
* use [the classic staticfile deployment procedure which collects all static files into some root](https://docs.djangopr... | Add below code your settings.py file
```
STATIC_ROOT = os.path.join(BASE_DIR, 'static', )
```
Add below code in your urls.py
```
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [.
.....] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
```
Then run below... | 9,153 |
50,396,802 | I want to check if an arg was actually passed on the command line when there is a default value for that arg.
Specifically in my case, I am using SCons and scons has a class which inherits from pythons optparse. So my code is like this so far:
```
from SCons.Environment import Environment
from SCons.Script.SConsOptio... | 2018/05/17 | [
"https://Stackoverflow.com/questions/50396802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644736/"
] | Figured it out.
I didn't add my redirect uri to the list of authorized ones as the option doesn't appear if you set your app type to "Other". I set it to "Web Application" (even though it isn't) and added my redirect uri and that fixed it. | Your code snippet lists "<https://googleapis.com/oauth/v4/token>".
The token endpoint is "<https://googleapis.com/oauth2/v4/token>". | 9,154 |
21,678,165 | it's still not a year that i code in python in my spare time, and it is my first programming language. I need to generate serie of numbers in range ("1, 2, 3...99; 1, 2, 3...99;" ) and match them against a list. I managed to do this but the code looks pathetic and i failed in some tasks, for example by skipping series ... | 2014/02/10 | [
"https://Stackoverflow.com/questions/21678165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1348293/"
] | thanks to user2357112 suggestion on using itertools.permutations(xrange(a, b), 4) I did the following and i'm very satisfied, it is fast and nice:
```
def solution(d, a, q):
for i in itertools.permutations(xrange(d, a), q):
#do something
solution(1,100,4)
```
Thanks to this brilliant community as well. | Create array[100], fill it numbers from 0 to 99. Then use random generator to mix them. And then just take needed number of numbers. | 9,159 |
50,595,357 | I have a question of while in python.
How to collect the result values using while?
```
ColumnCount_int = 3
while ColumnCount_int > 0 :
ColumnCount_text = str('<colspec colnum="'+ str(ColumnCount_int) +'"' ' ' 'colname="'+ str(ColumnCount_int) + '">')
Blank_text = ""
Blank_text = Blank_text + ColumnCount_t... | 2018/05/30 | [
"https://Stackoverflow.com/questions/50595357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9817554/"
] | You can fix the code by following where `Blank_text = ""` is moved before `while loop` and `print(Blank_text)` is called after the `loop`.
(**Note**: *since `Blank_text` accumulates, variable name changed to `accumulated_text` as suggested in the comment*):
```
ColumnCount_int = 3
accumulated_text = "" # variable nam... | Try appending it to the new list i created `l`, then do [`''.join(l)`](https://www.tutorialspoint.com/python3/string_join.htm) to output it in one line :
```
l = []
ColumnCount_int = 3
while ColumnCount_int > 0 :
ColumnCount_text = str('<colspec colnum="'+ str(ColumnCount_int) +'"' ' ' 'colname="'+ str(ColumnCou... | 9,160 |
61,027,226 | I have already translated in this project in the same way a number of similar templates in the same directory, which are nearly equal to this one. But this template makes me helpless.
Without a translation tag `{% blocktrans %}` it properly works and renders the variable.
[.But I think that i have problem in python 3.5. Can anyone help me with this error?
[... | 2018/01/22 | [
"https://Stackoverflow.com/questions/48376714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9250190/"
] | It happened to me. Just copy the "object\_detection" folder from "models" folder into the folder where you are running the train.py. I posted the link to the folder from github but you better copy the folder from your local files so it will match with your code perfectly in case you are using an older version of the ob... | Move the object\_detection folder to upper folder
cp /models/research/object\_detection object\_detection | 9,162 |
24,469,353 | New to python so...
I have a list with two columns, like so:
```
>>>print langs
[{u'code': u'en', u'name': u'ENGLISH'}, {u'code': u'hy', u'name': u'ARMENIAN'}, ... {u'code': u'ms', u'name': u'MALAY'}]
```
I would like to add another row with:
code: xx and name: UNKNOWN
Tried with `langs.append` and so on, but ca... | 2014/06/28 | [
"https://Stackoverflow.com/questions/24469353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1662464/"
] | It's pretty easy:
```
>>> langs.append({u'code': u'xx', u'name': u'UNKNOWN'})
```
But I'd use `collections.namedtuple` for this kind of job(when columns are well-defined):
```
In [1]: from collections import namedtuple
In [2]: Lang = namedtuple("Lang", ("code", "name"))
In [3]: langs = []
In [4]: langs.append(Lang(... | This is one way of doing it...
```
langs += [{u'code': u'xx', u'name': u'UNKNOWN'}]
``` | 9,163 |
74,006,179 | i'm new to python and i got a problem with dictionary filter.
I searched a really long time for solution and asked on several discord server, but no one could really help me.
If i have a dictionary like this:
```
[
{"champion": "ahri", "kills": 12, "assists": 7, "deaths": 4, "puuid": "17hd72he7wu"}
{"champion... | 2022/10/09 | [
"https://Stackoverflow.com/questions/74006179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20198636/"
] | use a list comprehension and cycle through the dictionaries in your list to only keep the one that meets the specified conditions.
```
[
{"champion": ahri, "kills": 12, "assists": 7, "deaths": 4, "puuid": 17hd72he7wu}
{"champion": sett, "kills": 14, "assists": 5, "deaths": 7, "puuid": 2123r3ze7wu}
{"champion": thresh,... | you want something like this:
new\_list = [ x for x in orgininal\_list if x[puuid] == value ]
its called a list comprehension | 9,164 |
73,323,330 | so im learning some python but i got a list out of index error at this point if i put my header index to 0 it works not the way i see it works but ok, but if i get an upper index for header it wont can you help me out why?[photo of my csv file](https://i.stack.imgur.com/cDD13.png)
[heres the first picture of my code][... | 2022/08/11 | [
"https://Stackoverflow.com/questions/73323330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19744452/"
] | When you put your header index as `0` what is output?
Assuming your delimiter is `tab`
```py
with open("sample.csv", "r") as csvfile:
reader = csv.reader(csvfile,delimiter='\t')
headers = next(reader, None)
print(headers[1])
``` | My delimeter was \t after i changed it to it problem all solved | 9,167 |
67,933,453 | I have a file that consists of data shown below
```
GS*642510*18762293*0*0*0*0*0*0*0*HN*056000522*601200162*20210513*101046*200018825*X*005010X214
ST*642510*18762293*1*0*0*0*0*0*0*277*000000001*005010X214
BHT*642510*18762293*1*0*0*0*0*0*0*0085*08*1*20210513*101046*TH
NM1*642510*18762293*1*1*1*1*1*0*0*QC*1*TORIBIO ... | 2021/06/11 | [
"https://Stackoverflow.com/questions/67933453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15153070/"
] | <https://regex101.com/r/khgAVj/1>
[](https://i.stack.imgur.com/5Ru4N.png)
regex pattern: `(\*\w+){9}\*`
Explanation of the regex pattern can be found on the regex101 page on the right side.
There is a code generator and replacing/removing the sec... | You could write a regular expression to solve this, but if you know that you always want to remove the content between the first and ninth stars, then I would split your strings into lists by "\*" and rejoin select slices. For example:
```py
mystring = "GS*642510*18762293*0*0*0*0*0*0*0*HN*056000522*601200162*20210513*... | 9,168 |
58,335,344 | I want scheduled to run my python script every hour and save the data in elasticsearch index. So that I used a function I wrote, set\_interval which uses the tweepy library. But it doesn't work as I need it to work. It runs every minute and save the data in index. Even after the set that seconds equal to 3600 it runs i... | 2019/10/11 | [
"https://Stackoverflow.com/questions/58335344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11931186/"
] | Why do you need so much complexity to do some task every hour? You can run script every one hour this way below, note that it is runned 1 hour + time to do work:
```
import time
def do_some_work():
print("Do some work")
time.sleep(1)
print("Some work is done!")
if __name__ == "__main__":
time.sleep(6... | Get rid of all timer code just write the logic and
**cron** will do the job for you add this to the end of the file after `crontab -e`
```
0 * * * * /path/to/python /path/to/script.py
```
`0 * * * *` means run at every *zero* minute you can find more explanation [here](https://www.computerhope.com/unix/ucrontab.htm)... | 9,171 |
40,753,137 | suppose I have a list which calls name:
name=['ACCBCDB','CCABACB','CAABBCB']
I want to use python to remove middle B from each element in the list.
the output should display :
['ACCCDB','CCAACB','CAABCB'] | 2016/11/22 | [
"https://Stackoverflow.com/questions/40753137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6169548/"
] | It is not possible to test for `NULL` values with comparison operators, such as `=`, `<`, or `<>`.
You have to use the `IS NULL` and `IS NOT NULL` operators instead, or you have to use functions like `ISNULL()` and `COALESCE()`
```
Select * From MyTableName where [boolfieldX] <> 1 OR [boolfieldX] IS NULL
```
**OR**... | Hi try to use this query:
```
select * from mytablename where [boolFieldX] is null And [boolFieldX] <> 1
``` | 9,172 |
28,530,928 | I am trying to have a python script execute on the click of an image but whenever the python script gets called it always throws a 500 Internal Server Error? Here is the text from the log
```
[Sun Feb 15 20:31:04 2015] [error] (2)No such file or directory: exec of '/var/www/forward.py' failed
[Sun Feb 15 20:31:04 201... | 2015/02/15 | [
"https://Stackoverflow.com/questions/28530928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4547894/"
] | Things to check:
1. Make sure the script is executable (`chmod +x forward.py`) and that it has a she-bang line (e.g. `#!/usr/bin/env python`).
2. Make sure the script's owner & group match up with what user apache is running as.
3. Try running the script from the command line as the apache user. I see that you're test... | In addition to @lost-theory's recommendations, I would also check to make sure:
* You have executable permission on the script.
* Apache has permission to access the folder/file of the script. For example:
```
<Directory /path/to/your/dir>
<Files *>
Order allow,deny
Allow from all
Require all granted... | 9,175 |
44,579,050 | I am using python and OpenCV. I am trying to find the center and angle of the batteries:
[Image of batteries with random angles:](https://i.stack.imgur.com/qB8S7.jpg)
[](https://i.stack.imgur.com/DgD8p.jpg)
The code than I have is this:
```
import c... | 2017/06/16 | [
"https://Stackoverflow.com/questions/44579050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8093906/"
] | Almost identical to [one of my other answers](https://stackoverflow.com/questions/43863931/contour-axis-for-image/43883758#43883758). PCA seems to work fine.
```
import cv2
import numpy as np
img = cv2.imread("test_images/battery001.png") #load an image of a single battery
img_gs = cv2.cvtColor(img, cv2.COLOR_BGR2GR... | You can reference the code.
```
import cv2
import imutils
import numpy as np
PIC_PATH = r"E:\temp\Battery.jpg"
image = cv2.imread(PIC_PATH)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 100, 220)
kernel = np.ones((5,5),np.uint8)
closed =... | 9,176 |
22,948,119 | i am trying to make a program for my computer science class that has us create a lottery game generator. this game has you input your number, then it creates tickets winning tickets to match to your ticket. so if you match 3, it says you matched 3, 4 says 4, 5 says 5 and at 6 matches it will stop the program. my proble... | 2014/04/08 | [
"https://Stackoverflow.com/questions/22948119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3512754/"
] | ```
from random import randint, sample
# Ontario Lotto 6/49 prize schedule
COST = 0.50
PRIZES = [0, 0, 0, 5., 50., 500., 1000000.]
def draw():
return set(sample(range(1, 50), 6))
def get_ints(prompt):
while True:
try:
return [int(i) for i in input(prompt).split()]
except ValueErro... | just keep a record of what you have seen
```
...
costs=0
found = []
while True:
...
if matches==3 and 3 not in found:
found.append(3)
print ("You Matched 3 on try", costs)
elif matches==4 add 4 not in found:
found.append(4)
print ("Cool! 4 matches on try", costs)
...
... | 9,179 |
7,533,677 | ```
a.zip---
-- b.txt
-- c.txt
-- d.txt
```
Methods to process the zip files with Python,
I could expand the zip file to a temporary directory, then process each txt file one bye one
Here, I am more interested to know whether or not python provides such a way so that
I don't have to manually expan... | 2011/09/23 | [
"https://Stackoverflow.com/questions/7533677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391104/"
] | The [Python standard library](http://docs.python.org/library/zipfile.html) helps you.
Doug Hellman writes very informative posts about selected modules: <https://pymotw.com/3/zipfile/>
To comment on Davids post: From Python 2.7 on the Zipfile object provides a context manager, so the recommended way would be:
```
im... | Yes you can process each file by itself. Take a look at the tutorial [here](http://effbot.org/librarybook/zipfile.htm). For your needs you can do something like this example from that tutorial:
```
import zipfile
file = zipfile.ZipFile("zipfile.zip", "r")
for name in file.namelist():
data = file.read(name)
pri... | 9,180 |
58,381,152 | In training a neural network in Tensorflow 2.0 in python, I'm noticing that training accuracy and loss change dramatically between epochs. I'm aware that the metrics printed are an average over the entire epoch, but accuracy seems to drop significantly after each epoch, despite the average always increasing.
The loss... | 2019/10/14 | [
"https://Stackoverflow.com/questions/58381152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4607066/"
] | It seems this phenomenon comes from the fact that the model has a high batch-to-batch variance in terms of accuracy and loss. This is illustrated if I take a graph of the model with the actual metrics per step as opposed to the average over the epoch:
[ doens't work in Windows with mixed slashes. But kerastuner forms the path with backslashes. So I sh... | The problem it would appear is a Windows issue. Running the same code in a Linux environment had no issue in this regard. | 9,182 |
54,547,986 | I couldn't figure out why I'm getting a `NameError` when trying to access a function inside the class.
This is the code I am having a problem with. Am I missing something?
```
class ArmstrongNumber:
def cubesum(num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(num):
if... | 2019/02/06 | [
"https://Stackoverflow.com/questions/54547986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10361602/"
] | Use `classname` before method:
```
class ArmstrongNumber:
def cubesum(num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(num):
if ArmstrongNumber.cubesum(num) == num:
return "Armstrong Number"
return "Not an Armstrong Number"
def Armstrong(num):
... | this should be your actual solution if you really want to use class
```
class ArmstrongNumber(object):
def cubesum(self, num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(self, num):
if self.cubesum(num) == num:
return "Armstrong Number"
return "Not ... | 9,184 |
32,562,253 | I am trying to run multiple calculations with UI using Tkinter in python where i have to display all the outputs for all the calculations. The problem is, the output for the first calculation is fine but the outputs for further calculations seems to be calculated out of default values. I came to know that i should dest... | 2015/09/14 | [
"https://Stackoverflow.com/questions/32562253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5325381/"
] | Temporary tables always gets created in TempDb. However, it is not necessary that size of TempDb is only due to temporary tables. TempDb is used in various ways
1. Internal objects (Sort & spool, CTE, index rebuild, hash join etc)
2. User objects (Temporary table, table variables)
3. Version store (AFTER/INSTEAD OF tr... | Perhaps you can use following SQL command on temp db files seperately
```
DBCC SHRINKFILE
```
Please refer to <https://support.microsoft.com/en-us/kb/307487> for more information | 9,185 |
5,440,550 | The sample application on the android developers site validates the purchase json using java code. Has anybody had any luck working out how to validate the purchase in python. In particular in GAE?
The following are the relevant excerpts from the android in-app billing [example program](http://developer.android.com/gu... | 2011/03/26 | [
"https://Stackoverflow.com/questions/5440550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677760/"
] | Here's how i did it:
```
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from base64 import b64decode
def chunks(s, n):
for start in range(0, len(s), n):
yield s[start:start+n]
def pem_format(key):
return '\n'.join([
'-----BEGIN PUBLIC KEY-... | I finally figured out that your base64 encoded public key from Google Play is an X.509 subjectPublicKeyInfo DER SEQUENCE, and that the signature scheme is RSASSA-PKCS1-v1\_5 and not RSASSA-PSS. If you have [PyCrypto](https://www.dlitz.net/software/pycrypto/) installed, it's actually quite easy:
```
import base64
from ... | 9,186 |
44,972,219 | I’m pretty new to Python and I just start to understand the basics.
I’m trying to run a script in a loop to check the temperatures and if the outside temp getting higher than inside or the opposite, the function should print it once and continue to check every 5 seconds, for changed state.
I found a similar [questions]... | 2017/07/07 | [
"https://Stackoverflow.com/questions/44972219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8271048/"
] | Its been long time, but for future readers thought to share some info.
There is a good article that explains the `getItemLayout`, please find it [here](https://medium.com/@jsoendermann/sectionlist-and-getitemlayout-2293b0b916fb)
I also faced `data[index]` as `undefined`. The reason is that `index` is calculated consi... | For some reason the `react-native-get-item-layout` package keeps crashing with `"height: <<NaN>>"` so I had to write my [own RN SectionList getItemLayout](https://npmjs.com/package/sectionlist-get-itemlayout) . It uses the same interface as the former.
Like the `package` it's also an `O(n)`. | 9,189 |
9,866,923 | I'm trying to solve this newbie puzzle:
I've created this function:
```
def bucket_loop(htable, key):
bucket = hashtable_get_bucket(htable, key)
for entry in bucket:
if entry[0] == key:
return entry[1]
return None
```
And I have to call it in two ot... | 2012/03/26 | [
"https://Stackoverflow.com/questions/9866923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/955883/"
] | In general, there are three things you can do:
1. Write “setter” functions (ex, `bucket_set`)
2. Return mutable values (ex, `bucket_get(table, key).append(42)` if the value is a `list`)
3. Use a class which overrides `__getitem__` and `__setitem__`
For example, you could have a class like like:
```
class Bucket(obje... | One option that would require few changes would be adding a third argument to `bucket_loop`, optional, to use for assignment:
```
empty = object() # An object that's guaranteed not to be in your htable
def bucket_loop(htable, key, value=empty):
bucket = hashtable_get_bucket(htable, key)
for entry in bucket:
... | 9,191 |
62,065,607 | I run into problems when calling Spark's MinHashLSH's approxSimilarityJoin on a dataframe of (name\_id, name) combinations.
**A summary of the problem I try to solve:**
I have a dataframe of around 30 million unique (name\_id, name) combinations for company names. Some of those names refer to the same company, but a... | 2020/05/28 | [
"https://Stackoverflow.com/questions/62065607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12383245/"
] | `approxSimilarityJoin` will only parallelize well across workers if the tokens being input into MinHash are sufficiently distinct. Since individual character tokens appear frequently across many records; include an `NGram` transformation on your character list to make the appearance of each token less frequent; this wi... | Thanks for the detailed explanation.
What threshold are you using a and how are reducing false -ve? | 9,194 |
29,970,679 | I have this simple code in Python:
```
import sys
class Crawler(object):
def __init__(self, num_of_runs):
self.run_number = 1
self.num_of_runs = num_of_runs
def single_run(self):
#do stuff
pass
def run(self):
while self.run_number <= self.num_of_runs:
self.single_run()
print s... | 2015/04/30 | [
"https://Stackoverflow.com/questions/29970679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717289/"
] | ```
num_of_runs = sys.argv[1]
```
`num_of_runs` is a string at that stage.
```
while self.run_number <= self.num_of_runs:
```
You are comparing a `string` and an `int` here.
A simple way to fix this is to convert it to an int
```
num_of_runs = int(sysargv[1])
```
Another way to deal with this is to use `argpar... | When accepting input from the command line, data is passed as a string. You need to convert this value to an `int` before you pass it to your `Crawler` class:
```
num_of_runs = int(sys.argv[1])
```
---
You can also utilize this to determine if the input is valid. If it doesn't convert to an int, it will throw an er... | 9,196 |
54,873,222 | I have a scenario where the data is like below in a text file:
```
first_id;"second_id";"name";"performer";"criteria"
12345;"13254";"abc";"def";"criteria_1"
65432;"13254";"abc";"ghi";"criteria_1"
24561;"13254";"abc";"pqr";"criteria_2"
24571;"13254";"abc";"jkl";"criteria_2"
first_id;"second_id";"name";"performer";"cri... | 2019/02/25 | [
"https://Stackoverflow.com/questions/54873222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6909182/"
] | Here's a general answer that will scale up to as many data frames as you have:
```
library(dplyr)
df_list = list(df5 = df5, df6 = df6)
library(dplyr)
big_df = bind_rows(df_list, .id = "source")
big_df = big_df %>% group_by(Year) %>% summarize_if(is.numeric, mean) %>%
mutate(source = "Mean") %>%
bind_rows(big_df)
... | If I understand you right, you would like to plot for the year 2013 10,054185
If you have for every year one line you can create a new col and add this to your existing ggplot:
```
df <- dataframe5$Year
df$total5 <- dataframe5$Total
df$total6 <- dataframe6$Total
df$totalmean <- (df$total5+df$total6)/2
```
By plotti... | 9,197 |
41,951,204 | I am new to python. I'm trying to connect my client with the broker. But I am getting an error "global name 'mqttClient' is not defined".
Can anyone help me to what is wrong with my code.
Here is my code,
**Test.py**
```
#!/usr/bin/env python
import time, threading
import mqttConnector
class UtilsThread(object):
... | 2017/01/31 | [
"https://Stackoverflow.com/questions/41951204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7134849/"
] | * **For MongoDB -**
Use AWS quick start MongoDB
<http://docs.aws.amazon.com/quickstart/latest/mongodb/overview.html>
<http://docs.aws.amazon.com/quickstart/latest/mongodb/architecture.html>
* **For rest of the docker stack i.e NodeJS & Nginx -**
Use the AWS ElasticBeanstalk Multi Container Deployment
<http://docs.aw... | Elastic Beanstalk supports Docker, as [documented here](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_docker.html). Elastic Beanstalk would manage the EC2 resources for you so that you, which should make things a bit easier on you. | 9,198 |
59,904,969 | Introduction
============
I want to combine my separate Minecraft worlds into a single world and it seemed like a relatively easy feat, but as I did research it evolved into the need to make a custom program.
The Struggle
------------
I started by shifting the region files and combining them in one region folder, wh... | 2020/01/24 | [
"https://Stackoverflow.com/questions/59904969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12778238/"
] | First of: As far as I know there is no more information about "where the chunks are", stored in the region files. There are 32(x direction)\*32(z-direction)= 1024 Chunks stored within one region file and each of it has its position of data within the file. So the chunks are just numbered within the file itself and the ... | I found an editor!
==================
Now I can *edit*, but I don't know *how* the editing works. I haven't *learned* anything, but I did finally find someone else's editor. Not quite what I wanted because I wanted to know how to do this myself.
**Update:** To fix a region using this software I have to manually edit... | 9,200 |
34,344,171 | Getting a strange error. I created a database in MySQL, set the database to use it. Using the right settings in my Django settings.py. But still there's an error that no database has been selected.
**First I tried:**
```
python manage.py syncdb
```
**Got this traceback:**
```
django.db.utils.OperationalError: (104... | 2015/12/17 | [
"https://Stackoverflow.com/questions/34344171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2058553/"
] | Check to make sure your database my\_db exists in your MySQL instance. Log into MySQL and run;
```
show databases;
```
make sure my\_db exists. If it does not, run
```
create database my_db;
``` | GRANT access privileges to the user mentioned in the file
```
GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';
```
You need not grant all privileges. modify accordingly. | 9,202 |
35,189,234 | I am trying to seed an instance of pythons random. However when I run the code below it generates a different answer each time even if user input stays the same.
```
import random
import hashlib
mapSeed = hashlib.sha1(input("Enter seed: ").encode('utf-8'))
rnd = random.Random()
rnd.seed(mapSeed)
print(mapSeed)
print(... | 2016/02/03 | [
"https://Stackoverflow.com/questions/35189234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4831464/"
] | Assuming that the seed remains constant during all executions, it will never change. Look at this:
```
>>> import random
>>> r = random.Random()
>>> r.seed(515)
>>> r.random()
0.1646746342919
>>> r.random()
0.9567223584846931
>>> r.seed(515)
>>> r.random()
0.1646746342919
>>> r.random()
0.9567223584846931
```
Howeve... | One very important concept regarding "random numbers" is that are not actually random, they are dependent of:
1) Algorithm used to generate the "random" sequence of numbers
2) The seed for the algorithm
The same seed will generate the same sequence of random numbers. Why? Because if you can have the same stream of ran... | 9,203 |
38,772,498 | I am running the command in my django project:-
```
$python manage.py runserver
```
then I am getting the error like:-
```
from django.core.context_processors import csrf
ImportError: No module named context_processors
```
here is results of
```
$ pip freeze
dj-database-url==0.4.1
dj-static==0.0.6
Django==1.10... | 2016/08/04 | [
"https://Stackoverflow.com/questions/38772498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6623406/"
] | The `csrf` module is moved from `django.core.context_processors` to `django.views.decorators` in the latest release. You can refer it [here](https://docs.djangoproject.com/ja/1.9/ref/csrf/) | `context_processors` in Django 1.10 and above has been moved from `core` to `template`.
Replace
```
django.core.context_processors
```
with
```
django.template.context_processors
``` | 9,206 |
965,663 | We've had these for a lot of other languages. The one for [C/C++](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) was quite popular, so was the equivalent for [Python](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets). I thought one for BASH would be interesti... | 2009/06/08 | [
"https://Stackoverflow.com/questions/965663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In a BASH script, assign an argument to variable but provide a default if it exists:
```
MYVAR=${1:-default}
```
$MYVAR will contain the first argument if one was given else "default". | To remove .svn directories you may also use the combination 'find...-prune...-exec...' (without xargs):
```
# tested on Mac OS X
find -x -E . \( -type d -regex '.*/\.svn/*.*' -prune \) -ls # test
find -x -E . \( -type d -regex '.*/\.svn/*.*' -prune \) -exec /bin/rm -PRfv '{}' \;
``` | 9,207 |
2,980,031 | I am using a module that is part of a commercial software API. The good news is there is a python module - the bad news is that its pretty unpythonic.
To iterate over rows, the follwoing syntax is used:
```
cursor = gp.getcursor(table)
row = cursor.next()
while row:
#do something with row
row = cursor.next(... | 2010/06/05 | [
"https://Stackoverflow.com/questions/2980031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103225/"
] | Assuming that one of Next and next is a typo and they're both the same, you can use the not-so-well-known variant of the built-in iter function:
```
for row in iter(cursor.next, None):
<do something>
``` | The best way is to use a Python iterator interface around the `table` object, imho:
```
class Table(object):
def __init__(self, table):
self.table = table
def rows(self):
cursor = gp.get_cursor(self.table)
row = cursor.Next()
while row:
yield row
row =... | 9,217 |
74,466,125 | Pyhton is new to me and i'm having a little problem with the for loops,
Im used to for loop in java where you can set integers as you like in the loops but can't get it right in python.
the task i was given is to make a function that return True of False.
the function get 3 integers: short rope amount, long ro... | 2022/11/16 | [
"https://Stackoverflow.com/questions/74466125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523368/"
] | Use a nested list comprehension:
```
pd.DataFrame([[k1, k2, v]
for k1,d in sample_dict.items()
for k2,v in d.items()],
columns=['job', 'person', 'age'])
```
Output:
```
job person age
0 doctor docter_a 26
1 doctor docter_b 40
2 doctor docter_c ... | You can construct a `zip` of length 3 elements, and feed them to `pd.DataFrame` after reshaping:
```
zip_list = [list(zip([key]*len(sample_dict['doctor']),
sample_dict[key],
sample_dict[key].values()))
for key in sample_dict.keys()]
col_len = len(sample_dict['doctor'])... | 9,220 |
19,551,186 | How do I let the user write text in my python program that will transfer into a file using open "w"?
I only figured out how write text into the seperate document using print. But how is it done if I want input to be written to a file? In short terms: Let the user itself write text to a seperate document.
Here is my c... | 2013/10/23 | [
"https://Stackoverflow.com/questions/19551186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2877270/"
] | First off, use raw\_input instead of input. This way you capture the text as a string instead of trying to evaluate it. But to answer your question:
```
with open(name, 'w') as o:
o.write(code)
```
You can also surround that code in a loop that keeps repeating until the user hits a certain key if you would like ... | ```
def main():
print ("This program let you create your own HTML-page")
name = input("Enter the name for your HTML-page (end it with .html): ")
outfile = open(name),'w')
code = input ("Enter your code here: ")
outfile.write(code)
main ()
```
This does not accept multi line code entries. You... | 9,221 |
61,624,276 | I'm looking for a pythonic way to define multiple related constants in a single file to be used in multiple modules. I came up with multiple options, but all of them have downsides.
### Approach 1 - simple global constants
```py
# file resources/resource_ids.py
FOO_RESOURCE = 'foo'
BAR_RESOURCE = 'bar'
BAZ_RESOURCE ... | 2020/05/05 | [
"https://Stackoverflow.com/questions/61624276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/895490/"
] | Use `Enum` and mix in `str`:
```
@unique
class ResourceIds(str, Enum):
foo = 'foo'
bar = 'bar'
baz = 'baz'
qux = 'qux'
```
Then you won't need to compare against `.value`:
```
>>> ResourceIds.foo == 'foo'
True
```
And you still get good debugging info:
```
>>> ResourceIds.foo
<ResourceIds.foo: 'f... | A few ways you can do this, I don't really like using enum in python because you dont *really* need them IMO ;)
This is how most packages out there do it AFAIK:
```
# module_name.py
CSV = 'csv'
JSON = 'json'
def save(path, format=CSV):
# do some thing with format
...
# other_module.py
import module_name
mo... | 9,222 |
45,836,369 | I know what iterators and generators are. I know the iteration protocol, and I can create both. I read the following line everywhere: "Every generator is an iterator, but not vice versa." I understand the first part, but I don't understand the "not vice versa" part. What does the generator object have that any simple i... | 2017/08/23 | [
"https://Stackoverflow.com/questions/45836369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5567387/"
] | In python3 an iterator is an object with a `__next__` method. That's all.
For an object to be a generator it needs `__next__` method but it also use a yield statement.
So both object have a `__next__` method and so are iterator but the first object doesn't always have a yield statement so an iterator is not necessari... | It's just that generators are a specific kind of iterators.
Their two particular traits are the lazy evaluation (no value is computed in anticipation of it being requested), and the fact that once exhausted, they cannot be iterated once again.
On the other hand, an iterator is no more than something with a `__next__` ... | 9,223 |
51,129,487 | I'm using `django-notification` to create notifications. based on [it's documention](https://github.com/django-notifications/django-notifications) I putted:
```
url(r'^inbox/notifications/', include(notifications.urls, namespace='notifications')),
```
in my `urls.py`. I generate a notification for test by using this... | 2018/07/02 | [
"https://Stackoverflow.com/questions/51129487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2454690/"
] | oops! It was my mistake.
I Finally find out what was the problem. `actor_object_id` was the field of `notifications_notification` table, which `User.objects.get(username = 'SirSaleh')` saved in it. It should be `Interger` (`user_id` of actor).
So I dropped previous table changed instance to `User.objects.get(usernam... | This is old, but I happen to know the answer.
In your code, you wrote:
```
guy = User.objects.get(username = 'SirSaleh')
notify.send(sender=User, recipient=guy, verb='you visted the site!')
```
You express that you want `guy` to be your sender However, in `notify.send`, you marked the sender as a generic `User` obj... | 9,226 |
22,725,990 | I always have a hard time understanding the logic of regex in python.
```
all_lines = '#hello\n#monica, how re "u?\n#hello#robert\necho\nfall and spring'
```
I want to retrieve the substring that STARTS WITH `#` until the FIRST `\n` THAT COMES RIGHT AFTER the LAST `#` - I.e., `'#hello\n#monica, how re "u?\n#hello#ro... | 2014/03/29 | [
"https://Stackoverflow.com/questions/22725990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1205745/"
] | This program matches the pattern you request.
```
#!/usr/bin/python
import re
all_lines = '#hello\n#monica, how re "u?\n#hello#robert\necho'
regex = re.compile(
r'''\# # first hash
.* # continues to (note: .* greedy)
\# # last hash
.*?$ # res... | Regular expressions are powerful but sometimes they are overkill. String methods should accomplish what you need with much less thought
```
>>> my_string = '#hello\n#monica, how re "u?\n#hello#robert\necho\nfall and spring'
>>> hash_positions = [index for index, c in enumerate(my_string) if c == '#']
>>> hash_position... | 9,228 |
49,126,184 | i've a docker with redis container
configuration of it
docker-compose.yml
```
# Redis
redis:
image: redis:4.0.6
build:
context: .
dockerfile: dockerfile_redis
volumes:
- "./redis.conf:/usr/local/etc/redis/redis.conf"
ports:
- "6379:6379"
```
dockerfile\_redis
```
CMD ["chown", "redis:redis... | 2018/03/06 | [
"https://Stackoverflow.com/questions/49126184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6488529/"
] | Please check this blogpost:
<https://blog.huntingmalware.com/notes/LLMalware>
It is very likely a malware causing the working directory of your redis to change, and redis tries to write RDB file to a directory owned by root, following the commands of a malicious script. As it does not run from root, and write access... | If you do not really need to expose ports, just remove next lines:
```
ports:
- "6379:6379"
``` | 9,229 |
22,932,789 | Hi I just start learning python today and get to apply what I learning on a flash cards program, I want to ask the user for their name, and only accept alphabet without numbers or symbols, I've tried several ways but there is something I am missing in my attempts. Here is what I did so far.
```
yname = raw_input('Your... | 2014/04/08 | [
"https://Stackoverflow.com/questions/22932789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3510177/"
] | >
> The homepage is fine but the images in the footer are missing in the whole website.
>
>
>
Seems, that problem is with `float: left` in `<li>` elements. Try fixing size of blocks or make elements inline; | The problem is compatibility of your css/javascript with upper versions of IE, [This](https://stackoverflow.com/a/19150943/87956) should help you out.
Above is just a work around better way would be to fix your css and javascript/jquery to take care of compatibility issues. | 9,230 |
3,258,072 | Customizing `pprint.PrettyPrinter`
==================================
The documentation for the `pprint` module mentions that the method `PrettyPrinter.format` is intended to make it possible to customize formatting.
I gather that it's possible to override this method in a subclass, but this doesn't seem to provide a... | 2010/07/15 | [
"https://Stackoverflow.com/questions/3258072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192812/"
] | *This question may be a duplicate of:*
* [Any way to properly pretty-print ordered dictionaries in Python?](https://stackoverflow.com/questions/4301069/any-way-to-properly-pretty-print-ordered-dictionaries-in-python)
---
Using `pprint.PrettyPrinter`
============================
I looked through the [source of pprin... | Consider using the `pretty` module:
* <http://pypi.python.org/pypi/pretty/0.1> | 9,231 |
44,302,426 | In my python package I have a configuration module that reads a yaml file (when creating the instance) at an explicit location, i.e. something like
```
class YamlConfig(object):
def __init__(self):
filename = os.path.join(os.path.expanduser('~'), '.hanzo\\config.yml')
with open(filename) as fs:
... | 2017/06/01 | [
"https://Stackoverflow.com/questions/44302426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2834295/"
] | JSON only supports a limited number of datatypes. If you want to store other types of data as JSON then you need to convert it to something that JSON accepts. The obvious choice for Numpy arrays is to store them as (possibly nested) lists. Fortunately, Numpy arrays have a `.tolist` method which performs the conversion ... | Here is a full working example of an Encoder/Decoder that can deal with NumPy arrays:
```
import numpy
from json import JSONEncoder,JSONDecoder
import json
# ********************************** #
class NumpyArrayEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, numpy.ndarray):
r... | 9,236 |
17,460,215 | I would like to know how I can get my code to not crash if a user types anything other than a number for input. I thought that my else statement would cover it but I get an error.
>
> Traceback (most recent call last): File "C:/Python33/Skechers.py",
> line 22, in
> run\_prog = input() File "", line 1, in NameErro... | 2013/07/04 | [
"https://Stackoverflow.com/questions/17460215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361013/"
] | Contrary to what you think, your script is *not* being run in Python 3.x. Somewhere on your system you have Python 2.x installed and the script is running in that, causing it to use 2.x's insecure/inappropriate `input()` instead. | The error message you showed indicates that `input()` tried to evaluate the string typed as a Python expression. This in turn means you're not actually using Python 3; `input` only does that in 2.x. Anyhow, I strongly recommend you do it this way instead, as it makes explicit the kind of input you want.
```
while time... | 9,237 |
62,028,585 | I have an ML model that predicts a target attribute `y` with `5` other attributes namely `Age`, `Sex`, `Satisfaction`, `Height` and `weight`
Let's say that I have a new dataset **but it is short `Age`** so it has only `4` attributes namely `Sex`, `Satisfaction`, `Height` and `weight`
So that new dataset I am going to... | 2020/05/26 | [
"https://Stackoverflow.com/questions/62028585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11433497/"
] | There are some models that can handle NaN (empty) values, life XGBOOST, and some models that can't.
Your best option here will be to re-train a model with only the 4 features.
If you can't you can give multiple values to "age" (like 2-99), predict y each time, and take the average of those predictions.
Again, you wi... | It's possible to predict y using fewer Xs. You need more data to train your model.
Keep in mind that 1st example in machine learning is to predict y using just one x. | 9,239 |
64,734,616 | I have a **Payment** Django model that has a *CheckNumber* attribute that I seem to be facing issues with, at least whilst mentioning the attribute in the **str** method. It works just fine on the admin page when creating a Payment instance, but as soon as I called it in the method it gave me the following error messag... | 2020/11/08 | [
"https://Stackoverflow.com/questions/64734616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6815773/"
] | Don't.
You have a form. Treat it as such.
```js
document.getElementById('input_listName').addEventListener('submit', function(e) {
e.preventDefault();
const li = document.createElement('li');
li.append(this.listName.value);
document.querySelector(".ul_current").append(li);
// optionally:
// this.listNam... | With the help of the `event`, you can catch the pressed `enter` (keycode = 13) key, as in my example.
Was it necessary?
```
$('#btn_createList').keypress(function(event){
if (event.keyCode == 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
});
``` | 9,240 |
46,195,187 | I am working on a remote server, say IP: 192.128.0.3. On this server there are two folders: `cgi-bin` & `html`. My python code file is in `cgi-bin` which wants to make data.json file in `html/Rohith/` where Rohith folder is already exists. I use the following code
```
jsonObj = json.dumps(main_func(s));
fileobj = op... | 2017/09/13 | [
"https://Stackoverflow.com/questions/46195187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6816478/"
] | It might be path issues; I suggest to use full path instead. Try the following:
```
import os
jsonObj = json.dumps(main_func(s));
path = '\\'.join(__file__.split('\\')[:-2]) # this will return the parent
# folder of cgi-bin on Windows
out_file = path + '/html/Ronhith/dat... | file.write does not create a directory First you have to create a directory then use file.write() for example
```
if not os.path.exists("../html/Rohith/"):
os.makedirs("../html/Rohith/")
jsonObj = json.dumps(mainfunc(s))
fileobj = open("../html/Rohith/data.json","w+")
fileobj.write(jsonObj)
``` | 9,243 |
30,107,212 | I have a deque in Python that I'm iterating over. Sometimes the deque changes while I'm interating which produces a `RuntimeError: deque mutated during iteration`.
If this were a Python list instead of a deque, I would just iterate over a copy of the list (via a slice like `my_list[:]`, but since slice operations can'... | 2015/05/07 | [
"https://Stackoverflow.com/questions/30107212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486484/"
] | You can "freeze" it by creating a list. There's no necessity to copy it to a new deque. A list is certainly good enough, since you only need it for iterating.
```
for elem in list(my_deque):
...
```
`list(x)` creates a list from any iterable `x`, including deque, and in most cases is the most pythonic way to do ... | While you can create a list out of the deque, `for elem in list(deque)`, this is not always optimum if it is a frequently used function: there's a performance cost to it esp. if there is a large number of elements in the deque and you're constantly changing it to an `array` structure.
A possible alternative without n... | 9,246 |
35,876,962 | So I think I know what my problem is but I cant seem to figure out how to fix it. I am relatively new to wxPython. I am moving some functionality I have in a terminal script to a GUI and cant seem to get it right. I use anaconda for my python distribution and have added wxPython for the GUI. I want users to be able to ... | 2016/03/08 | [
"https://Stackoverflow.com/questions/35876962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4996129/"
] | Assuming you don't want window chrome, you can accomplish this by removing the frame around Electron and filling the rest in with html/css/js. I wrote an article that achieves what you are looking for on my blog here: <http://mylifeforthecode.github.io/making-the-electron-shell-as-pretty-as-the-visual-studio-shell/>. C... | I was inspired by Shawn's article and apps like Hyper Terminal to figure out how to exactly replicate the Windows 10 style look as a seamless title bar, and wrote [this tutorial](https://github.com/binaryfunt/electron-seamless-titlebar-tutorial) *(please note: as of 2022 this tutorial is somewhat outdated in terms of E... | 9,247 |
56,355,248 | Is there anyway to merge npz files in python. In my directory I have output1.npz and output2.npz.
I want a new npz file that merges the arrays from both npz files. | 2019/05/29 | [
"https://Stackoverflow.com/questions/56355248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443944/"
] | use `numpy.load('output1.npz')` and `numpy.load('output2.npz')` to load both files as array a1,a2. Then use `a3 =[*a1,*a2]` to merge them. Finally, output via `numpy.savez('output.npz',a3)` | If you have 3 npz files ('Data\_chunk1.npz', 'Data\_chunk2.npz' and 'Data\_chunk3.npz'), all containing the same number of arrays (in my case 7 different arrays), then you can do
```
import numpy as np
# Load the 3 files
data_1 = np.load('Data_chunk1.npz')
data_2 = np.load('Data_chunk2.npz')
data_3 = np.load('Data_ch... | 9,253 |
8,165,086 | I'm learning Python using [Learn Python The Hard Way](http://learnpythonthehardway.org/). It is very good and efficient but at one point I had a crash. I've searched the web but could not find an answer.
Here is my question:
One of the exercises tell to do this:
```
from sys import argv
script, filename = argv
```
... | 2011/11/17 | [
"https://Stackoverflow.com/questions/8165086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1051438/"
] | ```
script, filename = argv
```
This is [unpacking the sequence](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences) `argv`. The first element goes into `script`, and the second element goes into `filename`. In general, this can be done with any iterable, as long as there exactly as many variabl... | `Unexpected character after line continuation character` means that you have split a command in two lines using the continuation character `\` (see [this question](https://stackoverflow.com/questions/53162/how-can-i-do-a-line-break-line-continuation-in-python)) but added some characters (e.g. a white space) after it.
... | 9,255 |
61,833,460 | I am creating a program that calculates the optimum angles to fire a projectile from a range of heights and a set initial velocity. Within the final equation I need to utilise, there is an inverse sec function present that is causing some troubles.
I have imported math and attempted to use asec(whatever) however it se... | 2020/05/16 | [
"https://Stackoverflow.com/questions/61833460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13553134/"
] | Let's say we're looking for real number *x* whose arcsecant is angle *θ*. Then we have:
```
θ = arcsec(x)
sec(θ) = x
1 / cos(θ) = x
cos(θ) = 1 / x
θ = arccos(1/x)
```
So with this reasoning, you can write your arcsecant function as:
```
from math import acos
def asec(x):
return acos(1/x)
``` | If you can try of inverse of sec then it will be same as
```
>>>from mpmath import *
>>> asec(-1)
mpf('3.1415926535897931')
```
Here are the link in where you can better understand - [<http://omz-software.com/pythonista/sympy/modules/mpmath/functions/trigonometric.html]> | 9,257 |
4,673,373 | I would like to put some logging statements within test function to examine some state variables.
I have the following code snippet:
```
import pytest,os
import logging
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
###########################################################################... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | Using `pytest --log-cli-level=DEBUG` works fine with pytest (tested from 6.2.2 to 7.1.1)
Using `pytest --log-cli-level=DEBUG --capture=tee-sys` will also print `stdtout`. | If you use `vscode`, use following config, assuming you've installed
**Python official plugin** (`ms-python.python`) for your python project.
`./.vscode/setting.json` under your proj
```json
{
....
"python.testing.pytestArgs": ["-s", "src"], //here before discover-path src
"python.testing.unittestEnabled": fals... | 9,260 |
36,261,398 | The following program is from a book of python. In this code, count is first set to 0 and then `while True` is used. In the book I read that zeros and empty strings are evaluated as False while all the other values are evaluated as True. If that is the case then how the program executes the while loop? wouldn't the cou... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36261398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6014533/"
] | If you evaluate
```
if count: # and count is zero
break
```
then sure - the loop will break immediately.
But you are evaluating this expression:
```
if count > 10: # 0 > 10
```
which is `False`, so you won't break on the first iteration. | If you changed `while True:` to `while count:`, your assumption would indeed be correct | 9,270 |
2,440,799 | when I use MySQLdb get this message:
```
/var/lib/python-support/python2.6/MySQLdb/__init__.py:34: DeprecationWarning: the sets module is deprecated from sets import ImmutableSet
```
I try filter the warning with
```
import warnings
warnings.filterwarnings("ignore", message="the sets module is deprecated from se... | 2010/03/14 | [
"https://Stackoverflow.com/questions/2440799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348081/"
] | From [python documentation](http://docs.python.org/library/warnings.html#temporarily-suppressing-warnings): you could filter your warning this way, so that if other warnings are caused by an other part of your code, there would still be displayed:
```
import warnings
with warnings.catch_warnings():
warnings.simple... | What release of MySQLdb are you using? I think the current one (1.2.3c1) should have it fixed see [this bug](http://sourceforge.net/tracker/index.php?func=detail&aid=2156977&group_id=22307&atid=374932) (marked as fixed as of Oct 2008, 1.2 branch). | 9,278 |
15,801,447 | I'm building an installation EXE for my project using setuptool's bdist\_wininst. However, I've found that when I actually run said installer on a Win7-64bit machine w/ Python 2.7.3, I get a Runtime Error that looks like this: <http://i.imgur.com/8osT3.jpg>. (only the 64 bit installer against python-2.7 64-bit; the 32-... | 2013/04/04 | [
"https://Stackoverflow.com/questions/15801447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182284/"
] | Maybe you have to create the executable specifically for the x64?
This is the command you would have to run:
```
python setup.py build --plat-name=win-amd64
```
More information can be found here:
<http://docs.python.org/2/distutils/builtdist.html#cross-compiling-on-windows> | Maybe a Visual C++ Redistributable Package is missing or corrupt, try (re)install Microsoft Visual C++ 2008 SP1/2010 Redistributable Package (x64) or any other version. | 9,279 |
51,987,427 | I've got working code below. Currently I'm pulling data from sav files, exporting it to a csv file, and then plotting this data. It looks good, but I'd like to zoom in on it and I'm not entirely sure how to do it. This is because my time is listed in the following format:
```
20141107B205309Y
```
There are both lett... | 2018/08/23 | [
"https://Stackoverflow.com/questions/51987427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10236830/"
] | If your data set is consistent then pandas can trim columns for you. Checkout <https://pandas.pydata.org/pandas-docs/stable/text.html>. You can split using 'B' character. After that convert the column into a date.
You can convert a series to date using [How do I convert dates in a Pandas data frame to a 'date' data typ... | Maybe try converting your s["time"] into a list of datetime objects instead of string.
```
from datetime import datetime
date_list = [datetime.strptime(d, '%Y%m%dB%H%M%SY') for d in s["time"]]
time=np.asarray(date_list)
```
Here str objects are converted into datetime objects using this format '%Y%m%dB%H... | 9,280 |
24,897,145 | I am using pythons mock.patch and would like to change the return value for each call.
Here is the caveat:
the function being patched has no inputs, so I can not change the return value based on the input.
Here is my code for reference.
```
def get_boolean_response():
response = io.prompt('y/n').lower()
while... | 2014/07/22 | [
"https://Stackoverflow.com/questions/24897145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2434234/"
] | You can assign an [*iterable*](https://docs.python.org/3/glossary.html#term-iterable) to `side_effect`, and the mock will return the next value in the sequence each time it is called:
```
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'ba... | You can also use patch for multiple return values:
```
@patch('Function_to_be_patched', return_value=['a', 'b', 'c'])
```
Remember that if you are making use of more than one patch for a method then the order of it will look like this:
```
@patch('a')
@patch('b')
def test(mock_b, mock_a);
pass
```
as you can ... | 9,281 |
72,221,253 | I was reading python collections's [Counter](https://docs.python.org/3/library/collections.html#counter-objects). It says following:
```
>>> from collections import Counter
>>> Counter({'z': 9,'a':4, 'c':2, 'b':8, 'y':2, 'v':2})
Counter({'z': 9, 'b': 8, 'a': 4, 'c': 2, 'y': 2, 'v': 2})
```
Somehow these printed valu... | 2022/05/12 | [
"https://Stackoverflow.com/questions/72221253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1317018/"
] | In terms of the data stored in a `Counter` object: The data is insertion-ordered as of Python 3.7, because `Counter` is a subclass of the built-in `dict`. Prior to Python 3.7, there was no guaranteed order of the data.
However, the behavior you are seeing is coming from `Counter.__repr__`. We can see from the [source ... | The order [depends on the python version](https://docs.python.org/3/library/collections.html#collections.Counter).
For python < 3.7, there is no guaranteed order, since python 3.7 the order is that of insertion.
>
> Changed in version 3.7: As a dict subclass, Counter inherited the
> capability to remember insertion ... | 9,284 |
70,957,167 | Through Python i'm trying to convert the future date into another format and subtract with current date but it's throwing error.
Python version = Python 3.6.8
```
from datetime import datetime
enddate = 'Thu Jun 02 08:00:00 EDT 2022'
todays = datetime.today()
print ('Tpday =',todays)
Modified_date1 = datetime.strptim... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658186/"
] | Using a `while` loop :
```r
x <- list1
while (inherits(x <- x[[1]], "list")) {}
x
#> Time Series:
#> Start = 1
#> End = 100
#> Frequency = 1
#> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#> [19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#> [37] 37 ... | **base R solution** I've just got the idea for a pretty simple function. It is a `while` loop that runs until the element is not a list.
```
myfun <- function(mylist){
dig_deeper <- TRUE
while(dig_deeper){
mylist<- my_list[[1]]
dig_deeper <- is.list(mylist)
}
return(mylist)
}
```
It works as expected... | 9,285 |
1,922,623 | I am using MySQLdb module of python on FC11 machine. Here, i have an issue. I have the following implementation for one of our requirement:
1. connect to mysqldb and get DB handle,open a cursor, execute a delete statement,commit and then close the cursor.
2. Again using the DB handle above, iam performing a "select" s... | 2009/12/17 | [
"https://Stackoverflow.com/questions/1922623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233901/"
] | I've had the same issue, with the TreeView not scrolling to the selected item.
What I did was, after expanding the tree to the selected TreeViewItem, I called a Dispatcher Helper method to allow the UI to update, and then used the TransformToAncestor on the selected item, to find its position within the ScrollViewer. ... | Jason's ScrollViewer trick is a great way of moving a TreeViewItem to a specific position.
One problem, though: in MVVM you do not have access to the ScrollViewer in the view model. Here is a way to get to it anyway. If you have a TreeViewItem, you can walk up its visual tree until you reach the embedded ScrollViewer:... | 9,295 |
47,043,554 | Suppose we have a dataset like this:
```
X =
6 2 1
-2 4 -1
4 1 -1
1 6 1
2 4 1
6 2 1
```
I would like to get two data from this one having last digit 1 and another having last digit -1.
```
X0 =
-2 4 -1
4 1 -1
```
And,
```
X1 =
6 2 1
1 6 1
2 4 1
6 2 1
```
How can we do this in ... | 2017/10/31 | [
"https://Stackoverflow.com/questions/47043554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Suppose you have an array:
```
>>> arr
array([[ 6, 2, 1],
[-2, 4, -1],
[ 4, 1, -1],
[ 1, 6, 1],
[ 2, 4, 1],
[ 6, 2, 1]])
```
Then simply:
```
>>> mask1 = arr[:, -1] == 1
>>> mask2 = arr[:, -1] == -1
>>> X1 = arr[mask1]
>>> X2 = arr[mask2]
```
Results:
```
>>> X1
array... | You could just use `numpy` and use slicing to access your data e.g.:
```
X[X[:, 2] == 1] # Returns all rows where the third column equals 1
```
or as a complete example:
```
import numpy as np
# Random data set
X = np.zeros((6, 3))
X[:3, 2] = 1
X[3:, 2] = -1
np.random.shuffle(X)
print(X[X[:, 2] == 1])
print('-')... | 9,296 |
4,837,218 | Last night I came across the term called Jython which was kind of new to me so I started reading about it only to add more to my confusion about Python in general. I have never really used Python either. So here is what I am confused about.
1. `Python is implemented in C` - Does that mean that the interpreter was writ... | 2011/01/29 | [
"https://Stackoverflow.com/questions/4837218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568638/"
] | "Python" is the name of the language itself, not of a particular interpreter implementation, just as "C" is the name of a programming language and not of a particular compiler.
"CPython" is an implementation of an interpreter of the Python language written in C. It compiles Python source code to byte code and interpre... | a) Python is a programming language. Interpreters of Python code are implemented using other programming languages like C (PyPy even using Python itself to implement one, I believe).
b) CPython, aka Classic Python, is the reference implementation and is written in C. Jython is a Python interpreter written in Java.
c)... | 9,298 |
46,431,145 | so im a python beginner and i cant find a way to put a input varible in a random like so,
```html
import time
import random
choice = input('easy (max of 100 number), medium(max of 1000) or hard (max of 5000)? Or custom)')
time.sleep(2)
if choice == 'custom':
cus = input(' max number?')
print ('okey dokey!')... | 2017/09/26 | [
"https://Stackoverflow.com/questions/46431145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8677673/"
] | There are multiple things wrong with your code. You're using ('s with print, which suggests you're using python3. This means that when you do `cus = input()`, cus is now a string. You probably want to do `cus = int(input())`
Doing `choice == 'easy' or 'medium' or 'hard' or cus` will always be True; I have no idea why ... | Convert your variable `cus` to an int and pass it as you normally would
```
cuss = random.randrange(0, int(cus))
``` | 9,303 |
7,817,926 | I'm trying to use scapy on win32 python2.7
I've manage to compile all the other dependencies expect this one
can some help in the goal of reaching this executable ?
"dnet-1.12.win32-py2.7.exe"
(I promise to update the this question too and the scapy manual,
[Running Scapy on Windows with Python 2.7](https://stackov... | 2011/10/19 | [
"https://Stackoverflow.com/questions/7817926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459189/"
] | I just called super on the following overridden method of the BaseExpandableListAdapter and since then the notifyDataSetChanged() works.
```
@Override
public void registerDataSetObserver(DataSetObserver observer) {
super.registerDataSetObserver(observer);
}
``` | you can try to additionally call invalidateViews() on your ExpandableListView when refreshing. | 9,304 |
61,038,562 | I'm writing a program where I'm converting a function to prefix and calculate.
```
from pythonds.basic import Stack
def doMath(op, op1, op2):
if op == "*":
return int(op1) * int(op2)
elif op == "/":
return int(op1) / int(op2)
elif op == "+":
return int(op1) + int(op2)
elif ... | 2020/04/05 | [
"https://Stackoverflow.com/questions/61038562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7737188/"
] | When you try:
```
if token in "0123456789":
operandStack.push(token)
```
for `token = 17`, this shall fail since `17` is not in `0123456789`.
So change it to this:
```
try:
if float(token):
operandStack.push(token)
except:
#your code here
```
---
**HOW THIS WORKS:**
When a type of `str`... | Replace `if token in "0123456789"` (checks if `token` is a substring of `"0123456789"`) with `if token.isdigit()` (checks if `token` consists of decimal digits). | 9,309 |
9,816,139 | I've got an old RRD file that was only set up to track 1 year of history. I decided more history would be nice. I did rrdtool resize, and the RRD is now bigger. I've got old backups of this RRD file and I'd like to merge the old data in so that the up-to-date RRD also has the historical data.
I've tried the rrd contri... | 2012/03/22 | [
"https://Stackoverflow.com/questions/9816139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91238/"
] | I ended up putting together a really simple script that works well enough for my case, by examining the existing python script.
<http://gist.github.com/2166343> | Looking at the XML file generated by rrdtool, there is a simple logic error in the Perl script. The elements AVERAGE and are simple enough but the tag is contained within tag with the text inside.
```
<cf> AVERAGE </cf>
<pdp_per_row> 1 </pdp_per_row> <!-- 300 seconds -->
<params>
... | 9,310 |
65,131,966 | Say I have a collection of scripts organized for convenience in a directory structure like so:
```
root
│ helpers.py
│
├───dir_a
│ data.txt
│ foo.py
│
└───dir_b
data.txt
bar.py
```
`foo.py` and `bar.py` are scripts doing different things, but they both load their distinct `data.txt` the... | 2020/12/03 | [
"https://Stackoverflow.com/questions/65131966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7227829/"
] | I don't think there is a way to have node do what you want. I had a similar where the main project was commonjs but one of the libraries was esm or a library it was using was esm. I don't remember the specific details but it was a royal pain.
The basic work around is to use `esm` to `import` the library giving you iss... | I had the same issue and I used single quotation for multi-value args like `--exec' to solve it.
```
nodemon --watch 'src/**/*' -e ts,tsx --exec 'ts-node ./src/index.ts'
``` | 9,315 |
8,587,633 | I'm trying to write a python script for BusyBox on ESXi with mail functionality. It runs Python 2.5 with some libraries missing (i.e. the smtplib). I downloaded Python2.5 sources and copied the lib-folder to ESXi. Now I am trying to import the smtplib via "import lib.smtplib" but Python says:
```
Traceback (most recen... | 2011/12/21 | [
"https://Stackoverflow.com/questions/8587633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/921051/"
] | Trying to install generic applications on an appliance or custom OS is always fun.
Just a guess, but it may be that the email lib is a compiled C module - i.e. not pure python.
I would try use libraries that are as completely python with no compiled code - I don't know if there are pure python versions of the librari... | I don't know anything about BusyBox or ESXi - therefore this may be more of a suggestion than an answer, but you might consider using a email service that supports an HTTP or RESTful API - such as [MailGun](http://documentation.mailgun.net/wrappers.html#python). They have a free plan for up to 200 emails a day, so it m... | 9,316 |
16,833,285 | I have searched for an answer to this but the related solutions seem to concern `'print'`ing in the interpreter.
I am wondering if it is possible to print (physically on paper) python code in color from IDLE?
I have gone to: `File > Print Window` in IDLE and it seems to just print out a black and white version withou... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16833285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063287/"
] | Use the IDLE extension called IDLE2HTML.py (search for this).
This lets IDLE print to an HTML file that has color in its style sheet.
Then save the HTML file to a PDF (the color will still be there). | I had the same problem and opened the py file into Visual Studio Code, then simply copied (Ctrl A / Ctrl C) and pasted the text (Ctrl V) into a Microsoft editor such as Word or RTF, or even outlook. The colors stay, including when printing.
Note that in order to avoid the night mode set as a default in VS Code, go to ... | 9,317 |
24,520,133 | I'd like to download a series of pdf files from my intranet. I'm able to see the files in my web browser without issue, but when trying to automate the pulling of the file via python, I run into problems. After talking through the proxy set up at my office, I can download files from the internet quite easily with this ... | 2014/07/01 | [
"https://Stackoverflow.com/questions/24520133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3746982/"
] | Installing openers into urllib2 doesn't affect requests. You need to use requests' own support for proxies. It should be enough to pass them in the `proxies` argument to `get`, or you can set the `HTTP_PROXY` and `HTTPS_PROXY` environment variables. See <http://docs.python-requests.org/en/latest/user/advanced/#proxies>... | Have you tried not using the proxy to download your files when it's on the intranet?
You could try something like this in python2
```
from urllib2 import urlopen
url = 'http://intranet/myfile.pdf'
with open(local_filename, 'wb') as f:
f.write(urlopen(url).read())
``` | 9,327 |
25,643,943 | I am trying to write a python program in which the user inputs the polynomial and it calculates the derivative. My current code is:
```
print ("Derviatives: ")
k5 = raw.input("Enter 5th degree + coefficent: ")
k4 = raw.input("Enter 4th degree + coefficent: ")
k3 = raw.input("Enter 3rd degree + coefficent: ... | 2014/09/03 | [
"https://Stackoverflow.com/questions/25643943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3953943/"
] | OK, use `raw_input` instead of `raw.input`. It is builtin, as is `int`, so nothing needs importing. When converting to a integer (`int`), you need to assign the result, or nothing will change. You can chain the functions, and use `k5 = int(raw_input("prompt.. "))`. Also, as pointed out by Evert, variable names cannot b... | I see the following issues with your code:
1. Variable names can't start with a digit: `1in`
2. You have undefined variable `Y`. I suppose you want to compare with a string literal, so write `"Y"` instead.
3. Parentheses aren't needed in python's `if` operators, but a trailing colon is necessary. Same goes for `else`.... | 9,328 |
52,651,733 | I try to find refresing elements (time minute) on the webpage. My code worked only for simple text earlier. Now I use *Ctrl+Shift+I* and point out my element and *"Copy Xpath"*.
Also, I have Chrome extension *"XPath helper"* and tried to do that with it one. There is more longer XPath, than in my code below. And it d... | 2018/10/04 | [
"https://Stackoverflow.com/questions/52651733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10290047/"
] | You should set `Tag` instead of assigning an id to the dynamic created view.
```
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflator=LayoutInflater.from(this.mContext);
View layout=inflator.inflate(R.layout.activity_main, parent, false);
ImageView imageView;
... | The position effectively acts as an id. Or I have missed the point? | 9,330 |
43,207,159 | first of all, i´m pretty new to Python. I also searched for a solution, but i guess the usual approach (subprocess.popen) won´t work in my case.
I have to pass arguments to a listener in an already running python script without starting the script over and over again. There is an example how to pass a message to a lcd... | 2017/04/04 | [
"https://Stackoverflow.com/questions/43207159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5607983/"
] | Once a process is running it won't re-evaluate its command line arguments. You need other ways to communicate with it. This is colloquially called *inter-process communication* (IPC), and there are several ways to achieve it. Here are a few:
* Files
* Pipes (on platforms that support them)
* Shared memory
* Socket com... | You can use some sort of messaging library that will allow you to communicate between processes. [ZeroMQ](http://www.zeromq.org/bindings:python) is a good option, and has python bindings. | 9,331 |
69,259,654 | When I debug, I often find it useful to print a variable's name and contents.
```python
a = 5
b = 7
print("a: "+str(a)+"\n b: "+str(b))
```
I want to write a function that achieves this. So far, I have the following function:
```python
def dprint(varslist, *varnames):
string = [var+": "+str(varslist[var]) for v... | 2021/09/20 | [
"https://Stackoverflow.com/questions/69259654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16337951/"
] | Use [`sys._getframe`](https://docs.python.org/3/library/sys.html#sys._getframe):
>
> Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack, ValueError is raised. The default for depth is ... | In Python you can debug a program calling the `breakpoint` built-in function. | 9,332 |
3,966,146 | On our production server we need to split 900k images into different dirs and update 400k rows (MySQL with InnoDB engine). I wrote a python script which goes through next steps:
1. Select small chunk of data from db (10 rows)
- Make new dirs
- Copy files to the created dirs and rename it
- Update db (there are some tr... | 2010/10/19 | [
"https://Stackoverflow.com/questions/3966146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/228012/"
] | What I recommend.
1. Add an `isProcessed` column to your table.
2. Make your script work on a chunk of, say, 1k rows for the first run (of course select only rows that are not processed).
3. Benchmark it.
4. Adjust the chunk size if needed.
5. Build another script that calls this one at intervals.
Don't forget to ad... | ```
db_data = db.query('''
SELECT id AS news_id, image AS src_filename
FROM emd_news
ORDER BY id ASC
LIMIT %s, %s''', offset, LIMIT_ROW_COUNT)
# Why is there any code here at all? If there's no data, why proceed?
if not db_data: break
``` | 9,333 |
32,506,956 | I am doing ex47 in Learning Python the Hard W[enter link description here](http://learnpythonthehardway.org/book/ex47.html)ay.
My problem here is that I am unable to import a module `from ex47.game.py import Room` from the other file in the following code:
```
from nose.tools import *
from ex47.game.py import Room
... | 2015/09/10 | [
"https://Stackoverflow.com/questions/32506956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427176/"
] | I just went through this exercises right now and since I wanted a bit more explanation I've searched on the internet and found this post... hence my late response.. but I hope this helps if someone else encounter this problem.
He is not really clear about the structure of your Directory. So you should have a **ex47** ... | `export PYTHONPATH=.` adds current directory to the list of paths that python will search when looking for a module.
That is, current directory at the time of the search, not the time you enter the line.
But, as you run your programe from `skeleton`, that will make python search for `ex47.game` in the `skeleton` direc... | 9,335 |
71,640,992 | I have a list of headings and subheadings of a document.
```
test_list = ['heading', 'heading','sub-heading', 'sub-heading', 'heading', 'sub-heading', 'sub-sub-heading', 'sub-sub-heading', 'sub-heading', 'sub-heading', 'sub-sub-heading', 'sub-sub-heading','sub-sub-heading', 'heading']
```
I want to assign unique ind... | 2022/03/27 | [
"https://Stackoverflow.com/questions/71640992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9669200/"
] | Those ghosts updates are a known, long standing issue, as evidenced by [this](https://github.com/hashicorp/terraform-provider-aws/issues/18311) still open, 3 year old issue on GH without a solution.
You can try updating your TF, as 0.13 is a very old version. You can also setup [ignore\_changes](https://www.terraform.... | I encountered a similar thing when upgrading Aurora mysql from 5.6 to 5.7: `log_output` re-appeared in every plan output.
However, the configured value in the default paramater group changed from 5.6 to 5.7 (from TABLE to FILE). I suspect since there was no change, AWS API returns empty, TF state is not updated, repea... | 9,337 |
70,078,645 | I have written the following python code to read in XYZ data as CSV and then grid to a GTiff format.
When I run the code I am getting no errors.
However, after trying to debug, I added some print statements and noticed that the functions aren't actually being called.
How can I run this script so that it all complete... | 2021/11/23 | [
"https://Stackoverflow.com/questions/70078645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15310475/"
] | Use
```
if __name__ == "__main__":
app = gdal_toolbox(kwargs)
app.run()
```
or
```
if __name__ == "__main__":
gdal_toolbox(kwargs).run()
```
Use thease codes at the end of your script.
And the solution is :
```
class gdal_toolbox:
## CONSTANTS ##
def __init__( self, kwargs ):
prin... | It seems like you are not executing anything in this piece of code, just defining class and functions within it, right? | 9,338 |
58,822,095 | I have a problem using pyarrow.orc module in Anaconda on Windows 10.
```
import pyarrow.orc as orc
```
throws an exception:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\apps\Anaconda3\envs\ws\lib\site-packages\pyarrow\orc.py", line 23, in <module>
import pyarrow._orc a... | 2019/11/12 | [
"https://Stackoverflow.com/questions/58822095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12361891/"
] | The ORC reader is not supported at all on Windows and has never been to my knowledge. Apache ORC in C++ is not known to build yet with the Visual Studio C++ compiler. | Bottom line up front,
I had the same error. This was the solution for me:
```
!pip install pyarrow==0.13.0
```
I'm not sure this is limited to Windows 10, I am getting the same error in AWS Sagemaker in the last few days. This was working fine before, on a previous Sagemaker instance.
Using the Conda Packages menu... | 9,339 |
67,928,883 | I'm working on this REST application in python `Flask` and a driver called `pymongo`. But if someone knows `mongodb` well he/she maybe able to answer my question.
Suppose Im inserting a new document in a collection say `students`. I want to get the whole inserted document as soon as the document is saved in the collec... | 2021/06/10 | [
"https://Stackoverflow.com/questions/67928883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12925831/"
] | Put the data to be inserted into a dictionary variable; on insert, the variable will have the `_id` added by pymongo.
```
from pymongo import MongoClient
db = MongoClient()['mydatabase']
doc = {
"name": "name"
}
db.students.insert_one(doc)
print(doc)
```
prints:
```
{'name': 'name', '_id': ObjectId('60ce419... | Unfortunately, the commenters are correct. The PyMongo pattern doesn't specifically allow for what you are asking. You are expected to just use the inserted\_id from the [result](https://pymongo.readthedocs.io/en/stable/api/pymongo/results.html#pymongo.results.InsertOneResult) and if you needed to get the full object f... | 9,341 |
52,501,105 | I am trying to connect to MSSQL with help of django-pyodbc. I have installed all the required packages like FreeTDS, unixODBC and django-pyodbc. When I connect using tsql and isql I am able to connect:-
```
>tsql -S mssql -U ********* -P ***********
locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default chars... | 2018/09/25 | [
"https://Stackoverflow.com/questions/52501105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034743/"
] | This has to do with the current scope that Rankx evaluates de Aggregation.
Try wrapping your aggregation with CALCULATE, and you probably want the SUM not the MAX:
```
Rank Reseller = RANKX(ALL(ResellerSales), CALCULATE(SUM(ResellerSales[SalesAmount])))
```
You can create a Measure like so, and use it on RANKX, sin... | To rank the [ReSellerkey] by [SalesAmount] you'd want to do something like this:
```
Rank Sales Amount :=
RANKX(
'Table',
'Table'[SalesAmount],
,
ASC,
Dense
)
``` | 9,342 |
42,301,458 | I have a large netcdf file which is three dimensional. I want to replace for the variable `LU_INDEX` in the netcdf file all the values 10 with 2.
I wrote this python script to do so but it does not seem to work.
```
filelocation = 'D:/dataset.nc'
ncdataset = nc.Dataset(filelocation,'r')
lat = ncdataset.v... | 2017/02/17 | [
"https://Stackoverflow.com/questions/42301458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7581459/"
] | You might try [NCO](http://nco.sf.net/nco.html#ncap2)
```
ncap2 -s 'where(LU_INDEX == 10) LU_INDEX=2' in.nc out.nc
``` | I worked it out as follow:
```
import netCDF4 as nc
import numpy as np
pathname = 'D:'
filename = '%s/dataset.nc'%pathname
ncfile = nc.Dataset(filename,'r+')
lu_index = ncfile.variables['LU_INDEX'][:]
I = np.where(lu_index == 10)
lu_index[I] = 2
ncfile.variables['LU_INDEX'][:] = lu_index
filename.close()
print 'conv... | 9,343 |
25,811,202 | I am trying to execute a shell command and kill it using python **signal** module.
I know signals work only with main thread, so I run the Django development server with,
```
python manage.py runserver --nothreading --noreload
```
and it works fine.
But when i deploy the django application with Apache/mod\_wsgi, i... | 2014/09/12 | [
"https://Stackoverflow.com/questions/25811202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2102830/"
] | are you running with DEBUG enabled in setting.py ?
If yes try disabling it to see if the issue persists. | I'm not sure that can be done that easily, or at least not with mod\_wsgi. The decision to thread or not to thread is the sum of build and run time options in both apache and mod\_wsgi, which are both set by default, to threading.
I would point you to the docs about that, but I can only post two links, so I think it's... | 9,345 |
64,512,500 | Arrays of labels of objects and distances to that objects are given. I want to apply knn to find the label of prediction. I want to use `np.bincount` for that. However, I don't understand how to use this.
See some example
```
labels = [[1,1,2,0,0,3,3,3,5,1,3],
[1,1,2,0,0,3,3,3,5,1,3]]
weights= [[0,0,0,0,0,0... | 2020/10/24 | [
"https://Stackoverflow.com/questions/64512500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13184183/"
] | The next solution gives me desired result:
```
labels = [[1,1,2,0,0,3,3,3,5,1,3],
[1,1,2,0,0,3,3,3,5,1,3]]
weights= [[0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,0,1,0,0]]
length = len(labels[0])
lab_weight = np.hstack((labels, weights))
predict = np.apply_along_axis(lambda x: np.bincount(x[:length], ... | The problem with your code is that you attempt to use your
function to **2-D** slices of your array, whereas *apply\_along\_axis*
applies the given function to **1-D** slices.
So your code generates an exception: *ValueError: object of too small
depth for desired array*.
To apply your function to 2-D slices, use a li... | 9,346 |
5,769,382 | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's... | 2011/04/24 | [
"https://Stackoverflow.com/questions/5769382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492336/"
] | Here is a solution that doesn't require code changes:
```
python -m pdb prog.py <prog_args>
(pdb) b 3
Breakpoint 1 at prog.py:3
(pdb) c
...
(pdb) p a
5
(pdb) a=7
(pdb) ...
```
In short:
* start your program under debugger control
* set a break point at a given line of code
* let the program run up to that point
* y... | Not sure what the real question is. Python gives you the 'pdb' debugger (google yourself) and in addition you can add logging and debug output as needed. | 9,347 |
69,486,648 | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of `foo(?: [abc])*`, where `a`, `b`, `c` could only appear once. So:
```
foo a b c
foo b c a
foo a b
foo b
```
would all be valid, b... | 2021/10/07 | [
"https://Stackoverflow.com/questions/69486648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] | I have assumed that the elements of the string can be in any order and appear any number of times. For example, `'a foo'` should match and `'a foo b foo'` should not.
You can do that with a series of alternations employing lookaheads, one for each substring of interest, but it becomes a bit of a dog's breakfast when t... | If the order of the strings doesn't matter, and you want to make sure every string occurs only once, you can turn the list into a set in Python:
```
my_lst = ['a', 'a', 'b', 'c']
my_set = set(lst)
print(my_set)
# {'a', 'c', 'b'}
``` | 9,357 |
2,313,032 | I am trying to create a regex that matches a US state abbreviations in a string using python.
The abbreviation can be in the format:
```
CA
Ca
```
The string could be:
```
Boulder, CO 80303
Boulder, Co
Boulder CO
...
```
Here is what I have, which obviously doesn't work that well. I'm not very good with regular... | 2010/02/22 | [
"https://Stackoverflow.com/questions/2313032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74474/"
] | A simple and reliable way is to have all the states listed:
```
states = ['IA', 'KS', 'UT', 'VA', 'NC', 'NE', 'SD', 'AL', 'ID', 'FM', 'DE', 'AK', 'CT', 'PR', 'NM', 'MS', 'PW', 'CO', 'NJ', 'FL', 'MN', 'VI', 'NV', 'AZ', 'WI', 'ND', 'PA', 'OK', 'KY', 'RI', 'NH', 'MO', 'ME', 'VT', 'GA', 'GU', 'AS', 'NY', 'CA', 'HI', 'IL',... | ```
re.search(r'\b[a-z]{2}\b', subject, re.I)
```
it will find double-letter names of towns, though | 9,367 |
42,244,819 | My objective is to insert a key value pair in a YAML file which might be empty.
For example, my `hiera.yaml` (used in puppet) file contains only three hyphens.
Here is my code:
```
#!/usr/bin/python
import ruamel.yaml
import sys
def read_file(f):
with open(f, 'r') as yaml:
return ruamel.yaml.round_trip_load(y... | 2017/02/15 | [
"https://Stackoverflow.com/questions/42244819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7543970/"
] | If you indeed want to get all the data into a single string you can do it using collect:
```
val rows = df.select("defectDescription").collect().map(_.getString(0)).mkString(" ")
```
You first select the relevant column (so you have just it) and collect it, it would give you an array of rows. the map turns each row ... | ```
val str1 = df.select("defectDescription").collect.mkString(",")
val str = str1.replaceAll("[\\[\\]]","")
```
Another way to do this is as follows:
The 1st line selects the particular columns then collects the subset, collects behaves as:
Collect (Action) - Return all the elements of the dataset as an array at t... | 9,368 |
60,311,694 | I'm taking a look at some parser combinator libraries in Python ([Parsy](https://parsy.readthedocs.io/en/latest/index.html) to be more precise) and I'm currently faced with the following problem, simplified with a minimally working example below:
```py
text = '''
AAAAAAAAAA AAAAAAAA AAAAAAAAAAAAAA
BBBBBBB START THE TE... | 2020/02/20 | [
"https://Stackoverflow.com/questions/60311694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4614840/"
] | There was an issue related to the routing in the application. I had a parser inside the controller that was used for directing correct routes between a route "aluno" with first Param.
Once I had taken the route with no params and put it first at the controller, there was no need anymore for the parser, and the issue w... | Please check your method result type of controller
Change this:
```
@Contoller()
export class MyController {
// ...
async myMethod() {
return {}
}
}
```
to:
```
@Contoller()
export class MyController {
// ...
async myMethod():Promise<any> {
return {}
}
}
``` | 9,373 |
27,708,882 | I have two Anaconda installations on my computer. The first one is based on Python 2.7 and the other is based on Python 3.4. The default Python version is the 3.4 though. What is more, I can start Python 3.4 either by typing **/home/eualin/.bin/anaconda3/bin/python** or just **python**. I can do the same but for Python... | 2014/12/30 | [
"https://Stackoverflow.com/questions/27708882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706838/"
] | You don't need multiple `anaconda` distributions for different python versions. I would suggest keeping only one.
`conda` basically lets you create environments for your different needs.
`conda create -n myenv python=3.3` creates a new environment named `myenv`, which works with a python3.3 interpreter.
`source acti... | Using virtualenv is your best option as @Dettorer has mentioned.
I found this method of installing and using virtualenv the most useful.
Check it out:
[Proper way to install virtualenv](https://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python) | 9,374 |
18,730,612 | I want to run both a websocket and a flash policy file server on port 80 using Tornado. The reason for not wanting to run a server on the default port 843 is that it's often closed in corporate networks. Is it possible to do this and if so, how should I do this?
I tried the following structure, which does not seem to ... | 2013/09/10 | [
"https://Stackoverflow.com/questions/18730612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2259361/"
] | the new formula become L= P / [(1+c)^n-1]/[c(1+c)^n]
let me work this out for you. To add L to the other side you have to multiple by 1/L. so now the left side of the equation is P/L. to get rid of the P you have to multiple 1/P. now leaving the L alone makes the L into a ratio of 1/L. To get rid of the one you have ... | Your monthly payment isn't being calculated correctly in the code that isn't working properly. If you look at it, you'll see that you're not factoring in your debts whatsoever.
I'm not sure exactly how you're choosing to calculate the monthly payment, but my guess is you need to subtract your debts from your income an... | 9,377 |
25,514,378 | This sample python program:
```
document='''<p>This is <i>something</i>, it happens
in <b>real</b> life</p>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(document)
print(soup.prettify())
```
produces the following output:
```
<html>
<body>
<p>
This is
<i>
something
</i>
, i... | 2014/08/26 | [
"https://Stackoverflow.com/questions/25514378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538701/"
] | Beautiful Soup's `.prettify()` method is defined as outputting each tag on its own line (<http://www.crummy.com/software/BeautifulSoup/bs4/doc/index.html#pretty-printing>). If you want something else you'll need to make it yourself by walking the parse tree. | As previous comments and thebjorn stated, BeautifulSoup's definition of pretty html is with each tag on it's own line, however, to deal with some of your problems with the spacing of , and such, you can collapse it first like so:
```
from bs4 import BeautifulSoup
document = """<p>This is <i>something</i>, it happens... | 9,379 |
14,281,469 | So I've got these huge text files that are filled with a single comma delimited record per line. I need a way to process the files line by line, removing lines that meet certain criteria. Some of the removals are easy, such as one of the fields is less than a certain length. The hardest criteria is that these lines all... | 2013/01/11 | [
"https://Stackoverflow.com/questions/14281469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/947756/"
] | Reading all the rows in is not ideal, because you need to store the whole lot in memory.
Instead you could read line by line, writing out the records that you want to keep as you go. You could keep a cache of the rows you've hit previously, bounded to be within 15 seconds of the current program. In very rough pseudo-c... | You might read the file and output just the line numbers to be deleted (to be sorted and used in a separate pass.) Your hash map could then contain just the minimum data needed plus the line number. This could save a lot of memory if the data needed is small compared to the line size. | 9,381 |
32,054,066 | I'm using the [`websockets`](https://github.com/aaugustin/websockets) library to create a websocket server in Python 3.4. Here's a simple echo server:
```python
import asyncio
import websockets
@asyncio.coroutine
def connection_handler(websocket, path):
while True:
msg = yield from websocket.recv()
... | 2015/08/17 | [
"https://Stackoverflow.com/questions/32054066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1668646/"
] | **TL;DR** Use [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future) to run several coroutines concurrently.
---
>
> Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? Tornado?
>
>
>
No, you don't need any other ... | Same issue, can hardly got solution until I saw the perfect sample here: <http://websockets.readthedocs.io/en/stable/intro.html#both>
```
done, pending = await asyncio.wait(
[listener_task, producer_task],
return_when=asyncio.FIRST_COMPLETED) # Important
```
So, I can handle multi coroutine tasks s... | 9,382 |
27,812,789 | I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.
But when I debug this function:
```
def popall(self):
objs = self.curstack
self.curstack = []
return objs
```
It looks like some kind of copy is taking place. After this function runs obis... | 2015/01/07 | [
"https://Stackoverflow.com/questions/27812789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444342/"
] | It doesn't copy anything. It's just that assigning to `self.curstack` does not modify whatever `self.curstack` used to refer to. It just makes `self.curstack` refer to something else.
Think of it this way. `self.curstack` points to some stuff. With `objs = self.curstack` you make `objs` point to that same stuff. With ... | Python uses references everywhere. So your code works like this:
```
objs = self.curstack
```
Now `objs` points to whatever `curstack` was.
```
self.curstack = []
```
Now `curstack` points to an empty list. `objs` is unchanged, and points to the old `curstack`.
```
return objs
```
You return `objs`, which is t... | 9,388 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.